repo
string
commit
string
message
string
diff
string
360/360-Engine-for-Android
e5214fd7825e0e8f8446937c067da62e2ec0e521
PAND-2301: Added a persistent cache of MyIdentities.
diff --git a/src/com/vodafone360/people/database/DatabaseHelper.java b/src/com/vodafone360/people/database/DatabaseHelper.java index ec1b2e7..81bdac7 100644 --- a/src/com/vodafone360/people/database/DatabaseHelper.java +++ b/src/com/vodafone360/people/database/DatabaseHelper.java @@ -1,813 +1,815 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.database; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Timer; import java.util.TimerTask; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import android.os.Handler; import android.os.Message; import android.util.Log; import com.vodafone360.people.MainApplication; import com.vodafone360.people.Settings; import com.vodafone360.people.database.tables.ActivitiesTable; import com.vodafone360.people.database.tables.ContactChangeLogTable; import com.vodafone360.people.database.tables.ContactDetailsTable; import com.vodafone360.people.database.tables.ContactGroupsTable; import com.vodafone360.people.database.tables.ContactSourceTable; import com.vodafone360.people.database.tables.ContactSummaryTable; import com.vodafone360.people.database.tables.ContactsTable; import com.vodafone360.people.database.tables.ConversationsTable; import com.vodafone360.people.database.tables.GroupsTable; import com.vodafone360.people.database.tables.MePresenceCacheTable; +import com.vodafone360.people.database.tables.MyIdentitiesCacheTable; import com.vodafone360.people.database.tables.NativeChangeLogTable; import com.vodafone360.people.database.tables.PresenceTable; import com.vodafone360.people.database.tables.StateTable; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.database.tables.ContactChangeLogTable.ContactChangeInfo; import com.vodafone360.people.database.tables.ContactDetailsTable.Field; import com.vodafone360.people.datatypes.ActivityItem; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactDetail; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.PublicKeyDetails; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.ContactDetail.DetailKeyTypes; import com.vodafone360.people.datatypes.ContactDetail.DetailKeys; import com.vodafone360.people.engine.contactsync.ContactChange; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.engine.presence.PresenceDbUtils; import com.vodafone360.people.service.PersistSettings; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.interfaces.IPeopleService; import com.vodafone360.people.utils.CloseUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.StringBufferPool; import com.vodafone360.people.utils.ThumbnailUtils; import com.vodafone360.people.utils.WidgetUtils; /** * The main interface to the client database. * <p> * The {@link #DATABASE_VERSION} field must be increased each time any change is * made to the database schema. This includes any changes to the table name or * fields in table classes and any change to persistent settings. * <p> * All database functionality should be implemented in one of the table Table or * Utility sub classes * * @version %I%, %G% */ public class DatabaseHelper extends SQLiteOpenHelper { private static final String LOG_TAG = Settings.LOG_TAG + "Database"; /** * The name of the database file. */ private static final String DATABASE_NAME = "people.db"; /** * The name of the presence database file which is in memory. */ public static final String DATABASE_PRESENCE = "presence1_db"; /** * Contains the database version. Must be increased each time the schema is * changed. **/ private static final int DATABASE_VERSION = 63; private final List<Handler> mUiEventCallbackList = new ArrayList<Handler>(); private Context mContext; private boolean mMeProfileAvatarChangedFlag; private boolean mDbUpgradeRequired; /** * Time period in which the sending of database change events to the UI is delayed. * During this time period duplicate event types are discarded to avoid clogging the * event queue (esp. during first time sync). */ private static final long DATABASE_EVENT_DELAY = 1000; // ms /** * Timer to implement a wait before sending database change events to the UI in * order to prevent clogging the queue with duplicate events. */ private final Timer mDbEventTimer = new Timer(); /** * SELECT DISTINCT LocalId FROM NativeChangeLog UNION SELECT DISTINCT * LocalId FROM ContactDetails WHERE NativeSyncId IS NULL OR NativeSyncId <> * -1 ORDER BY 1 */ private final static String QUERY_NATIVE_SYNCABLE_CONTACTS_LOCAL_IDS = NativeChangeLogTable.QUERY_MODIFIED_CONTACTS_LOCAL_IDS_NO_ORDERBY + " UNION " + ContactDetailsTable.QUERY_NATIVE_SYNCABLE_CONTACTS_LOCAL_IDS + " ORDER BY 1"; /** * Datatype holding a database change event. This datatype is used to collect unique * events for a certain period before sending them to the UI to avoid clogging of the * event queue. */ private class DbEventType { @Override public boolean equals(Object o) { boolean isEqual = false; if (o instanceof DbEventType) { DbEventType event = (DbEventType) o; if ( (event.ordinal == this.ordinal) &&(event.isExternal == this.isExternal)) { isEqual = true; } } return isEqual; } int ordinal; boolean isExternal; } /** * List of database change events which needs to be sent to the UI as soon as the a * certain amount of time has passed. */ private final List<DbEventType> mDbEvents = new ArrayList<DbEventType>(); /** * Timer task which implements the actualy sending of all stored database change events * to the UI. */ private class DbEventTimerTask extends TimerTask { public void run() { synchronized (mDbEvents) { for (DbEventType event:mDbEvents ) { fireEventToUi(ServiceUiRequest.DATABASE_CHANGED_EVENT, event.ordinal, (event.isExternal ? 1 : 0), null); } mDbEvents.clear(); } } }; /** * Used for passing server contact IDs around. */ public static class ServerIdInfo { public Long localId; public Long serverId; public Long userId; } /** * Used for passing contact avatar information around. * * @see #fetchThumbnailUrls */ public static class ThumbnailInfo { public Long localContactId; public String photoServerUrl; } /** * An instance of this enum is passed to database change listeners to define * the database change type. */ public static enum DatabaseChangeType { CONTACTS, ACTIVITIES, ME_PROFILE, ME_PROFILE_PRESENCE_TEXT } /*** * Public Constructor. * * @param context Android context */ public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mContext = context; /* * // Uncomment the next line to reset the database // * context.deleteDatabase(DATABASE_NAME); // copyDatabaseToSd(); */ } /** * Constructor. * * @param context the Context where to create the database * @param name the name of the database */ public DatabaseHelper(Context context, String name) { super(context, name, null, DATABASE_VERSION); mContext = context; } /** * Called the first time the database is generated to create all tables. * * @param db An open SQLite database object */ @Override public void onCreate(SQLiteDatabase db) { try { ContactsTable.create(db); ContactDetailsTable.create(db); ContactSummaryTable.create(db); StateTable.create(db); ContactChangeLogTable.create(db); NativeChangeLogTable.create(db); GroupsTable.create(mContext, db); ContactGroupsTable.create(db); ContactSourceTable.create(db); ActivitiesTable.create(db); ConversationsTable.create(db); } catch (SQLException e) { LogUtils.logE("DatabaseHelper.onCreate() SQLException: Unable to create DB table", e); } } /** * Called whenever the database is opened. * * @param db An open SQLite database object */ @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); // Adding the creation code for the MePresenceCacheTable here because this older // versions of the client do not contain this table MePresenceCacheTable.create(db); db.execSQL("ATTACH DATABASE ':memory:' AS " + DATABASE_PRESENCE + ";"); PresenceTable.create(db); + MyIdentitiesCacheTable.create(db); // will be created if not existing } /*** * Delete and then recreate a newer database structure. Note: Only called * from tests. * * @param db An open SQLite database object * @param oldVersion The current database version on the device * @param newVersion The required database version */ // TODO: This is only called from the tests!!!! @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { try { trace(true, "DatabaseHelper.onUpgrade() Upgrading database version from [" + oldVersion + "] to [" + newVersion + "]"); mContext.deleteDatabase(DATABASE_NAME); mDbUpgradeRequired = true; } catch (SQLException e) { LogUtils.logE("DatabaseHelper.onUpgrade() SQLException: Unable to upgrade database", e); } } /*** * Deletes the database and then fires a Database Changed Event to the UI. */ private void deleteDatabase() { trace(true, "DatabaseHelper.deleteDatabase()"); synchronized (this) { getReadableDatabase().close(); mContext.deleteDatabase(DATABASE_NAME); } fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); } /*** * Called when the Application is first started. */ public void start() { SQLiteDatabase mDb = getReadableDatabase(); if (mDbUpgradeRequired) { mDbUpgradeRequired = false; mDb.close(); mDb = getReadableDatabase(); } mMeProfileAvatarChangedFlag = StateTable.fetchMeProfileAvatarChangedFlag(mDb); } /*** * Adds a contact to the database and fires an internal database change * event. * * @param contact A {@link Contact} object which contains the details to be * added * @return SUCCESS or a suitable error code * @see #deleteContact(long) * @see #addContactDetail(ContactDetail) * @see #modifyContactDetail(ContactDetail) * @see #deleteContactDetail(long) * @see #addContactToGroup(long, long) * @see #deleteContactFromGroup(long, long) */ public ServiceStatus addContact(Contact contact) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.addContact() contactID[" + contact.contactID + "] nativeContactId[" + contact.nativeContactId + "]"); } List<Contact> mContactList = new ArrayList<Contact>(); mContactList.add(contact); ServiceStatus mStatus = syncAddContactList(mContactList, true, true); if (ServiceStatus.SUCCESS == mStatus) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); } return mStatus; } /*** * Deletes a contact from the database and fires an internal database change * event. * * @param localContactID The local ID of the contact to delete * @return SUCCESS or a suitable error code * @see #addContact(Contact) * @see #addContactDetail(ContactDetail) * @see #modifyContactDetail(ContactDetail) * @see #deleteContactDetail(long) * @see #addContactToGroup(long, long) * @see #deleteContactFromGroup(long, long) */ public ServiceStatus deleteContact(long localContactID) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.deleteContact() localContactID[" + localContactID + "]"); } if (SyncMeDbUtils.getMeProfileLocalContactId(this) != null && SyncMeDbUtils.getMeProfileLocalContactId(this).longValue() == localContactID) { LogUtils.logW("DatabaseHelper.deleteContact() Can not delete the Me profile contact"); return ServiceStatus.ERROR_NOT_FOUND; } ContactsTable.ContactIdInfo mContactIdInfo = ContactsTable.validateContactId( localContactID, getWritableDatabase()); List<ContactsTable.ContactIdInfo> idList = new ArrayList<ContactsTable.ContactIdInfo>(); idList.add(mContactIdInfo); ServiceStatus mStatus = syncDeleteContactList(idList, true, true); if (ServiceStatus.SUCCESS == mStatus) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); } return mStatus; } /*** * Adds a contact detail to the database and fires an internal database * change event. * * @param detail A {@link ContactDetail} object which contains the detail to * add * @return SUCCESS or a suitable error code * @see #modifyContactDetail(ContactDetail) * @see #deleteContactDetail(long) * @see #addContact(Contact) * @see #deleteContact(long) * @see #addContactToGroup(long, long) * @see #deleteContactFromGroup(long, long) * @throws NullPointerException When detail is NULL */ public ServiceStatus addContactDetail(ContactDetail detail) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.addContactDetail() name[" + detail.getName() + "]"); } if (detail == null) { throw new NullPointerException( "DatabaseHelper.addContactDetail() detail should not be NULL"); } boolean isMeProfile = (SyncMeDbUtils.getMeProfileLocalContactId(this) != null && detail.localContactID != null && detail.localContactID.equals(SyncMeDbUtils .getMeProfileLocalContactId(this))); List<ContactDetail> mDetailList = new ArrayList<ContactDetail>(); mDetailList.add(detail); ServiceStatus mStatus = syncAddContactDetailList(mDetailList, !isMeProfile, !isMeProfile); if (mStatus == ServiceStatus.SUCCESS) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); if (isMeProfile) { WidgetUtils.kickWidgetUpdateNow(mContext); } } return mStatus; } /*** * Modifies an existing contact detail in the database. Also fires an * internal database change event. * * @param detail A {@link ContactDetail} object which contains the detail to * add * @return SUCCESS or a suitable error code * @see #addContactDetail(ContactDetail) * @see #deleteContactDetail(long) * @see #addContact(Contact) * @see #deleteContact(long) * @see #addContactToGroup(long, long) * @see #deleteContactFromGroup(long, long) */ public ServiceStatus modifyContactDetail(ContactDetail detail) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.modifyContactDetail() name[" + detail.getName() + "]"); } boolean isMeProfile = false; // me profile has changed List<ContactDetail> mDetailList = new ArrayList<ContactDetail>(); mDetailList.add(detail); ServiceStatus mStatus = syncModifyContactDetailList(mDetailList, !isMeProfile, !isMeProfile); if (ServiceStatus.SUCCESS == mStatus) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); if (isMeProfile) { WidgetUtils.kickWidgetUpdateNow(mContext); } } return mStatus; } /*** * Deletes a contact detail from the database. Also fires an internal * database change event. * * @param localContactDetailID The local ID of the detail to delete * @return SUCCESS or a suitable error code * @see #addContactDetail(ContactDetail) * @see #modifyContactDetail(ContactDetail) * @see #addContact(Contact) * @see #deleteContact(long) * @see #addContactToGroup(long, long) * @see #deleteContactFromGroup(long, long) */ public ServiceStatus deleteContactDetail(long localContactDetailID) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.deleteContactDetail() localContactDetailID[" + localContactDetailID + "]"); } SQLiteDatabase mDb = getReadableDatabase(); ContactDetail mDetail = ContactDetailsTable.fetchDetail(localContactDetailID, mDb); if (mDetail == null) { LogUtils.logE("Database.deleteContactDetail() Unable to find detail for deletion"); return ServiceStatus.ERROR_NOT_FOUND; } boolean isMeProfile = false; if (mDetail.localContactID.equals(SyncMeDbUtils.getMeProfileLocalContactId(this))) { isMeProfile = true; } List<ContactDetail> mDetailList = new ArrayList<ContactDetail>(); mDetailList.add(mDetail); ServiceStatus mStatus = syncDeleteContactDetailList(mDetailList, true, !isMeProfile); if (ServiceStatus.SUCCESS == mStatus) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); if (isMeProfile) { WidgetUtils.kickWidgetUpdateNow(mContext); } } return mStatus; } /*** * Modifies the server Contact Id and User ID stored in the database for a * specific contact. * * @param localId The local Id of the contact to modify * @param serverId The new server Id * @param userId The new user Id * @return true if successful * @see #fetchContactByServerId(Long, Contact) * @see #fetchServerId(long) */ public boolean modifyContactServerId(long localId, Long serverId, Long userId) { trace(false, "DatabaseHelper.modifyContactServerId() localId[" + localId + "] " + "serverId[" + serverId + "] userId[" + userId + "]"); final SQLiteDatabase mDb = getWritableDatabase(); try { mDb.beginTransaction(); if (!ContactsTable.modifyContactServerId(localId, serverId, userId, mDb)) { return false; } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } return true; } /*** * Sets the Server Id for a contact detail and flags it as synchronized * with the server. * * @param localDetailId The local Id of the contact detail to modify * @param serverDetailId The new server Id * @return true if successful */ public boolean syncContactDetail(Long localDetailId, Long serverDetailId) { trace(false, "DatabaseHelper.modifyContactDetailServerId() localDetailId[" + localDetailId + "]" + " serverDetailId[" + serverDetailId + "]"); SQLiteDatabase mDb = getWritableDatabase(); try { mDb.beginTransaction(); if (!ContactDetailsTable.syncSetServerId(localDetailId, serverDetailId, mDb)) { return false; } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } return true; } /*** * Fetches the user's logon credentials from the database. * * @param details An empty LoginDetails object which will be filled on * return * @return SUCCESS or a suitable error code * @see #fetchLogonCredentialsAndPublicKey(LoginDetails, PublicKeyDetails) * @see #modifyCredentials(LoginDetails) * @see #modifyCredentialsAndPublicKey(LoginDetails, PublicKeyDetails) */ public ServiceStatus fetchLogonCredentials(LoginDetails details) { return StateTable.fetchLogonCredentials(details, getReadableDatabase()); } /*** * Fetches the user's logon credentials and public key information from the * database. * * @param details An empty LoginDetails object which will be filled on * return * @param pubKeyDetails An empty PublicKeyDetails object which will be * filled on return * @return SUCCESS or a suitable error code * @see #fetchLogonCredentials(LoginDetails) * @see #modifyCredentials(LoginDetails) * @see #modifyCredentialsAndPublicKey(LoginDetails, PublicKeyDetails) */ public ServiceStatus fetchLogonCredentialsAndPublicKey(LoginDetails details, PublicKeyDetails pubKeyDetails) { return StateTable.fetchLogonCredentialsAndPublicKey(details, pubKeyDetails, getReadableDatabase()); } /*** * Modifies the user's logon credentials. Note: Only called from tests. * * @param details The login details to store * @return SUCCESS or a suitable error code * @see #fetchLogonCredentials(LoginDetails) * @see #fetchLogonCredentialsAndPublicKey(LoginDetails, PublicKeyDetails) * @see #modifyCredentialsAndPublicKey(LoginDetails, PublicKeyDetails) */ public ServiceStatus modifyCredentials(LoginDetails details) { return StateTable.modifyCredentials(details, getWritableDatabase()); } /*** * Modifies the user's logon credentials and public key details. * * @param details The login details to store * @param pubKeyDetails The public key details to store * @return SUCCESS or a suitable error code * @see #fetchLogonCredentials(LoginDetails) * @see #fetchLogonCredentialsAndPublicKey(LoginDetails, PublicKeyDetails) * @see #modifyCredentials(LoginDetails) */ public ServiceStatus modifyCredentialsAndPublicKey(LoginDetails details, PublicKeyDetails pubKeyDetails) { return StateTable.modifyCredentialsAndPublicKey(details, pubKeyDetails, getWritableDatabase()); } /*** * Remove contact changes from the change log. This will be called once the * changes have been sent to the server. * * @param changeInfoList A list of changeInfoIDs (none of the other fields * in the {@link ContactChangeInfo} object are required). * @return true if successful */ public boolean deleteContactChanges(List<ContactChangeLogTable.ContactChangeInfo> changeInfoList) { return ContactChangeLogTable.deleteContactChanges(changeInfoList, getWritableDatabase()); } /*** * Fetches a setting from the database. * * @param option The option required. * @return A {@link PersistSettings} object which contains the setting data * if successful, null otherwise * @see #setOption(PersistSettings) */ public PersistSettings fetchOption(PersistSettings.Option option) { PersistSettings mSetting = StateTable.fetchOption(option, getWritableDatabase()); if (mSetting == null) { mSetting = new PersistSettings(); mSetting.putDefaultOptionData(); } return mSetting; } /*** * Modifies a setting in the database. * * @param setting A {@link PersistSetting} object which is populated with an * option set to a value. * @return SUCCESS or a suitable error code * @see #fetchOption(com.vodafone360.people.service.PersistSettings.Option) */ public ServiceStatus setOption(PersistSettings setting) { ServiceStatus mStatus = StateTable.setOption(setting, getWritableDatabase()); if (ServiceStatus.SUCCESS == mStatus) { fireSettingChangedEvent(setting); } return mStatus; } /*** * Removes all groups from the database. * * @return SUCCESS or a suitable error code */ public ServiceStatus deleteAllGroups() { SQLiteDatabase mDb = getWritableDatabase(); ServiceStatus mStatus = GroupsTable.deleteAllGroups(mDb); if (ServiceStatus.SUCCESS == mStatus) { mStatus = GroupsTable.populateSystemGroups(mContext, mDb); } return mStatus; } /*** * Fetches Avatar URLs from the database for all contacts which have an * Avatar and have not yet been loaded. * * @param thumbInfoList An empty list where the {@link ThumbnailInfo} * objects will be stored containing the URLs * @param firstIndex The 0-based index of the first item to fetch from the * database * @param count The maximum number of items to fetch * @return SUCCESS or a suitable error code * @see ThumbnailInfo * @see #fetchThumbnailUrlCount() */ public ServiceStatus fetchThumbnailUrls(List<ThumbnailInfo> thumbInfoList, int firstIndex, int count) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.fetchThumbnailUrls() firstIndex[" + firstIndex + "] " + "count[" + count + "]"); } Cursor mCursor = null; try { thumbInfoList.clear(); mCursor = getReadableDatabase().rawQuery( "SELECT " + ContactDetailsTable.TABLE_NAME + "." + ContactDetailsTable.Field.LOCALCONTACTID + "," + Field.STRINGVAL + " FROM " + ContactDetailsTable.TABLE_NAME + " INNER JOIN " + ContactSummaryTable.TABLE_NAME + " WHERE " + ContactDetailsTable.TABLE_NAME + "." + ContactDetailsTable.Field.LOCALCONTACTID + "=" + ContactSummaryTable.TABLE_NAME + "." + ContactSummaryTable.Field.LOCALCONTACTID + " AND " + ContactSummaryTable.Field.PICTURELOADED + " =0 " + " AND " + ContactDetailsTable.Field.KEY + "=" + ContactDetail.DetailKeys.PHOTO.ordinal() + " LIMIT " + firstIndex + "," + count, null); ArrayList<String> urls = new ArrayList<String>(); ThumbnailInfo mThumbnailInfo = null; while (mCursor.moveToNext()) { mThumbnailInfo = new ThumbnailInfo(); if (!mCursor.isNull(0)) { mThumbnailInfo.localContactId = mCursor.getLong(0); } mThumbnailInfo.photoServerUrl = mCursor.getString(1); if (!urls.contains(mThumbnailInfo.photoServerUrl)) { urls.add(mThumbnailInfo.photoServerUrl); thumbInfoList.add(mThumbnailInfo); } } // LogUtils.logWithName("THUMBNAILS:","urls:\n" + urls); return ServiceStatus.SUCCESS; } catch (SQLException e) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(mCursor); } } /*** * Fetches Avatar URLs from the database for all contacts from contactList * which have an Avatar and have not yet been loaded. * * @param thumbInfoList An empty list where the {@link ThumbnailInfo} * objects will be stored containing the URLs * @param contactList list of contacts to fetch the thumbnails for * @return SUCCESS or a suitable error code * @see ThumbnailInfo * @see #fetchThumbnailUrlCount() */ public ServiceStatus fetchThumbnailUrlsForContacts(List<ThumbnailInfo> thumbInfoList, final List<Long> contactList) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.fetchThumbnailUrls()"); } StringBuilder localContactIdList = new StringBuilder(); localContactIdList.append("("); Long localContactId = -1l; for (Long contactId : contactList) { if (localContactId != -1) { localContactIdList.append(","); } localContactId = contactId; localContactIdList.append(contactId); } localContactIdList.append(")"); Cursor cursor = null; try { thumbInfoList.clear(); cursor = getReadableDatabase().rawQuery( "SELECT " + ContactDetailsTable.TABLE_NAME + "." + ContactDetailsTable.Field.LOCALCONTACTID + "," + ContactDetailsTable.Field.STRINGVAL + " FROM " + ContactDetailsTable.TABLE_NAME + " INNER JOIN " + ContactSummaryTable.TABLE_NAME + " WHERE " + ContactDetailsTable.TABLE_NAME + "." + ContactDetailsTable.Field.LOCALCONTACTID + " in " + localContactIdList.toString() + " AND " + ContactSummaryTable.Field.PICTURELOADED + " =0 " + " AND " + ContactDetailsTable.Field.KEY + "=" + ContactDetail.DetailKeys.PHOTO.ordinal(), null); HashSet<String> urlSet = new HashSet<String>(); ThumbnailInfo mThumbnailInfo = null; while (cursor.moveToNext()) { mThumbnailInfo = new ThumbnailInfo(); if (!cursor.isNull(cursor.getColumnIndexOrThrow( diff --git a/src/com/vodafone360/people/database/tables/MyIdentitiesCacheTable.java b/src/com/vodafone360/people/database/tables/MyIdentitiesCacheTable.java new file mode 100755 index 0000000..bfee47b --- /dev/null +++ b/src/com/vodafone360/people/database/tables/MyIdentitiesCacheTable.java @@ -0,0 +1,267 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the Common Development + * and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at + * src/com/vodafone360/people/VODAFONE.LICENSE.txt or + * http://github.com/360/360-Engine-for-Android + * See the License for the specific language governing permissions and + * limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each file and + * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. + * If applicable, add the following below this CDDL HEADER, with the fields + * enclosed by brackets "[]" replaced with your own identifying information: + * Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + * + * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. + * Use is subject to license terms. + */ + +package com.vodafone360.people.database.tables; + +import java.util.ArrayList; + +import android.content.ContentValues; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; + +import com.vodafone360.people.database.DatabaseHelper; +import com.vodafone360.people.datatypes.Identity; +import com.vodafone360.people.datatypes.IdentityCapability; +import com.vodafone360.people.datatypes.IdentityCapability.CapabilityID; + +/** + * The MyIdentitiesCacheTable class implements a persistent cache of the identities that were + * registered by the user. Using it allows to display these identities if the device is restarted + * and no network connection is available. + */ +public class MyIdentitiesCacheTable { + + /** + * The identities cache table name. + */ + public final static String TABLE_NAME = "MyIndentitiesCache"; + + /** + * Capability flag: no capability. + */ + public final static int FLAG_CAPABILITY_NONE = 0x0; + + /** + * Capability flag: chat capability. + */ + public final static int FLAG_CAPABILITY_CHAT = 0x1; + + /** + * Capability flag: mail capability. + */ + public final static int FLAG_CAPABILITY_MAIL = 0x2; + + + /** + * Table fields. + */ + private static enum Fields { + _ID("_id"), + NAME("Name"), + NETWORK_ID("NetworkId"), + USER_NAME("UserName"), + CAPABILITIES("Capabilities"); + + /** + * The name of the field as it appears in the database + */ + private String mField; + + /** + * Constructor + * + * @param field - The name of the field (see list above) + */ + private Fields(String field) { + mField = field; + } + + /** + * @return the name of the field as it appears in the database. + */ + public String toString() { + return mField; + } + } + + /** + * Creates the table in the database. + * + * @param database the database where to create the table + * @return true if creation is successful, false otherwise + */ + public static boolean create(SQLiteDatabase database) { + + DatabaseHelper.trace(true, "MyIdentitiesCacheTable.create()"); + + StringBuffer buffer = new StringBuffer(); + + buffer.append("CREATE TABLE IF NOT EXISTS "); + buffer.append(TABLE_NAME); + buffer.append(" ("); + buffer.append(Fields._ID); + buffer.append(" INTEGER PRIMARY KEY AUTOINCREMENT, "); + buffer.append(Fields.NAME); + buffer.append(" TEXT, "); + buffer.append(Fields.USER_NAME); + buffer.append(" TEXT, "); + buffer.append(Fields.NETWORK_ID); + buffer.append(" TEXT, "); + buffer.append(Fields.CAPABILITIES); + buffer.append(" INTEGER);"); + + try { + + database.execSQL(buffer.toString()); + return true; + } catch(Exception e) { + + DatabaseHelper.trace(true, "MyIdentitiesCacheTable.create() - Exception: "+e); + } + + return false; + } + + /** + * Populates the provided ContentValues object with the Identity data. + * + * Note: the ContentValues object is first cleared before being filled. + * + * @param values the ContentValues object to populate + * @param identity the identity to extract the data from + * @return the provided ContentValues object + */ + private static ContentValues getContentValues(ContentValues values, Identity identity) { + + int capabilities = FLAG_CAPABILITY_NONE; + + values.clear(); + + values.put(Fields.NAME.toString(), identity.mName); + values.put(Fields.USER_NAME.toString(), identity.mUserName); + values.put(Fields.NETWORK_ID.toString(), identity.mNetwork); + + if (identity.mCapabilities != null) { + + for (IdentityCapability cap : identity.mCapabilities) { + + if (cap.mCapability != null) { + + switch(cap.mCapability) { + case chat: + if (cap.mValue) capabilities |= FLAG_CAPABILITY_CHAT; + break; + case mail: + if (cap.mValue) capabilities |= FLAG_CAPABILITY_MAIL; + break; + // TODO: add the other cases when needed + } + } + } + } + + values.put(Fields.CAPABILITIES.toString(), capabilities); + + return values; + } + + /** + * Persists the provided identities into the client database. + * + * @param database the database where to save the values + * @param identities the identities to save + */ + public static void setCachedIdentities(SQLiteDatabase database, ArrayList<Identity> identities) { + + final ContentValues contentValues = new ContentValues(); + + database.delete(TABLE_NAME, null, null); + + for (Identity identity : identities) { + + database.insert(TABLE_NAME, null, getContentValues(contentValues, identity)); + } + } + + /** + * Retrieves the saved identities. + * + * @param database the database where to read the values + * @param identities the identities array to fill + */ + public static void getCachedIdentities(SQLiteDatabase database, ArrayList<Identity> identities) { + + final String[] COLUMNS = { /* 0 */Fields.NAME.toString(), /* 1 */Fields.USER_NAME.toString(), + /* 2 */Fields.NETWORK_ID.toString(), /* 3 */Fields.CAPABILITIES.toString() }; + Cursor cursor = null; + + try { + + cursor = database.query(TABLE_NAME, COLUMNS, null, null, null, null, null); + + while (cursor.moveToNext()) { + + final Identity identity = new Identity(); + final int capabilities = cursor.getInt(3); + + identity.mName = cursor.getString(0); + identity.mUserName = cursor.getString(1); + identity.mNetwork = cursor.getString(2); + identity.mCapabilities = getCapabilities(capabilities); + identities.add(identity); + } + + } catch(Exception e) { + DatabaseHelper.trace(true, "MyIdentitiesCacheTable.getCachedIdentities() - Exception: "+e); + } finally { + if (cursor != null) { + cursor.close(); + cursor = null; + } + } + } + + /** + * Gets an array of IdentityCapability from capability flags. + * + * @param capabilities the capability flags + * @return an array of IdentityCapability + */ + private static ArrayList<IdentityCapability> getCapabilities(int capabilities) { + + ArrayList<IdentityCapability> capabilitiesList = null; + + if (capabilities != FLAG_CAPABILITY_NONE) { + + IdentityCapability cap; + capabilitiesList = new ArrayList<IdentityCapability>(); + + if ((capabilities & FLAG_CAPABILITY_CHAT) == FLAG_CAPABILITY_CHAT) { + cap = new IdentityCapability(); + cap.mCapability = CapabilityID.chat; + cap.mValue = true; + capabilitiesList.add(cap); + } + if ((capabilities & FLAG_CAPABILITY_MAIL) == FLAG_CAPABILITY_MAIL) { + cap = new IdentityCapability(); + cap.mCapability = CapabilityID.chat; + cap.mValue = true; + capabilitiesList.add(cap); + } + } + + return capabilitiesList; + } +} diff --git a/src/com/vodafone360/people/engine/EngineManager.java b/src/com/vodafone360/people/engine/EngineManager.java index d414e0d..244101e 100644 --- a/src/com/vodafone360/people/engine/EngineManager.java +++ b/src/com/vodafone360/people/engine/EngineManager.java @@ -1,579 +1,580 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine; import java.security.InvalidParameterException; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import com.vodafone360.people.MainApplication; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.engine.activities.ActivitiesEngine; import com.vodafone360.people.engine.contactsync.ContactSyncEngine; import com.vodafone360.people.engine.content.ContentEngine; import com.vodafone360.people.engine.groups.GroupsEngine; import com.vodafone360.people.engine.identities.IdentityEngine; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.engine.meprofile.SyncMeEngine; import com.vodafone360.people.engine.presence.PresenceEngine; import com.vodafone360.people.engine.upgrade.UpgradeEngine; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.WorkerThread; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.ResponseQueue; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.utils.LogUtils; /** * EngineManager class is responsible for creating, handling and deletion of * engines in the People client. The EngineManager determine when each engine * should be run based on the engine's next run time or whether there is a * waiting request for that engine. The EngineManager routes received responses * to the appropriate engine. */ public class EngineManager { /** * Identifiers for engines. */ public enum EngineId { LOGIN_ENGINE, CONTACT_SYNC_ENGINE, GROUPS_ENGINE, ACTIVITIES_ENGINE, IDENTITIES_ENGINE, PRESENCE_ENGINE, UPGRADE_ENGINE, CONTENT_ENGINE, SYNCME_ENGINE, UNDEFINED // add ids as we progress } /** * {@link EngineManager} is a singleton, so this is the static reference. */ private static EngineManager sEngineManager; /** * Engine manager maintains a list of all engines in the system. This is a * map between the engine ID and the engine reference. */ private final HashMap<Integer, BaseEngine> mEngineList = new HashMap<Integer, BaseEngine>(); /** * Reference to the {@RemoteService} object which provides * access to the {@link WorkerThread}. */ private RemoteService mService; /** * Engines require access the {@link IEngineEventCallback} interface. * Implements several useful methods for engines such as UI request * complete. */ private IEngineEventCallback mUiEventCallback; /** * @see LoginEngine */ private LoginEngine mLoginEngine; /** * @see UpgradeEngine */ private UpgradeEngine mUpgradeEngine; /** * @see ActivitiesEngine */ private ActivitiesEngine mActivitiesEngine; /** * @see SyncMeEngine */ private SyncMeEngine mSyncMeEngine; /** * @see PresenceEngine */ private PresenceEngine mPresenceEngine; /** * @see IdentityEngine */ private IdentityEngine mIdentityEngine; /** * @see ContactSyncEngine */ private ContactSyncEngine mContactSyncEngine; /** * @see GroupsEngine */ private GroupsEngine mGroupsEngine; /** * @see ContentEngine */ private ContentEngine mContentEngine; /** * Maximum time the run function for an engine is allowed to run before a * warning message will be displayed (debug only) */ private static final long ENGINE_RUN_TIME_THRESHOLD = 3000; /** * Engine Manager Constructor * * @param service {@link RemoteService} reference * @param uiCallback Provides useful engine callback functionality. */ private EngineManager(RemoteService service, IEngineEventCallback uiCallback) { mService = service; mUiEventCallback = uiCallback; } /** * Create instance of EngineManager. * * @param service {@link RemoteService} reference * @param uiCallback Provides useful engine callback functionality. */ public static void createEngineManager(RemoteService service, IEngineEventCallback uiCallback) { sEngineManager = new EngineManager(service, uiCallback); sEngineManager.onCreate(); } /** * Destroy EngineManager. */ public static void destroyEngineManager() { if (sEngineManager != null) { sEngineManager.onDestroy(); sEngineManager = null; } } /** * Get single instance of {@link EngineManager}. * * @return {@link EngineManager} singleton instance. */ public static EngineManager getInstance() { if (sEngineManager == null) { throw new InvalidParameterException("Please call EngineManager.createEngineManager() " + "before EngineManager.getInstance()"); } return sEngineManager; } /** * Add a new engine to the EngineManager. * * @param newEngine Engine to be added. */ private synchronized void addEngine(BaseEngine newEngine) { final String newName = newEngine.getClass().getSimpleName(); String[] deactivatedEngines = SettingsManager .getStringArrayProperty(Settings.DEACTIVATE_ENGINE_LIST_KEY); for (String engineName : deactivatedEngines) { if (engineName.equals(newName)) { LogUtils.logW("DEACTIVATE ENGINE: " + engineName); newEngine.deactivateEngine(); } } if (!newEngine.isDeactivated()) { newEngine.onCreate(); mEngineList.put(newEngine.mEngineId.ordinal(), newEngine); } mService.kickWorkerThread(); } /** * Closes an engine and removes it from the list. * * @param engine Reference of engine by base class {@link BaseEngine} to * close */ private synchronized void closeEngine(BaseEngine engine) { mEngineList.remove(engine.engineId().ordinal()); if (!engine.isDeactivated()) { engine.onDestroy(); } } /** * Called immediately after manager has been created. Starts the necessary * engines */ private synchronized void onCreate() { // LogUtils.logV("EngineManager.onCreate()"); createLoginEngine(); createIdentityEngine(); createSyncMeEngine(); createContactSyncEngine(); createGroupsEngine(); if (SettingsManager.getProperty(Settings.UPGRADE_CHECK_URL_KEY) != null) { createUpgradeEngine(); } createActivitiesEngine(); createPresenceEngine(); createContentEngine(); } /** * Called just before the service is stopped. Shuts down all the engines */ private synchronized void onDestroy() { final int engineCount = mEngineList.values().size(); BaseEngine[] engineList = new BaseEngine[engineCount]; mEngineList.values().toArray(engineList); for (int i = 0; i < engineCount; i++) { closeEngine(engineList[i]); } mLoginEngine = null; mUpgradeEngine = null; mActivitiesEngine = null; mPresenceEngine = null; mIdentityEngine = null; mContactSyncEngine = null; mGroupsEngine = null; mContentEngine = null; } /** * Obtains a reference to the login engine * * @return a reference to the LoginEngine */ public LoginEngine getLoginEngine() { assert mLoginEngine != null; return mLoginEngine; } /** * Create instance of LoginEngine. */ private synchronized void createLoginEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mLoginEngine = new LoginEngine(mService, mUiEventCallback, app.getDatabase()); addEngine(mLoginEngine); } /** * Fetch upgrade engine * * @return UpgradeEngine object */ public UpgradeEngine getUpgradeEngine() { assert mUpgradeEngine != null; return mUpgradeEngine; } /** * Create instance of UpgradeEngine. */ private synchronized void createUpgradeEngine() { mUpgradeEngine = new UpgradeEngine(mService, mUiEventCallback); addEngine(mUpgradeEngine); } /** * Fetch activities engine * * @return a ActivitiesEngine object */ public ActivitiesEngine getActivitiesEngine() { assert mActivitiesEngine != null; return mActivitiesEngine; } /** * Create instance of ActivitiesEngine. */ private synchronized void createActivitiesEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mActivitiesEngine = new ActivitiesEngine(mService, mUiEventCallback, app.getDatabase()); getLoginEngine().addListener(mActivitiesEngine); addEngine(mActivitiesEngine); } /** * Fetch sync me engine, starting it if necessary. * * @return The SyncMeEngine */ public SyncMeEngine getSyncMeEngine() { assert mSyncMeEngine != null; return mSyncMeEngine; } /** * Create instance of SyncMeEngine. */ private synchronized void createSyncMeEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mSyncMeEngine = new SyncMeEngine(mService, mUiEventCallback, app.getDatabase()); addEngine(mSyncMeEngine); } /** * Fetch presence engine * * @return Presence Engine object */ public PresenceEngine getPresenceEngine() { assert mPresenceEngine != null; return mPresenceEngine; } /** * Fetch identity engine * * @return IdentityEngine object */ public IdentityEngine getIdentityEngine() { assert mIdentityEngine != null; return mIdentityEngine; } /** * Fetch content engine * * @return ContentEngine object */ public ContentEngine getContentEngine() { assert mContentEngine != null; return mContentEngine; } /** * Fetch contact sync engine * * @return ContactSyncEngine object */ public ContactSyncEngine getContactSyncEngine() { assert mContactSyncEngine != null; return mContactSyncEngine; } private synchronized void createContactSyncEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mContactSyncEngine = new ContactSyncEngine(mUiEventCallback, app.getDatabase()); addEngine(mContactSyncEngine); } /** * Fetch groups engine * * @return GroupEngine object */ public GroupsEngine getGroupsEngine() { assert mGroupsEngine != null; return mGroupsEngine; } private synchronized void createGroupsEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mGroupsEngine = new GroupsEngine(mService, mUiEventCallback, app.getDatabase()); addEngine(mGroupsEngine); } /** * Create instance of IdentityEngine. */ private synchronized void createIdentityEngine() { - mIdentityEngine = new IdentityEngine(mUiEventCallback); + final MainApplication app = (MainApplication)mService.getApplication(); + mIdentityEngine = new IdentityEngine(mUiEventCallback, app.getDatabase()); ConnectionManager.getInstance().addConnectionListener(mIdentityEngine); addEngine(mIdentityEngine); } /** * Create instance of ContentEngine. */ private synchronized void createContentEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mContentEngine = new ContentEngine(mUiEventCallback, app.getDatabase()); addEngine(mContentEngine); } /** * Create instance of PresenceEngine. */ private synchronized void createPresenceEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mPresenceEngine = new PresenceEngine(mUiEventCallback, app.getDatabase()); ConnectionManager.getInstance().addConnectionListener(mPresenceEngine); getLoginEngine().addListener(mPresenceEngine); addEngine(mPresenceEngine); } /** * Respond to incoming message received from Comms layer. If this message * has a valid engine id it is routed to that engine, otherwise The * {@link EngineManager} will try to get the next response. * * @param source EngineId associated with incoming message. */ public void onCommsInMessage(EngineId source) { BaseEngine engine = null; if (source != null) { engine = mEngineList.get(source.ordinal()); } if (engine != null) { engine.onCommsInMessage(); } else { LogUtils.logE("EngineManager.onCommsInMessage - " + "Cannot dispatch message, unknown source " + source); final ResponseQueue queue = ResponseQueue.getInstance(); queue.getNextResponse(source); } } /** * Run any waiting engines and return the time in milliseconds from now when * this method needs to be called again. * * @return -1 never needs to run, 0 needs to run as soon as possible, * CurrentTime + 60000 in 1 minute, etc. */ public synchronized long runEngines() { long nextRuntime = -1; Set<Integer> e = mEngineList.keySet(); Iterator<Integer> i = e.iterator(); while (i.hasNext()) { int engineId = i.next(); BaseEngine engine = mEngineList.get(engineId); long currentTime = System.currentTimeMillis(); // TODO: Pass mCurrentTime to getNextRunTime() to help with Unit tests long tempRuntime = engine.getNextRunTime(); if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logV("EngineManager.runEngines() " + "engine[" + engine.getClass().getSimpleName() + "] " + "nextRunTime[" + getHumanReadableTime(tempRuntime, currentTime) + "] " + "current[" + getHumanReadableTime(nextRuntime, currentTime) + "]"); } else { if (tempRuntime > 0 && tempRuntime < currentTime) { LogUtils.logD("Engine[" + engine.getClass().getSimpleName() + "] run pending"); } } if (tempRuntime < 0) { if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logV("EngineManager.runEngines() Engine is off, so ignore"); } } else if (tempRuntime <= currentTime) { if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logV("EngineManager.runEngines() Run Engine [" + engine.getClass().getSimpleName() + "] and make sure we check it once more before sleeping"); } /** TODO: Consider passing mCurrentTime to mEngine.run(). **/ engine.run(); nextRuntime = 0; final long timeForRun = System.currentTimeMillis() - currentTime; if (timeForRun > ENGINE_RUN_TIME_THRESHOLD) { LogUtils.logE("EngineManager.runEngines() Engine [" + engine.getClass().getSimpleName() + "] took " + timeForRun + "ms to run"); } if (Settings.ENABLED_PROFILE_ENGINES) { StringBuilder string = new StringBuilder(); string.append(System.currentTimeMillis()); string.append("|"); string.append(engine.getClass().getSimpleName()); string.append("|"); string.append(timeForRun); LogUtils.profileToFile(string.toString()); } } else { if (nextRuntime != -1) { nextRuntime = Math.min(nextRuntime, tempRuntime); } else { nextRuntime = tempRuntime; } if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logV("EngineManager.runEngines() Set mNextRuntime to [" + getHumanReadableTime(nextRuntime, currentTime) + "]"); } } } if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logI("EngineManager.getNextRunTime() Return [" + getHumanReadableTime(nextRuntime, System.currentTimeMillis()) + "]"); } return nextRuntime; } /*** * Display the Absolute Time in a human readable format (for testing only). * * @param absoluteTime Time to convert * @param currentTime Current time, for creating all relative times * @return Absolute time in human readable form */ private static String getHumanReadableTime(long absoluteTime, long currentTime) { if (absoluteTime == -1) { return "OFF"; } else if ((absoluteTime == 0)) { return "NOW"; } else if (absoluteTime >= currentTime) { return (absoluteTime - currentTime) + "ms"; } else { return (currentTime - absoluteTime) + "ms LATE"; } } /** * Resets all the engines. Note: the method will block until all the engines * have performed the reset. */ public void resetAllEngines() { LogUtils.logV("EngineManager.resetAllEngines() - begin"); synchronized (this) { // Entering this block should guarantee that the engines are not running // Propagate the reset event to all engines for (BaseEngine engine : mEngineList.values()) { engine.onReset(); } // Reset engine requests inside this synchronized block to // prevent running the engines at the same time QueueManager.getInstance().clearAllRequests(); } LogUtils.logV("EngineManager.resetAllEngines() - end"); } } diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index f75afb4..6234770 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,957 +1,972 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.identities; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import android.os.Bundle; +import com.vodafone360.people.database.DatabaseHelper; +import com.vodafone360.people.database.tables.MyIdentitiesCacheTable; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.IEngineEventCallback; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Identities; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.ThirdPartyAccount; /** * Engine responsible for handling retrieval and validation of Identities (e.g. * 3rd party/web accounts). The Identities engine can fetch a list of available * accounts, and set required capabilities and validate credentials for * specified accounts. */ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { /** * States for IdentitiesEngine. States are based on the requests that the * engine needs to handle. */ private enum State { IDLE, FETCHING_IDENTITIES, VALIDATING_IDENTITY_CREDENTIALS, SETTING_IDENTITY_STATUS, GETTING_MY_IDENTITIES, GETTING_MY_CHATABLE_IDENTITIES, DELETE_IDENTITY } /** * Mutex for thread synchronisation */ private final Object mMutex = new Object(); /** * Container class for Identity Capability Status request. Consists of a * network, identity id and a filter containing the required capabilities. */ private static class IdentityStatusRequest { private String mNetwork; private String mIdentityId; private String mIdentityStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setIdentityStatus(String status) { mIdentityStatus = status; } } /** * Container class encapsulating an Identity validation request containing: * dry-run flag, network, user-name, password, set of required capabilities. */ private static class IdentityValidateCredentialsRequest { /** Performs a dry run if true. */ private boolean mDryRun; /** Network to sign into. */ private String mNetwork; /** Username to sign into identity with. */ private String mUserName; /** Password to sign into identity with. */ private String mPassword; private Map<String, Boolean> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } /** * * Container class for Delete Identity request. Consist network and identity id. * */ private static class DeleteIdentityRequest { /** Network to delete.*/ private String mNetwork; /** IdentityID which needs to be Deleted.*/ private String mIdentityId; } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mMyIdentityList; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; /** * Maintaining DeleteIdentityRequest so that it can be later removed from * maintained cache. **/ private DeleteIdentityRequest identityToBeDeleted; /** * The hard coded list of capabilities we use to getAvailable~/MyIdentities(): chat and status. */ private final Map<String, List<String>> mCapabilitiesFilter; + + /** + * The DatabaseHelper used to access the client database. + */ + private final DatabaseHelper mDatabaseHelper; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ - public IdentityEngine(IEngineEventCallback eventCallback) { + public IdentityEngine(IEngineEventCallback eventCallback, DatabaseHelper databaseHelper) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; + mDatabaseHelper = databaseHelper; mMyIdentityList = new ArrayList<Identity>(); + // restore cached identities + MyIdentitiesCacheTable.getCachedIdentities(databaseHelper.getReadableDatabase(), + mMyIdentityList); mAvailableIdentityList = new ArrayList<Identity>(); mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; // initialize identity capabilities filter mCapabilitiesFilter = new Hashtable<String, List<String>>(); final List<String> capabilities = new ArrayList<String>(); capabilities.add(IdentityCapability.CapabilityID.chat.name()); capabilities.add(IdentityCapability.CapabilityID.get_own_status.name()); mCapabilitiesFilter.put(Identities.CAPABILITY, capabilities); } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { final ArrayList<Identity> availableIdentityList; synchronized(mAvailableIdentityList) { // make a shallow copy availableIdentityList = new ArrayList<Identity>(mAvailableIdentityList); } if ((availableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return availableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { final ArrayList<Identity> myIdentityList; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } if ((myIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return myIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = getMyThirdPartyChattableIdentities(); // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chattableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chattableIdentities; } /** * * Takes all third party identities that have a chat capability set to true. * * @return A list of chattable 3rd party identities the user is signed in to. If the retrieval identities failed the returned list will be empty. * */ public ArrayList<Identity> getMyThirdPartyChattableIdentities() { final ArrayList<Identity> chattableIdentities = new ArrayList<Identity>(); final ArrayList<Identity> myIdentityList; final int identityListSize; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } identityListSize = myIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = myIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue)) { chattableIdentities.add(identity); break; } } } return chattableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, mCapabilitiesFilter); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, mCapabilitiesFilter); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * TODO: re-factor the method in the way that the UI doesn't pass the Bundle with capabilities * list to the Engine, but the Engine makes the list itself (UI/Engine separation). * * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Delete the given social network. * * @param network Name of the identity, * @param identityId Id of identity. */ public final void addUiDeleteIdentityRequest(final String network, final String identityId) { LogUtils.logD("IdentityEngine.addUiRemoveIdentity()"); DeleteIdentityRequest data = new DeleteIdentityRequest(); data.mNetwork = network; data.mIdentityId = identityId; /**maintaining the sent object*/ setIdentityToBeDeleted(data); addUiRequestToQueue(ServiceUiRequest.DELETE_IDENTITY, data); } /** * Setting the DeleteIdentityRequest object. * * @param data */ private void setIdentityToBeDeleted(final DeleteIdentityRequest data) { identityToBeDeleted = data; } /** * Return the DeleteIdentityRequest object. * */ private DeleteIdentityRequest getIdentityToBeDeleted() { return identityToBeDeleted; } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case GET_MY_IDENTITIES: sendGetMyIdentitiesRequest(); completeUiRequest(ServiceStatus.SUCCESS); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; case DELETE_IDENTITY: executeDeleteIdentityRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to delete the identity as specified . (Request is not issued if there * is currently no connectivity). * * @param data bundled request data containing network and identityId. */ private void executeDeleteIdentityRequest(final Object data) { if (!isConnected()) { completeUiRequest(ServiceStatus.ERROR_NO_INTERNET); } newState(State.DELETE_IDENTITY); DeleteIdentityRequest reqData = (DeleteIdentityRequest) data; if (!setReqId(Identities.deleteIdentity(this, reqData.mNetwork, reqData.mIdentityId))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(DecodedResponse resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if ((null == resp) || (null == resp.mDataTypes)) { LogUtils.logE("Response objects or its contents were null. Aborting..."); return; } // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; case BaseDataType.IDENTITY_DELETION_DATA_TYPE: handleDeleteIdentity(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); } } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { Identity identity = (Identity)item; mMyIdentityList.add(identity); } + // cache the identities + MyIdentitiesCacheTable.setCachedIdentities(mDatabaseHelper.getWritableDatabase(), + mMyIdentityList); } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); if (errorStatus == ServiceStatus.SUCCESS) { addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, null); } } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response of request to delete the identity. The response * should be a status that whether the operation is succeeded or not. The * response will be a status result otherwise ERROR_UNEXPECTED_RESPONSE if * the response is not as expected. * * @param data * List of BaseDataTypes generated from Server response. */ private void handleDeleteIdentity(final List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus( BaseDataType.IDENTITY_DELETION_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { for (BaseDataType item : data) { if (item.getType() == BaseDataType.IDENTITY_DELETION_DATA_TYPE) { synchronized(mMyIdentityList) { // iterating through the subscribed identities for (Identity identity : mMyIdentityList) { if (identity.mIdentityId .equals(getIdentityToBeDeleted().mIdentityId)) { mMyIdentityList.remove(identity); break; } } + // cache the new set of identities + MyIdentitiesCacheTable.setCachedIdentities(mDatabaseHelper.getWritableDatabase(), + mMyIdentityList); } completeUiRequest(ServiceStatus.SUCCESS); return; } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } } completeUiRequest(errorStatus, bu); - } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; synchronized (mAvailableIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mAvailableIdentityList); } } else { requestKey = KEY_MY_IDS; synchronized (mMyIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mMyIdentityList); } } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ /** {@inheritDoc} */ @Override public final void onReset() { super.onReset(); mMyIdentityList.clear(); mAvailableIdentityList.clear(); mStatusList.clear(); mState = State.IDLE; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of Identity objects, can be NULL. * @return TRUE if the given Identity contains a Facebook account. */ public boolean isFacebookInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_FACEBOOK)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given Identity contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given Identity contains a Hyves account. */ public boolean isHyvesInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_HYVES)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Hyves not found in list"); return false; } - } diff --git a/src/com/vodafone360/people/service/receivers/SimStateReceiver.java b/src/com/vodafone360/people/service/receivers/SimStateReceiver.java index 7dc2463..e2d8a94 100755 --- a/src/com/vodafone360/people/service/receivers/SimStateReceiver.java +++ b/src/com/vodafone360/people/service/receivers/SimStateReceiver.java @@ -1,65 +1,90 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the Common Development + * and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at + * src/com/vodafone360/people/VODAFONE.LICENSE.txt or + * http://github.com/360/360-Engine-for-Android + * See the License for the specific language governing permissions and + * limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each file and + * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. + * If applicable, add the following below this CDDL HEADER, with the fields + * enclosed by brackets "[]" replaced with your own identifying information: + * Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + * + * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. + * Use is subject to license terms. + */ + package com.vodafone360.people.service.receivers; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.SimCard; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.TelephonyManager; /** * The SimStateReceiver is a BroadcastReceiver used to listen for SIM state changes. * * @see INTENT_SIM_STATE_CHANGED */ public class SimStateReceiver extends BroadcastReceiver { /** * The Listener interface. */ public interface Listener { /** * Callback method when SIM is ready. */ void onSimReadyState(); } /** * The Intent broadcasted by the Android platform when the SIM card state changes. */ public final static String INTENT_SIM_STATE_CHANGED = "android.intent.action.SIM_STATE_CHANGED"; /** * The registered Listener. */ private final Listener mListener; /** * The SimStateReceiver constructor. * * @param listener the registered listener */ public SimStateReceiver(Listener listener) { LogUtils.logD("SimStateReceiver instance created."); mListener = listener; } /** * @see BroadcastReceiver#onReceive(Context, Intent) */ @Override public void onReceive(Context context, Intent intent) { final int simState = SimCard.getState(context); LogUtils.logD("SimStateReceiver.onReceive() - simState="+simState); if (simState == TelephonyManager.SIM_STATE_READY) { mListener.onSimReadyState(); } } } diff --git a/src/com/vodafone360/people/service/utils/UserDataProtection.java b/src/com/vodafone360/people/service/utils/UserDataProtection.java index 4222b80..b9a9501 100755 --- a/src/com/vodafone360/people/service/utils/UserDataProtection.java +++ b/src/com/vodafone360/people/service/utils/UserDataProtection.java @@ -1,155 +1,180 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the Common Development + * and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at + * src/com/vodafone360/people/VODAFONE.LICENSE.txt or + * http://github.com/360/360-Engine-for-Android + * See the License for the specific language governing permissions and + * limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each file and + * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. + * If applicable, add the following below this CDDL HEADER, with the fields + * enclosed by brackets "[]" replaced with your own identifying information: + * Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + * + * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. + * Use is subject to license terms. + */ + package com.vodafone360.people.service.utils; import android.content.Context; import android.content.IntentFilter; import android.telephony.TelephonyManager; import android.text.TextUtils; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.receivers.SimStateReceiver; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.SimCard; /** * The UserDataProtection is responsible of putting in place mechanisms that will guarantee * the User data safety. * * The case to watch are the following: * -User uses SIM card A to log in 360 then restarting the device with SIM card B or without a SIM * card will automatically log out from the 360 client. * -User uses no SIM card to log in 360 then restarting the device with a SIM card will automatically * log out from the 360 client. */ public class UserDataProtection implements SimStateReceiver.Listener { /** * The Service context. */ private Context mContext; /** * The DatabaseHelper used for our database access. */ private DatabaseHelper mDatabaseHelper; /** * The BroadcastReceiver listening for SIM states changes. */ private SimStateReceiver mSimStateReceiver; /** * The UserDataProtection constructor. * * @param context the Service context * @param databaseHelper the DatabaseHelper */ public UserDataProtection(Context context, DatabaseHelper databaseHelper) { mContext = context; mDatabaseHelper = databaseHelper; } /** * Performs the checks needed when the 360 Service is started. * * This method checks if the user has changed and if the SIM card id cannot be read, sets a * SIM state changes listener. */ public void performStartupChecks() { LogUtils.logD("UserDataProtection.performStartupChecks()"); final LoginEngine loginEngine = EngineManager.getInstance().getLoginEngine(); if (loginEngine.isLoggedIn()) { final int simState = SimCard.getState(mContext); if (simState == TelephonyManager.SIM_STATE_ABSENT || simState == TelephonyManager.SIM_STATE_READY) { processUserChanges(); } else { LogUtils.logD("UserDataProtection.performStartupChecks() - SIM_STATE_UNKNOWN, register a SimStateReceiver."); // SIM is not ready, register a listener for Sim state changes to check // the subscriber id when possible mSimStateReceiver = new SimStateReceiver(this); mContext.registerReceiver(mSimStateReceiver, new IntentFilter(SimStateReceiver.INTENT_SIM_STATE_CHANGED)); } } } /** * Requests to log out from 360 if the user has changed. */ public void processUserChanges() { LogUtils.logD("UserDataProtection.checkUserChanges()"); final LoginEngine loginEngine = EngineManager.getInstance().getLoginEngine(); if (loginEngine.isLoggedIn() && hasUserChanged()) { // User has changed, log out LogUtils.logD("UserDataProtection.checkUserChanges() - User has changed! Request logout."); loginEngine.addUiRemoveUserDataRequest(); } } /** * Unregister the SIM state changes receiver. */ public void unregisterSimStateReceiver() { if (mSimStateReceiver != null) { LogUtils.logD("UserDataProtection.checkUserChanges() - unregister the SimStateReceiver"); mContext.unregisterReceiver(mSimStateReceiver); } } /** * Check wether or not the User has changed. * * @return true if the current User is different, false otherwise */ public boolean hasUserChanged() { final String loginSubscriberId = getSubscriberIdForLogin(); final String currentSuscriberId = SimCard.getSubscriberId(mContext); return !TextUtils.equals(loginSubscriberId, currentSuscriberId); } /** * Gets the Subscriber Id used to log in 360. * * @param databaseHelper the DatabaseHelper * @return the Subscriber Id used to log in 360, null if there was a problem while retrieving it */ public String getSubscriberIdForLogin() { final LoginDetails mLoginDetails = new LoginDetails(); final ServiceStatus mServiceStatus = mDatabaseHelper.fetchLogonCredentials(mLoginDetails); if (mServiceStatus == ServiceStatus.SUCCESS) { return mLoginDetails.mSubscriberId; } return null; } /** * @see SimStateReceiver.Listener#onSimReadyState() */ @Override public void onSimReadyState() { processUserChanges(); unregisterSimStateReceiver(); } } diff --git a/src/com/vodafone360/people/utils/SimCard.java b/src/com/vodafone360/people/utils/SimCard.java index ebd7da9..6200437 100755 --- a/src/com/vodafone360/people/utils/SimCard.java +++ b/src/com/vodafone360/people/utils/SimCard.java @@ -1,313 +1,338 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the Common Development + * and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at + * src/com/vodafone360/people/VODAFONE.LICENSE.txt or + * http://github.com/360/360-Engine-for-Android + * See the License for the specific language governing permissions and + * limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each file and + * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. + * If applicable, add the following below this CDDL HEADER, with the fields + * enclosed by brackets "[]" replaced with your own identifying information: + * Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + * + * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. + * Use is subject to license terms. + */ + package com.vodafone360.people.utils; import java.util.HashMap; import java.util.Map; import android.content.Context; import android.telephony.TelephonyManager; /** * The SimCard class provides utility methods to access SIM card data. */ public class SimCard { /** * Digits beyond this count will be replaced by 0. */ private static final int ANONYMISED_DIGITS = 4; /** * The Network. */ public enum Network { CH("ch", 41), // Switzerland DE("de", 49), // Germany FR("fr", 33), // France GB("gb", 44), // Great Britain IE("ie", 353), // Ireland IT("it", 39), // Italy NL("nl", 31), // Netherlands SE("se", 46), // Sweden TR("tr", 90), // Turkey TW("tw", 886), // Taiwan US("us", 1), // United States ES("es", 34), // Spain // ZA("za", 260), //Zambia/VodaCom-SA?? UNKNOWN("unknown", 0); private final String mIso; private final int mPrefix; private Network(String iso, int prefix) { mIso = iso; mPrefix = prefix; } private Network() { mIso = null; mPrefix = -1; } public String iso() { return mIso; } protected int prefix() { return mPrefix; } /*** * Returns the SimNetwork of a given ISO if known * * @param iso Country ISO value. * @return SimNetwork or SimNetwork.UNKNOWN if not found. */ public static Network getNetwork(String iso) { for (final Network network : Network.values()) { if (network.iso().equals(iso)) { return network; } } return UNKNOWN; } } /** * SIM card absent state. * @see #getSubscriberId(Context) */ public final static String SIM_CARD_ABSENT = "SimAbsent"; /** * SIM card not readable state. * @see #getSubscriberId(Context) */ public final static String SIM_CARD_NOT_READABLE = "SimNotReadable"; /** * Gets the SIM card state. * * @see TelephonyManager#getSimState() * * @param context the application context * @return the SIM card state */ public static int getState(Context context) { try { final TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); return telephonyManager.getSimState(); } catch (final Exception e) { LogUtils.logE("SimCard.getState() - Exception:", e); } return TelephonyManager.SIM_STATE_UNKNOWN; } /** * Tells whether or not the SIM card is present. * * @param context the * @return true if the SIM is ready, false otherwise (not ready or absent) */ public static boolean isSimReady(Context context) { return getState(context) == TelephonyManager.SIM_STATE_READY; } /** * Gets the Subscriber Id. * * @see SIM_CARD_NOT_READABLE * @see SIM_CARD_ABSENT * * @param databaseHelper the DatabaseHelper * @return the Subscriber Id or SIM_CARD_ABSENT or SIM_CARD_NOT_READABLE */ public static String getSubscriberId(Context context) { if (getState(context) == TelephonyManager.SIM_STATE_ABSENT) { return SIM_CARD_ABSENT; } else { try { final TelephonyManager mTelephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); return mTelephonyManager.getSubscriberId(); } catch (final Exception e) { LogUtils.logE("SimCard.getSubscriberId() - Exception: "+e); } } return SIM_CARD_NOT_READABLE; } /** * Logs a MSISDN validation failure event to Flurry. * * @param context Android context. * @param workflow Given work flow (either sign in or sign up). * @param status Current status string. * @param enteredMsisdn User provided MSISDN. */ public static void logMsisdnValidationFail(Context context, String workflow, String status, String enteredMsisdn) { final TelephonyManager telephonyManager = (TelephonyManager)context .getSystemService(Context.TELEPHONY_SERVICE); final Map<String, String> map = new HashMap<String, String>(); map.put("NetworkCountryIso", telephonyManager.getNetworkCountryIso()); map.put("NetworkOperator", telephonyManager.getNetworkOperator()); map.put("NetworkOperatorName", telephonyManager.getNetworkOperatorName()); map.put("SimCountryIso", telephonyManager.getSimCountryIso()); map.put("SimOperator", telephonyManager.getSimOperator()); map.put("SimOperatorName", telephonyManager.getSimOperatorName()); map.put("AnonymisedMsisdn", getAnonymisedMsisdn(telephonyManager.getLine1Number())); map.put("AnonymisedEntereddMsisdn", getAnonymisedMsisdn(enteredMsisdn)); map.put("Workflow", workflow); map.put("Error", status); // FlurryAgent.onEvent("EnterMobileNumberActivity_FAIL", map); LogUtils.logV("SimUtils.logMsisdnValidationFail() enteredMsisdn[" + enteredMsisdn + "]"); } /** * Retrieves the full international MSISDN number from the SIM or NULL if * unavailable or unsure. Note: This functionality is currently part of * SignupEnterMobileNumberActivity so anonymised data can be sent back to * Flurry, in order to verify this program logic on multiple SIMs. * * @param context Android Context * @return Full international MSISDN, or NULL if unsure of conversion. */ public static String getFullMsisdn(Context context) { final TelephonyManager telephonyManager = (TelephonyManager)context .getSystemService(Context.TELEPHONY_SERVICE); final String rawMsisdn = telephonyManager.getLine1Number(); final String verifyedMsisdn = getVerifyedMsisdn(rawMsisdn, telephonyManager .getNetworkCountryIso(), telephonyManager.getNetworkOperatorName(), telephonyManager.getNetworkOperator()); final Map<String, String> map = new HashMap<String, String>(); map.put("NetworkCountryIso", telephonyManager.getNetworkCountryIso()); map.put("NetworkOperator", telephonyManager.getNetworkOperator()); map.put("NetworkOperatorName", telephonyManager.getNetworkOperatorName()); map.put("SimCountryIso", telephonyManager.getSimCountryIso()); map.put("SimOperator", telephonyManager.getSimOperator()); map.put("SimOperatorName", telephonyManager.getSimOperatorName()); map.put("AnonymisedMsisdn", getAnonymisedMsisdn(rawMsisdn)); map.put("AnonymisedVerifyedMsisdn", getAnonymisedMsisdn(verifyedMsisdn)); // FlurryAgent.onEvent("EnterMobileNumberActivity", map); return verifyedMsisdn; } /*** * Convert raw MSISDN to a verified MSISDN with country code. * * @param rawMsisdn Unverified MSISDN. * @param countryIso Country ISO value from the SIM. * @param networkOperatorName Network operator name value from the SIM. * @param networkOperator Network operator value from the SIM. * @return Verified MSISDN, or "" if NULL or unsure of country code. */ public static String getVerifyedMsisdn(String rawMsisdn, String countryIso, String networkOperatorName, String networkOperator) { if (rawMsisdn == null || rawMsisdn.trim().equals("")) { // Reject any NULL or empty values. return ""; } else if (rawMsisdn.substring(0, 1).equals("+")) { // Accept any values starting with "+". return rawMsisdn; // the MTS Russian SIM may have just "8" as a rawNsisdn string } else if (rawMsisdn.length() > 1 && (rawMsisdn.substring(0, 2).equals("00"))) { // Accept any values starting with "00", but at +. return "+" + rawMsisdn.substring(2); } else if (countryIso != null && !countryIso.trim().equals("")) { // Filter known values: try { final Network simNetwork = Network.getNetwork(countryIso); if (simNetwork != Network.UNKNOWN) { return "+" + smartAdd(simNetwork.prefix() + "", dropZero(rawMsisdn)); } else { // Rejected return ""; } } catch (final NumberFormatException e) { // Rejected return ""; } } else { // Rejected return ""; } } /*** * Concatenate the "start" value with the "end" value, except where the * "start" value is already in place. * * @param start First part of String. * @param end Last part of String. * @return "start" + "end". */ private static String smartAdd(String start, String end) { if (end == null || end.trim().equals("")) { return ""; } else if (end.startsWith(start)) { return end; } else { return start + end; } } /*** * Remove the preceding zero, if present. * * @param rawMsisdn Number to alter. * @return Number without the zero. */ private static String dropZero(String rawMsisdn) { if (rawMsisdn == null || rawMsisdn.trim().equals("")) { return ""; } else if (rawMsisdn.startsWith("0")) { return rawMsisdn.substring(1); } else { return rawMsisdn; } } /*** * Converts an identifiable MSISDN value to something that can be sent via a * third party. E.g. "+49123456789" becomes "+49100000000". * * @param input Private MSISDN. * @return Anonymous MSISDN. */ public static String getAnonymisedMsisdn(String input) { if (input == null || input.trim().equals("")) { return ""; } else { final int length = input.length(); final StringBuffer result = new StringBuffer(); for (int i = 0; i < length; i++) { if (i < ANONYMISED_DIGITS) { result.append(input.charAt(i)); } else { result.append("0"); } } return result.toString(); } } }
360/360-Engine-for-Android
2a8250dd5341a670e01a49e0e61a9d5ef2ca6af1
Fix for PAND-1183
diff --git a/src/com/vodafone360/people/engine/login/LoginEngine.java b/src/com/vodafone360/people/engine/login/LoginEngine.java index f3c09d2..f0e6124 100644 --- a/src/com/vodafone360/people/engine/login/LoginEngine.java +++ b/src/com/vodafone360/people/engine/login/LoginEngine.java @@ -691,723 +691,723 @@ public class LoginEngine extends BaseEngine { } mActivationCode = null; newState(State.SIGNING_UP); if (!validateRegistrationDetails()) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } int reqId = Auth.signupUserCrypted( this, mRegistrationDetails.mFullname, mRegistrationDetails.mUsername, theBytes, // what is encrypted timestamp, mRegistrationDetails.mEmail, mRegistrationDetails.mBirthdayDate, mRegistrationDetails.mMsisdn, mRegistrationDetails.mAcceptedTAndC, mRegistrationDetails.mCountrycode, mRegistrationDetails.mTimezone, mRegistrationDetails.mLanguage, mRegistrationDetails.mMobileOperatorId, mRegistrationDetails.mMobileModelId, mRegistrationDetails.mSendConfirmationMail, mRegistrationDetails.mSendConfirmationSms, mRegistrationDetails.mSubscribeToNewsLetter); if (!setReqId(reqId)) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Basic check to determine if the registration details given by the user * are valid * * @return true if the details are valid, false otherwise. */ private boolean validateRegistrationDetails() { if (mRegistrationDetails.mFullname == null || mRegistrationDetails.mEmail == null || mRegistrationDetails.mBirthdayDate == null || mRegistrationDetails.mMsisdn == null || mRegistrationDetails.mAcceptedTAndC == null || mRegistrationDetails.mCountrycode == null || mRegistrationDetails.mTimezone == null || mRegistrationDetails.mLanguage == null || mRegistrationDetails.mMobileOperatorId == null || mRegistrationDetails.mMobileModelId == null || mRegistrationDetails.mSendConfirmationMail == null || mRegistrationDetails.mSendConfirmationSms == null || mRegistrationDetails.mSubscribeToNewsLetter == null) { return false; } return true; } /** * Requests a new Public Key from the server. */ public void getNewPublicKey() { LogUtils.logD("LoginEngine.getNewPublicKey"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mActivationCode = null; newState(State.RETRIEVING_PUBLIC_KEY); if (!setReqId(Auth.getPublicKey(this))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch terms of service request to the server. */ private void startFetchTermsOfService() { LogUtils.logD("LoginEngine.startFetchTermsOfService()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } newState(State.FETCHING_TERMS_OF_SERVICE); if (!setReqId(Auth.getTermsAndConditions(this))) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch privacy statement request to the server. */ private void startFetchPrivacyStatement() { LogUtils.logD("LoginEngine.startFetchPrivacyStatement()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } newState(State.FETCHING_PRIVACY_STATEMENT); if (!setReqId(Auth.getPrivacyStatement(this))) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch user-name state request to the server. * * @param username, the user-name to retrieve information for. */ private void startFetchUsernameState(String username) { LogUtils.logD("LoginEngine.startFetchUsernameState()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mLoginDetails.mUsername = username; newState(State.FETCHING_USERNAME_STATE); if (!setReqId(Auth.getUsernameState(this, username))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sets registration complete flag to false then starts a new sign-in * request. * * @param details Login details received from the UI request */ private void startManualLoginProcess(LoginDetails details) { LogUtils.logD("LoginEngine.startManualLoginProcess()"); setRegistrationComplete(false); setActivatedSession(null); if (details == null) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } mLoginDetails.copy(details); mLoginDetails.mSubscriberId = SimCard.getSubscriberId(mContext); mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); if (Settings.ENABLE_ACTIVATION) { startRequestActivationCode(); } else { startGetSessionManual(); } } /** * Sends a request activation code request to the server. */ private void startRequestActivationCode() { LogUtils.logD("LoginEngine.startRequestActivationCode()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mActivationCode = null; newState(State.REQUESTING_ACTIVATION_CODE); if (!setReqId(Auth.requestActivationCode(this, mLoginDetails.mUsername, mLoginDetails.mMobileNo))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a get session by credentials request to the server. */ private void startGetSessionManual() { LogUtils.logD("LoginEngine.startGetSessionManual()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } newState(State.CREATING_SESSION_MANUAL); if (!setReqId(Auth.getSessionByCredentials(this, mLoginDetails.mUsername, mLoginDetails.mPassword, null))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a activate account request to the server. */ private void startActivateAccount() { LogUtils.logD("LoginEngine.startActivateAccount()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } if (Settings.ENABLE_ACTIVATION) { newState(State.ACTIVATING_ACCOUNT); if (!setReqId(Auth.activate(this, mActivationCode))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } else { setRegistrationComplete(true); completeUiRequest(ServiceStatus.SUCCESS, null); } } /** * Clears the session and registration complete information so that the user * will need to manually login again to use the now+ services. Does not * currently send a request to the server to log out. */ private void startLogout() { LogUtils.logD("LoginEngine.startLogout()"); setRegistrationComplete(false); setActivatedSession(null); completeUiRequest(ServiceStatus.SUCCESS, null); } /** * Clears the session and registration complete information so that the user * will need to manually login again to use the now+ services. Does not * currently send a request to the server to log out. */ public final void logoutAndRemoveUser() { LogUtils.logD("LoginEngine.startLogout()"); addUiRemoveUserDataRequest(); LoginPreferences.clearPreferencesFile(mContext); mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UNSOLICITED_GO_TO_LANDING_PAGE, null); } /** * Retries to log the user in based on credential information stored in the * database. * * @return true if the login process was able to start */ public boolean retryAutoLogin() { LogUtils.logD("LoginEngine.retryAutoLogin()"); setActivatedSession(null); if (ServiceStatus.SUCCESS != mDb.fetchLogonCredentialsAndPublicKey(mLoginDetails, mPublicKey)) { LogUtils .logE("LoginEngine.retryAutoLogin() - Unable to fetch credentials from database"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } // AA: commented the condition out if (Settings.ENABLE_ACTIVATION) { // AA: the old version if (mCurrentSubscriberId == null || // !mCurrentSubscriberId.equals(mLoginDetails.mSubscriberId)) { // // logging off/fail will be done in another way according to bug 8288 final String currentSubscriberId = SimCard.getSubscriberId(mContext); if (currentSubscriberId != null && !currentSubscriberId.equals(mLoginDetails.mSubscriberId)) { LogUtils.logV("LoginEngine.retryAutoLogin() -" + " SIM card has changed or is missing (old subId = " + mLoginDetails.mSubscriberId + ", new subId = " + currentSubscriberId + ")"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } // } if (mLoginDetails.mUsername == null || mLoginDetails.mPassword == null || mLoginDetails.mMobileNo == null) { LogUtils.logV("LoginEngine.retryAutoLogin() - Username, password " + "or mobile number are missing (old username = " + mLoginDetails.mUsername + ", mobile no = " + mLoginDetails.mMobileNo + ")"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } mAreLoginDetailsValid = true; if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { newState(State.LOGGED_OFF_WAITING_FOR_NETWORK); LogUtils.logV("LoginEngine.retryAutoLogin() - Internet connection down. " + "Will try again when connection is available"); return false; } newState(State.CREATING_SESSION_AUTO); if (!setReqId(Auth.getSessionByCredentials(this, mLoginDetails.mUsername, mLoginDetails.mPassword, null))) { return false; } return true; } /** * Helper function to set the registration complete flag and update the * database with the new state. * * @param value true if registration is completed */ private void setRegistrationComplete(boolean value) { LogUtils.logD("LoginEngine.setRegistrationComplete(" + value + ")"); if (value != mIsRegistrationComplete) { StateTable.setRegistrationComplete(value, mDb.getWritableDatabase()); mIsRegistrationComplete = value; if (mIsRegistrationComplete) { // Create NAB Account at this point (does nothing on 1.X // devices) final NativeContactsApi nabApi = NativeContactsApi.getInstance(); if (!nabApi.isPeopleAccountCreated()) { // TODO: React upon failure to create account nabApi.addPeopleAccount(LoginPreferences.getUsername()); } } } } /** * Changes the state of the engine. Also displays the login notification if * necessary. * * @param newState The new state */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("LoginEngine.newState: " + oldState + " -> " + mState); Intent intent = null; // Update notification switch (mState) { case LOGIN_FAILED_WRONG_CREDENTIALS: intent = new Intent(); intent.setAction(Intents.START_LOGIN_ACTIVITY); mContext.sendBroadcast(intent); setRegistrationComplete(false); break; // here should be no break case NOT_REGISTERED: case LOGIN_FAILED: // intent = new Intent(); // intent.setAction(Intents.LOGIN_FAILED); // mContext.sendBroadcast(intent); setRegistrationComplete(false); // startLogout(); // mDb.removeUserData(); // sending user to login screen again // should be done by UI itself because // when it's done from here it cause problems when user tries to // login // giving wrong credentials, ui flow will be broken break; case LOGGED_OFF: case LOGGED_OFF_WAITING_FOR_NETWORK: case LOGGED_OFF_WAITING_FOR_RETRY: case LOGGED_ON: // intent = new Intent(); // intent.setAction(Intents.HIDE_LOGIN_NOTIFICATION); // mContext.sendBroadcast(intent); break; default:// do nothing break; } // Update listeners with any state changes switch (mState) { case NOT_REGISTERED: case LOGIN_FAILED: case LOGIN_FAILED_WRONG_CREDENTIALS: case LOGGED_OFF: onLoginStateChanged(false); break; case LOGGED_ON: onLoginStateChanged(true); break; default: // do nothing. break; } } /** * Called when the engine transitions between the logged in and logged out * states. Notifies listeners. * * @param loggedIn true if the user is now logged in, false otherwise. */ private synchronized void onLoginStateChanged(boolean loggedIn) { LogUtils.logD("LoginEngine.onLoginStateChanged() Login state changed to " + (loggedIn ? "logged in." : "logged out.")); if (loggedIn == mCurrentLoginState) { return; } mCurrentLoginState = loggedIn; for (ILoginEventsListener listener : mEventsListener) { listener.onLoginStateChanged(loggedIn); } } /** * A helper function which determines which activity should be displayed * when the UI is loaded. * * @return true if landing page should be displayed, false otherwise */ public synchronized boolean getLoginRequired() { LogUtils.logD("LoginEngine.getLoginRequired() - " + !mIsRegistrationComplete); return !mIsRegistrationComplete; } /** * Retrieves the active comms session. * * @return The session or NULL if the user is logged out. */ public static AuthSessionHolder getSession() { return sActivatedSession; } /** * Helper function to store the new session in the database and inform * clients that the session has changed. * * @param session The new session or NULL if the user has logged off. */ public synchronized void setActivatedSession(AuthSessionHolder session) { LogUtils.logD("LoginEngine.setActivatedSession() session[" + session + "]"); sActivatedSession = session; if (session != null) { LogUtils.logD("LoginEngine.setActivatedSession() Login successful"); } else { LogUtils.logW("LoginEngine.setActivatedSession() " + "Login unsuccessful, the session is NULL"); } StateTable.setSession(session, mDb.getWritableDatabase()); } /** * Called when a response to the sign-up API is received. In case of success * sets a timeout value waiting for the activation SMS to arrive. * * @param data The received data */ private void handleSignUpResponse(List<BaseDataType> data) { ServiceStatus errorStatus = getResponseStatus(BaseDataType.CONTACT_DATA_TYPE, data); LogUtils.logD("LoginEngine.handleSignUpResponse() errorStatus[" + errorStatus.name() + "]"); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils.logD("LoginEngine.handleSignUpResponse() - Registration successful"); if (!Settings.ENABLE_ACTIVATION) { startGetSessionManual(); } else { // Now waiting for SMS... setTimeout(ACTIVATE_LOGIN_TIMEOUT); } // AA } else if (errorStatus == ServiceStatus.ERROR_INVALID_PUBLIC_KEY) { // start new key retrieval and make the new cycle getNewPublicKey(); } else { completeUiRequest(errorStatus, null); } } /** * Called when a response to the server fetch public key request is * received. Validates the response and stores the new public key details. * * @param mDataTypes Response data from server. */ private void handleNewPublicKeyResponse(List<BaseDataType> mDataTypes) { LogUtils.logD("LoginEngine.handleNewPublicKeyResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.PUBLIC_KEY_DETAILS_DATA_TYPE, mDataTypes); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils.logD("LoginEngine.handleNewPublicKeyResponse() - Succesfully retrieved"); // AA // 1. save to DB; save the flag that we aren't using default and // have to use one from DB // 2. start registration again mPublicKey = (PublicKeyDetails)mDataTypes.get(0); // done in startRegistrationProcessCrypted already // mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); startRegistrationProcessCrypted(mRegistrationDetails); } else { completeUiRequest(errorStatus, null); } } /** * Called when a response to the GetSessionByCredentials API is received * (manual login). In case of success, tries to activate the account using * the activation code received by SMS. * * @param data The received data */ private void handleCreateSessionManualResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleCreateSessionManualResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AUTH_SESSION_HOLDER_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS && (data.size() > 0)) { setActivatedSession((AuthSessionHolder)data.get(0)); startActivateAccount(); return; } completeUiRequest(errorStatus, null); } /** * Called when a response to the GetSessionByCredentials API is received * (auto login). In case of success, moves to the logged in state * * @param data The received data */ private void handleCreateSessionAutoResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleCreateSessionResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AUTH_SESSION_HOLDER_TYPE, data); - if (errorStatus == ServiceStatus.SUCCESS) { + if (errorStatus == ServiceStatus.SUCCESS && (data.size() > 0)) { clearTimeout(); setActivatedSession((AuthSessionHolder)data.get(0)); newState(State.LOGGED_ON); } else { LogUtils.logE("LoginEngine.handleCreateSessionResponse() - Auto Login Failed Error " + errorStatus); // AA:the 1st retry failed, just go to the start page, // if (loginAttemptsRemaining() // && errorStatus!=ServiceStatus.ERROR_INVALID_PASSWORD) { // newState(State.LOGGED_OFF_WAITING_FOR_RETRY); // setTimeout(LOGIN_RETRY_TIME); // } else { // mAreLoginDetailsValid = false; if (errorStatus == ServiceStatus.ERROR_INVALID_PASSWORD) { mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED_WRONG_CREDENTIALS); } else { newState(State.LOGIN_FAILED); } // } } } /** * Called when a response to the RequestActivationCode API is received * (manual login). In case of success, tries to fetch a login session from * the server. * * @param data The received data */ private void handleRequestingActivationResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleRequestingActivationResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { // Now waiting for SMS... setTimeout(ACTIVATE_LOGIN_TIMEOUT); return; } completeUiRequest(errorStatus, null); } /** * Called when a response to the Activate API is received (manual login or * sign-up). In case of success, moves to the logged in state and completes * the manual login or sign-up request. * * @param data The received data */ private void handleActivateAccountResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleActivateAccountResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils .logD("LoginEngine.handleActivateAccountResponse: ** Mobile number activated **"); setRegistrationComplete(true); completeUiRequest(ServiceStatus.SUCCESS, null); return; } setActivatedSession(null); completeUiRequest(ServiceStatus.ERROR_ACCOUNT_ACTIVATION_FAILED, null); } /** * Called when a response to the GetTermsAndConditions, GetPrivacyStatement * and GetUsernameState APIs are received. In case of success, completes the * request and passes the response data to the UI. * * @param data The received data */ private void handleServerSimpleTextResponse(List<BaseDataType> data, State type) { LogUtils.logV("LoginEngine.handleServerSimpleTextResponse()"); ServiceStatus serviceStatus = getResponseStatus(BaseDataType.SIMPLE_TEXT_DATA_TYPE, data); String result = null; if (serviceStatus == ServiceStatus.SUCCESS) { result = ((SimpleText) data.get(0)).mValue.toString().replace( CARRIAGE_RETURN_CHARACTER, SPACE_CHARACTER); switch (type) { case FETCHING_TERMS_OF_SERVICE: LogUtils.logD("LoginEngine.handleServerSimpleTextResponse() Terms of Service"); ApplicationCache.setTermsOfService(result, mContext); break; case FETCHING_PRIVACY_STATEMENT: LogUtils.logD("LoginEngine.handleServerSimpleTextResponse() Privacy Statemet"); ApplicationCache.setPrivacyStatemet(result, mContext); break; case FETCHING_USERNAME_STATE: // TODO: Unused by UI. break; } } updateTermsState(serviceStatus, result); } /*** * Informs the UI to update any terms which are being shown on screen. * * @param serviceStatus Current ServiceStatus. * @param messageText Legacy call for old UI (TODO: remove after UI-Refresh * merge). NULL when combined with a ServiceStatus of * ERROR_COMMS, or contains the Privacy or Terms and Conditions * text to be displayed in the UI. */ private void updateTermsState(ServiceStatus serviceStatus, String messageText) { ApplicationCache.setTermsStatus(serviceStatus); /** Trigger UiAgent. **/ mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.TERMS_CHANGED_EVENT, null); /** Clear this request from the UI queue. **/ completeUiRequest(serviceStatus, messageText); } /** * A broadcast receiver which is used to receive notifications when a data * SMS arrives. */ private final BroadcastReceiver mEventReceiver = new BroadcastReceiver() { /** * Called when an SMS arrives. The activation code is extracted from the * given intent and the worker thread kicked. * * @param context Context from which the intent was broadcast * @param intent Will only process the SMS which the action is * {@link SmsBroadcastReceiver#ACTION_ACTIVATION_CODE}. */ @Override public void onReceive(Context context, Intent intent) { LogUtils.logD("LoginEngine.BroadcastReceiver.onReceive - Processing data sms"); if (intent.getAction().equals(SmsBroadcastReceiver.ACTION_ACTIVATION_CODE)) { String activationCode = intent.getStringExtra("code"); LogUtils .logD("LoginEngine.BroadcastReceiver.onReceive - Activation code Received: " + activationCode); synchronized (LoginEngine.this) { mActivationCode = activationCode; } mEventCallback.kickWorkerThread(); } } }; /** * Called when an SMS is received during sign-up or manual login. Starts * requesting a session from the server. */ private void handleSmsResponse() { LogUtils.logD("LoginEngine.handleSmsResponse(" + mActivationCode + ")"); clearTimeout(); startGetSessionManual(); } /** * Called by the base engine implementation whenever a UI request is * completed to do any necessary cleanup. We use it to restore our state to * a suitable value. */ @Override protected void onRequestComplete() { LogUtils.logD("LoginEngine.onRequestComplete()"); restoreLoginState(); } /** * Handles timeouts for SMS activation and auto login retries. */ protected synchronized void onTimeoutEvent() { LogUtils.logD("LoginEngine.onTimeoutEvent()"); switch (mState) { case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: completeUiRequest(ServiceStatus.ERROR_SMS_CODE_NOT_RECEIVED, null); break; case LOGGED_OFF_WAITING_FOR_RETRY: retryAutoLogin(); break; default: // do nothing. break; } } /** * Called by the framework before a remove user data operation takes place. * Initiates a suitable UI request which will kick the worker thread. */ @Override public void onReset() { // reset the engine as if it was just created super.onReset(); setRegistrationComplete(false); setActivatedSession(null); mState = State.NOT_INITIALISED; mRegistrationDetails = new RegistrationDetails(); mActivationCode = null; onLoginStateChanged(false); } /** * Set 'dummy' auth session for test purposes only. * * @param session 'dummy' session supplied to LoginEngine */ public static void setTestSession(AuthSessionHolder session) { sActivatedSession = session; } }
360/360-Engine-for-Android
b95542e5fcbecbe82ca45a24337dd2cea1745f37
PAND-2408 Crash fixes
diff --git a/src/com/vodafone360/people/ThumbnailCache.java b/src/com/vodafone360/people/ThumbnailCache.java index 6675375..337d869 100644 --- a/src/com/vodafone360/people/ThumbnailCache.java +++ b/src/com/vodafone360/people/ThumbnailCache.java @@ -1,475 +1,482 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import java.lang.ref.SoftReference; import java.lang.reflect.Field; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.List; import java.util.Set; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.View; import android.widget.ImageView; import com.vodafone360.people.utils.LRUHashMap; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.ThumbnailUtils; /*** * Unified thumbnail cache with asynchronous file reading, intended to be * utilised by multiple activities. */ public class ThumbnailCache { /** Thread name. **/ private static final String THREAD_NAME = "ThumbnailCacheThread"; /** Request queue size (number of possible on screen items). **/ private static final int REQUEST_QUEUE_SIZE = 9; /** * Thumbnails cache size (REQUEST_QUEUE_SIZE or greater, but larger values * are OK due to garbage collection). */ private static final int THUMBNAILS_CACHE_SIZE = 20; /** * Keep the Thumbnail Cache thread in the background by making it wait a * tiny bit between loading files. */ private static final long THREAD_WAIT = 5L; /** Thumbnail cache. **/ private final LRUHashMap<Long, SoftReference<Bitmap>> mThumbnailCache; /** Request queue (must be synchronised). **/ private final List<Item> mRequestQueue; /** List of invalid Thumbnails. **/ private final List<Long> mInvalidatedThumbnails; /** * Instance of the background thread (must always be accessed by the main * thread only). */ private BackgroundThread mBackgroundThread; /** Background Thread sync object. **/ private Object mBackgroundThreadSync = new Object(); /** Reference to activity which is currently using this item. **/ private Activity mActivity; /** True if the background thread should not be doing any work. **/ private boolean mPaused = false; /** Item in the request queue. **/ private class Item { /** Contact ID. **/ private final long mContactId; /** ImageView to populate. **/ private final ImageView mImageView; /*** * Item constructor. * * @param contactId Contact ID. * @param imageView ImageView to populate. */ public Item(final long contactId, final ImageView imageView) { mContactId = contactId; mImageView = imageView; } /*** * Contact ID. * * @return Contact ID. */ public long getContactId() { return mContactId; } /*** * ImageView to populate. * * @return ImageView to populate. */ public ImageView getImageView() { return mImageView; } } /*** * Create the Cache. */ public ThumbnailCache() { mThumbnailCache = new LRUHashMap<Long, SoftReference<Bitmap>>(THUMBNAILS_CACHE_SIZE); mRequestQueue = new ArrayList<Item>(REQUEST_QUEUE_SIZE); mInvalidatedThumbnails = new ArrayList<Long>(); } /*** * Subscribe this Activity to the cache. * * @param activity Current Activity for posting to a UI thread. */ public final void subscribe(final Activity activity) { synchronized (mBackgroundThreadSync) { if (mBackgroundThread == null) { mBackgroundThread = new BackgroundThread(); } } mActivity = activity; pauseThread(false); } /*** * Removed the background thread and clear all pending work. */ public final void unsubscribe() { synchronized (mBackgroundThreadSync) { if (mBackgroundThread != null) { mBackgroundThread.killThread(); } mBackgroundThread = null; } mPaused = true; mActivity = null; synchronized (mRequestQueue) { mRequestQueue.clear(); } } /*** * Pause the Background Thread, while keeping the work queue. * * @param pause TRUE if the thread should be paused, FALSE will immediately * resume the thread. */ public final void pauseThread(final boolean pause) { mPaused = pause; synchronized (mBackgroundThreadSync) { if (!pause && mBackgroundThread != null) { mBackgroundThread.doWork(); } } } /*** * Sets the given ImageView with the cached thumbnail for this contact ID, * using the default thumbnail if it is not cached. If the thumbnail is * not cached and "queue" is set to TRUE, then a background thread will try * and populate the ImageView later. * * @param imageView ImageView to set now (from cache) or later (in * background thread). * @param localContactId ID of the contact thumbnail. * @param defaultThumbnailId ID of default thumbnail resource. */ public final void setThumbnail(final ImageView imageView, final long localContactId, final int defaultThumbnailId) { if (imageView == null) { throw new InvalidParameterException("ThumbnailCache.setThumbnail() " + "ImageView should not be NULL"); } boolean imageSet = false; /** Associate the ImageView with the contact ID. **/ imageView.setTag(localContactId); /** Check the thumbnail cache. **/ final SoftReference<Bitmap> bitmapRef = mThumbnailCache.get(localContactId); if (bitmapRef != null) { final Bitmap thumbnail = bitmapRef.get(); if (thumbnail != null) { /** Instantly return a cached reference. **/ imageView.setImageBitmap(thumbnail); imageSet = true; if (!mInvalidatedThumbnails.contains(localContactId)) { /** This image is valid, so don't try and reload. **/ return; } } else { /** Remove any faulty references from the cache. **/ LogUtils.logW("ThumbnailCache.setThumbnail() " + "Bad reference removed id[" + localContactId + "]"); mThumbnailCache.remove(localContactId); } } /** Add this thumbnail to the request queue. **/ synchronized (mRequestQueue) { if (!mRequestQueue.contains(localContactId)) { /** Remove oldest item in the list. **/ if (mRequestQueue.size() > REQUEST_QUEUE_SIZE) { mRequestQueue.remove(0); } mRequestQueue.add(new Item(localContactId, imageView)); synchronized (mBackgroundThreadSync) { if (mBackgroundThread != null) { mBackgroundThread.doWork(); } } } } if (!imageSet) { /** Thumbnail was not found, so use default. **/ imageView.setImageResource(defaultThumbnailId); } } /*** * Clear the entire thumbnail cache to save memory. */ private final void clearThumbnailCache() { synchronized (mRequestQueue) { mRequestQueue.clear(); } mThumbnailCache.clear(); mInvalidatedThumbnails.clear(); System.gc(); } /*** * Invalidate the entire thumbnail cache, that way a thumbnail that has * been changed in the file system will be updated the next time it is * requested by the UI. */ public final void invalidateThumbnailCache() { mInvalidatedThumbnails.clear(); Set<Long> x = mThumbnailCache.keySet(); Long[] thumbnailCacheArray = (Long[]) x.toArray(new Long[x.size()]); for (Long contactId : thumbnailCacheArray) { mInvalidatedThumbnails.add(contactId); } } /*** * Perform work in a background thread. */ private class BackgroundThread extends Thread { /** * Object is used to indicate that this thread has started, and for * pausing and notifying the Thread. Thread will wait on this object. */ private Object mRunning; /** Set to TRUE to indicate that this thread should roll to a stop. **/ private boolean mKillThread = false; /*** * Start or bring the thread out of wait state to do some background * work. */ public void doWork() { if (mKillThread) { /** Exit now. **/ return; } else if (mRunning == null) { /** First time start. **/ mRunning = new Object(); start(); } else if (mRequestQueue.size() != 0 && !mPaused) { /** Notify the running thread. **/ synchronized (mRunning) { mRunning.notify(); } } } @Override public void run() { android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_BACKGROUND); Thread.currentThread().setName(THREAD_NAME); while (!mKillThread) { loadThumbnails(); threadWait(null); } } /*** * Load thumbnails from the file IO, posting a cache updated * notification to the handled as long as one file has been loaded. */ private final void loadThumbnails() { while (!mKillThread) { if (mPaused || mActivity == null) { return; } final Item item; synchronized (mRequestQueue) { if (mRequestQueue.size() < 1) { /** Loading done. **/ return; } item = mRequestQueue.remove(0); } if (item.getContactId() != getLocalContactId(item.getImageView())) { /** ImageView has been Recycled. **/ continue; } /** * Do all expensive File IO and Bitmap decoding work. */ final String path = ThumbnailUtils.thumbnailPath( item.getContactId()); if (path != null) { try { /* Using reflection to set inPurgeable flag as it is not available on 1.5 */ Class bitmapFactoryOptionsClass = BitmapFactory.Options.class; BitmapFactory.Options bitmapFactoryOptionsInstance = new BitmapFactory.Options(); Field field; try { field = bitmapFactoryOptionsClass.getField("inPurgeable"); field.setBoolean(bitmapFactoryOptionsInstance, true); } catch (SecurityException e) { LogUtils.logW("ThumbnailCache.loadThumbnails() " + "Security Exception"); } catch (NoSuchFieldException e) { LogUtils.logW("ThumbnailCache.loadThumbnails() " + "Field not found"); } catch (IllegalArgumentException e) { LogUtils.logW("ThumbnailCache.loadThumbnails() " + "Illegal Argument"); } catch (IllegalAccessException e) { LogUtils.logW("ThumbnailCache.loadThumbnails() " + "Illegal Access"); } final Bitmap bitmap = BitmapFactory.decodeFile(path, bitmapFactoryOptionsInstance); mThumbnailCache.put(item.getContactId(), new SoftReference<Bitmap>(bitmap)); /** Thumbnail is now valid. **/ mInvalidatedThumbnails.remove(item.getContactId()); if (item.getContactId() != getLocalContactId(item.getImageView())) { /** ImageView has been Recycled. **/ continue; } if (mActivity == null) { return; } mActivity.runOnUiThread(new Runnable() { @Override public void run() { /** * Check if the view is still the same, and * hasn't been re-used by the ListView. */ if (item.getContactId() == getLocalContactId(item.getImageView())) { item.getImageView().setImageBitmap(bitmap); } }}); + } catch (NullPointerException e) { + LogUtils.logE("ThumbnailCache.loadThumbnails() " + + "Unexpected NullPointerException while " + + "loading thumbnails, clearing Thumbnail " + + "cache for safety.", e); + clearThumbnailCache(); + } catch (OutOfMemoryError outOfMemoryError) { LogUtils.logE("ThumbnailCache.loadThumbnails() " + "Low on memory while decoding thumbnails", outOfMemoryError); clearThumbnailCache(); } } threadWait(THREAD_WAIT); } } /*** * Stop the thread between cycles to stop it overloading the device and * possibly blocking the UI. * * @param wait Time to wait in milliseconds, or NULL to wait for a * thread notify. */ private void threadWait(final Long wait) { synchronized (mRunning) { try { if (mKillThread) { /** Never wait while thread is being killed. **/ return; } else if (wait == null) { mRunning.wait(); } else { mRunning.wait(wait); } } catch (InterruptedException e) { // Do nothing. } } } /*** * Kills the running background thread. */ public void killThread() { mKillThread = true; synchronized (mRunning) { mRunning.notify(); } } } /*** * Return the local contact ID tag for the given View. * * @param view View to extract the list position information. * @return List position of the view. */ private static long getLocalContactId(final View view) { final Object localContactIdObject = view.getTag(); if (localContactIdObject == null) { LogUtils.logW("ThumbnailCache.getLocalContactId() " + "ID for view should not be NULL"); return -1L; } else { return (Long) localContactIdObject; } } /*** * Return TRUE if the background thread is paused. * * @return TRUE if the background thread is paused. */ public boolean isPaused() { return mPaused; } } diff --git a/src/com/vodafone360/people/engine/presence/ChatDbUtils.java b/src/com/vodafone360/people/engine/presence/ChatDbUtils.java index 969271c..efaf82c 100644 --- a/src/com/vodafone360/people/engine/presence/ChatDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/ChatDbUtils.java @@ -1,267 +1,320 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.database.sqlite.SQLiteDatabase; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ActivitiesTable; import com.vodafone360.people.database.tables.ContactDetailsTable; import com.vodafone360.people.database.tables.ContactSummaryTable; import com.vodafone360.people.database.tables.ContactsTable; import com.vodafone360.people.database.tables.ConversationsTable; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineNativeTypes; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.ActivityItem; import com.vodafone360.people.datatypes.ChatMessage; import com.vodafone360.people.datatypes.ContactDetail; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.ContactDetail.DetailKeys; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.LogUtils; +/*** + * Utilities relating to Chat messages. + */ public class ChatDbUtils { + /** + * User ID is formated <network>::<userId>, using this as the divider. + */ protected static final String COLUMNS = "::"; - protected static void convertUserIds(ChatMessage msg, DatabaseHelper databaseHelper) { + /*** + * Set the user ID, network ID and local contact ID values in the given + * ChatMessage. + * + * The original msg.getUserId() is formatted <network>::<userId>, meaning + * if "::" is present the values are split, otherwise the original value is + * used. + * + * @param chatMessage ChatMessage to be altered. + * @param databaseHelper DatabaseHelper with a readable database. + */ + public static void convertUserIds(final ChatMessage chatMessage, + final DatabaseHelper databaseHelper) { + + /** + * Use original User ID, in case of NumberFormatException (see + * PAND-2356). + */ + final String originalUserId = chatMessage.getUserId(); - String userId = msg.getUserId(); - String network = SocialNetwork.VODAFONE.name(); + int index = originalUserId.indexOf(COLUMNS); + if (index > -1) { + /** Parse a <networkId>::<userId> formatted user ID. **/ + chatMessage.setUserId( + originalUserId.substring(index + COLUMNS.length())); + String network = originalUserId.substring(0, index); - // TODO: PAND-2356: log original userID, in case of NumberFormatException - String originalUserId = userId; + /** Parse the <networkId> component. **/ + SocialNetwork sn = SocialNetwork.getValue(network); + if (sn != null) { + chatMessage.setNetworkId(sn.ordinal()); + } else { + chatMessage.setNetworkId(SocialNetwork.INVALID.ordinal()); + LogUtils.logE("ChatUtils.convertUserIds() Invalid Network ID [" + + network + "] in [" + originalUserId + "]"); + } - int columnsIndex = userId.indexOf(COLUMNS); - if (columnsIndex > -1) { - network = userId.substring(0, columnsIndex); - userId = userId.substring(columnsIndex + COLUMNS.length()); - } - SocialNetwork sn = SocialNetwork.getValue(network); - if (sn != null) { - msg.setNetworkId(sn.ordinal()); } else { - throw new RuntimeException("ChatUtils.convertUserIds: Invalid network : " + network); + /** Use defaults. **/ + chatMessage.setUserId(chatMessage.getUserId()); + chatMessage.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } - msg.setUserId(userId); - int networkId = msg.getNetworkId(); - if (networkId == SocialNetwork.VODAFONE.ordinal()) { + + /** Search for a Local Contact ID. **/ + if (chatMessage.getNetworkId() == SocialNetwork.VODAFONE.ordinal()) { + Long userId = null; + + /** Try with parsed User ID. **/ try { - Long id = Long.valueOf(msg.getUserId()); - msg.setLocalContactId(ContactsTable.fetchLocalIdFromUserId(id, databaseHelper.getReadableDatabase())); + userId = Long.valueOf(chatMessage.getUserId()); + } catch (NumberFormatException e) { - LogUtils.logE("ChatDbUtils.convertUserIds() Original userid: " + originalUserId); + LogUtils.logE("ChatDbUtils.convertUserIds() User ID not a long [" + + chatMessage.getUserId() + "], trying original."); + + /** Try with original User ID. **/ + try { + userId = Long.valueOf(originalUserId); + + } catch (NumberFormatException ef) { + LogUtils.logE("ChatDbUtils.convertUserIds() Original user ID " + + "not a long [" + chatMessage.getUserId() + + "], local contact ID left unset"); + } + } + + if (userId != null) { + chatMessage.setLocalContactId(ContactsTable.fetchLocalIdFromUserId( + userId, databaseHelper.getReadableDatabase())); } + } else { - msg.setLocalContactId(ContactDetailsTable.findLocalContactIdByKey(SocialNetwork - .getChatValue(networkId).toString(), msg.getUserId(), - ContactDetail.DetailKeys.VCARD_IMADDRESS, databaseHelper - .getReadableDatabase())); + chatMessage.setLocalContactId( + ContactDetailsTable.findLocalContactIdByKey( + SocialNetwork.getChatValue( + chatMessage.getNetworkId()).toString(), + chatMessage.getUserId(), + ContactDetail.DetailKeys.VCARD_IMADDRESS, + databaseHelper.getReadableDatabase()) + ); } } /** * This method saves the supplied * * @param msg * @param type * @param databaseHelper */ protected static void saveChatMessageAsATimeline(ChatMessage message, TimelineSummaryItem.Type type, DatabaseHelper databaseHelper) { TimelineSummaryItem item = new TimelineSummaryItem(); fillInContactDetails(message, item, databaseHelper, type); SQLiteDatabase writableDatabase = databaseHelper.getWritableDatabase(); boolean isRead = true; if(type == TimelineSummaryItem.Type.INCOMING) { isRead = false; } if (ActivitiesTable.addChatTimelineEvent(item, isRead, writableDatabase) != -1) { ConversationsTable.addNewConversationId(message, writableDatabase); } else { LogUtils.logE("The msg was not saved to the ActivitiesTable"); } } /** * Remove hard code * * @param msg * @param item * @param databaseHelper * @param incoming */ private static void fillInContactDetails(ChatMessage msg, TimelineSummaryItem item, DatabaseHelper databaseHelper, TimelineSummaryItem.Type incoming) { item.mTimestamp = System.currentTimeMillis(); // here we set the time stamp back into the chat message // in order to be able to remove it from the chat history by time stamp in case its delivery fails msg.setTimeStamp(item.mTimestamp); item.mType = ActivityItem.Type.MESSAGE_IM_CONVERSATION; item.mDescription = msg.getBody(); item.mTitle = DateFormat.getDateInstance().format(new Date(item.mTimestamp)); // we store sender's localContactId for incoming msgs and recipient's // localContactId for outgoing msgs item.mLocalContactId = msg.getLocalContactId(); if (item.mLocalContactId != null && item.mLocalContactId != -1) { ContactDetail cd = ContactDetailsTable.fetchDetail(item.mLocalContactId, DetailKeys.VCARD_NAME, databaseHelper.getReadableDatabase()); if (cd == null || cd.getName() == null) { // if we don't get any details, we have to check the summary // table because gtalk contacts // without name will be otherwise show as unknown ContactSummary contactSummary = new ContactSummary(); ServiceStatus error = ContactSummaryTable.fetchSummaryItem(item.mLocalContactId, contactSummary, databaseHelper.getReadableDatabase()); if (error == ServiceStatus.SUCCESS) { item.mContactName = (contactSummary.formattedName != null) ? contactSummary.formattedName : ContactDetail.UNKNOWN_NAME; } else { item.mContactName = ContactDetail.UNKNOWN_NAME; } } else { /** Get name from contact details. **/ VCardHelper.Name name = cd.getName(); item.mContactName = (name != null) ? name.toString() : ContactDetail.UNKNOWN_NAME; } } item.mIncoming = incoming; item.mContactNetwork = SocialNetwork.getChatValue(msg.getNetworkId()).toString(); item.mNativeItemType = TimelineNativeTypes.ChatLog.ordinal(); } /** * This method copies the conversation id and user id into the supplied * ChatMessage based on its mNetworkId and mLocalContactId * * @param chatMessage ChatMessage * @param databaseHelper Databasehelper */ protected static void fillMessageByLocalContactIdAndNetworkId(ChatMessage chatMessage, DatabaseHelper databaseHelper) { ConversationsTable.fillMessageInByLocalContactIdAndNetworkId(chatMessage, databaseHelper .getReadableDatabase(), databaseHelper.getWritableDatabase()); } /** * This method finds the user id (360 UserId or 3rd-party network id) and * sets it into the supplied chat message * * @param msg ChatMessage - the supplied chat message * @param databaseHelper DatabaseHelper - the database */ protected static void findUserIdForMessageByLocalContactIdAndNetworkId(ChatMessage msg, DatabaseHelper databaseHelper) { List<String> tos = new ArrayList<String>(); if (msg.getNetworkId() == SocialNetwork.VODAFONE.ordinal()) { msg.setUserId(String.valueOf(ContactsTable.fetchUserIdFromLocalContactId(msg .getLocalContactId(), databaseHelper.getReadableDatabase()))); tos.add(msg.getUserId()); } else { msg.setUserId(ContactDetailsTable.findChatIdByLocalContactIdAndNetwork(SocialNetwork .getChatValue(msg.getNetworkId()).toString(), msg.getLocalContactId(), databaseHelper.getReadableDatabase())); String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + COLUMNS + msg.getUserId(); tos.add(fullUserId); msg.setUserId(fullUserId); } msg.setTos(tos); } /** * This method deletes the conversation with the given id from the * ConversationsTable * * @param conversationId String - the conversation id * @param dbHelper DatabaseHelper - the database */ protected static void deleteConversationById(String conversationId, DatabaseHelper dbHelper) { ConversationsTable.removeConversation(conversationId, dbHelper.getWritableDatabase()); } /** * This method deletes conversations older than 1 week except for those with * current contact * * @param localContactId long- current contact mLocalContactId * @param dbHelper DatabaseHelper - the database */ protected static void cleanOldConversationsExceptForContact(long localContactId, DatabaseHelper dbHelper) { ActivitiesTable.removeChatTimelineExceptForContact(localContactId, dbHelper .getWritableDatabase()); } /** * This method returns the number of unread chat messages for this contact * * @param localContactId long - the contact's mLocalContactId * @param network String - the specified network, @see SocialNetwork * @param dbHelper Database - the database * @return int - the number of unread chat messages for the specified * contact */ public static int getNumberOfUnreadChatMessagesForContactAndNetwork(long localContactId, String network, DatabaseHelper dbHelper) { return ActivitiesTable.getNumberOfUnreadChatMessagesForContactAndNetwork(localContactId, network, dbHelper.getReadableDatabase()); } /** * This method deletes the last outgoing chat message in * ActivitiesTable, and removes the conversation id of this message from the * ConversationsTable. So that next time when user tries to send a message a * new conversation id will be requested. The message sending might fail * because the conversation id might have expired. * * Currently there's no reliable way to get the reason of message delivery failure, so * we assume that an expired conversation id might cause it as well, and remove it. * * In case the conversation id is valid the "get conversation" call will return the old id. * * @param dbHelper DatabaseHelper - database * @param message ChatMessage - the chat message which has not been sent and needs to be deleted from the history. */ protected static void deleteUnsentMessage(DatabaseHelper dbHelper, ChatMessage message) { ConversationsTable.removeConversation(message.getConversationId(), dbHelper.getWritableDatabase()); ActivitiesTable.deleteUnsentChatMessageForContact(message.getLocalContactId(), message.getTimeStamp(), dbHelper.getWritableDatabase()); } } diff --git a/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTableTest.java b/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTableTest.java index da78453..f093823 100644 --- a/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTableTest.java +++ b/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTableTest.java @@ -1,421 +1,423 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.tests.database; import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.ListIterator; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; import android.util.Log; import com.vodafone360.people.database.DatabaseHelper.ServerIdInfo; import com.vodafone360.people.database.tables.ContactsTable; import com.vodafone360.people.database.tables.ContactsTable.ContactIdInfo; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.tests.TestModule; public class NowPlusContactsTableTest extends NowPlusTableTestCase { final TestModule mTestModule = new TestModule(); final static int NUM_OF_CONTACTS = 50; private int mTestStep = 0; private static String LOG_TAG = "NowPlusContactsTableTest"; public NowPlusContactsTableTest() { super(); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } private void startSubTest(String function, String description) { Log.i(LOG_TAG, function + " - step " + mTestStep + ": " + description); mTestStep++; } private void createTable() { try { ContactsTable.create(mTestDatabase.getWritableDatabase()); } catch (SQLException e) { fail("An exception occurred when creating the table: " + e); } } @SmallTest public void testCreate() { Log.i(LOG_TAG, "***** EXECUTING testCreate *****"); final String fnName = "testCreate"; mTestStep = 1; startSubTest(fnName, "Creating table"); createTable(); Log.i(LOG_TAG, "*************************************"); Log.i(LOG_TAG, "testCreate has completed successfully"); Log.i(LOG_TAG, "**************************************"); Log.i(LOG_TAG, ""); } @MediumTest public void testAddFetchContact() { final String fnName = "testAddContact"; mTestStep = 1; Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****"); Log.i(LOG_TAG, "Adds and fetches a contact from the contacts table, validating all the way"); startSubTest(fnName, "Add Contact before creating a table"); Contact contact = mTestModule.createDummyContactData(); ServiceStatus status = ContactsTable.addContact(contact, mTestDatabase .getReadableDatabase()); assertEquals(ServiceStatus.ERROR_DATABASE_CORRUPT, status); startSubTest(fnName, "Fetch Contact before creating a table"); status = ContactsTable.fetchContact(-1L, contact, mTestDatabase .getReadableDatabase()); assertEquals(ServiceStatus.ERROR_DATABASE_CORRUPT, status); startSubTest(fnName, "Creating table"); createTable(); startSubTest(fnName, "Add Contact"); status = ContactsTable.addContact(contact, mTestDatabase .getReadableDatabase()); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Fetch added contact"); Contact fetchedContact = new Contact(); status = ContactsTable.fetchContact(contact.localContactID, fetchedContact, mTestDatabase.getReadableDatabase()); assertEquals(ServiceStatus.SUCCESS, status); assertTrue(TestModule.doContactsFieldsMatch(contact, fetchedContact)); startSubTest(fnName, "Fetch contact with wrong id"); status = ContactsTable.fetchContact(-1L, fetchedContact, mTestDatabase .getReadableDatabase()); assertEquals(ServiceStatus.ERROR_NOT_FOUND, status); Log.i(LOG_TAG, "***********************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "***********************************************"); Log.i(LOG_TAG, ""); } @MediumTest public void testDeleteContact() { final String fnName = "testDeleteContact"; mTestStep = 1; Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****"); Log.i(LOG_TAG, "Deltes a contact from the contacts table, validating all the way"); // Try to delete contact before creating a table SQLiteDatabase db = mTestDatabase.getWritableDatabase(); ServiceStatus status = ContactsTable.deleteContact(-1L, db); assertEquals(ServiceStatus.ERROR_DATABASE_CORRUPT, status); startSubTest(fnName, "Creating table"); createTable(); startSubTest(fnName, "Add Contact"); Contact contact = mTestModule.createDummyContactData(); status = ContactsTable.addContact(contact, mTestDatabase .getReadableDatabase()); assertEquals(ServiceStatus.SUCCESS, status); status = ContactsTable.deleteContact(contact.localContactID - 1, db); assertEquals(ServiceStatus.ERROR_NOT_FOUND, status); status = ContactsTable.deleteContact(contact.localContactID, db); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Fetch deleted contact"); Contact fetchedContact = new Contact(); status = ContactsTable.fetchContact(contact.localContactID, fetchedContact, db); assertEquals(ServiceStatus.ERROR_NOT_FOUND, status); Log.i(LOG_TAG, "***********************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "***********************************************"); Log.i(LOG_TAG, ""); } @MediumTest public void testModifyContact() { final String fnName = "testModifyContact"; mTestStep = 1; Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****"); Log.i(LOG_TAG, "Modifies a contact in the contacts table, validating all the way"); // Try to modify contact before creating a table SQLiteDatabase db = mTestDatabase.getWritableDatabase(); Contact contact = mTestModule.createDummyContactData(); ServiceStatus status = ContactsTable.modifyContact(contact, db); assertEquals(ServiceStatus.ERROR_DATABASE_CORRUPT, status); startSubTest(fnName, "Creating table"); createTable(); // Try to modify contact before adding to a table status = ContactsTable.modifyContact(contact, db); assertEquals(ServiceStatus.ERROR_NOT_FOUND, status); startSubTest(fnName, "Add Contact"); status = ContactsTable.addContact(contact, mTestDatabase .getReadableDatabase()); assertEquals(ServiceStatus.SUCCESS, status); Contact modifiedContact = mTestModule.createDummyContactData(); modifiedContact.localContactID = contact.localContactID; status = ContactsTable.modifyContact(modifiedContact, db); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Fetch modified contact"); Contact fetchedContact = new Contact(); status = ContactsTable.fetchContact(modifiedContact.localContactID, fetchedContact, db); assertEquals(ServiceStatus.SUCCESS, status); assertTrue(TestModule.doContactsFieldsMatch(modifiedContact, fetchedContact)); Log.i(LOG_TAG, "***********************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "***********************************************"); Log.i(LOG_TAG, ""); } @MediumTest public void testValidateContactId() { final String fnName = "testValidateContactId"; mTestStep = 1; Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****"); Log.i(LOG_TAG, "Validates a contact id"); SQLiteDatabase writableDb = mTestDatabase.getWritableDatabase(); SQLiteDatabase readableDb = mTestDatabase.getWritableDatabase(); startSubTest(fnName, "Creating table"); createTable(); startSubTest(fnName, "Add Contact"); Contact contact = mTestModule.createDummyContactData(); Long serverId = TestModule.generateRandomLong(); ServiceStatus status = ContactsTable.addContact(contact, readableDb); assertEquals(ServiceStatus.SUCCESS, status); assertTrue(ContactsTable.modifyContactServerId(contact.localContactID, serverId, contact.userID, writableDb)); ContactIdInfo idInfo = ContactsTable.validateContactId( contact.localContactID, readableDb); assertEquals(serverId, idInfo.serverId); assertTrue(contact.localContactID == idInfo.localId); Long fetchedServerId = ContactsTable.fetchServerId( contact.localContactID, readableDb); assertEquals(serverId, fetchedServerId); SQLiteStatement statement = ContactsTable.fetchLocalFromServerIdStatement(readableDb); assertTrue(statement != null); Long localId = ContactsTable.fetchLocalFromServerId(serverId, statement); assertEquals(Long.valueOf(idInfo.localId), localId); localId = ContactsTable.fetchLocalFromServerId(serverId, null); assertEquals(localId, null); Log.i(LOG_TAG, "***********************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "***********************************************"); Log.i(LOG_TAG, ""); } @MediumTest public void testServerSyncMethods() { final String fnName = "testServerSyncMethods"; mTestStep = 1; Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****"); Log.i(LOG_TAG, "Validates server sync methods"); SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase(); SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase(); startSubTest(fnName, "Creating table"); createTable(); // add contacts and populate contactServerIdList List<ServerIdInfo> contactServerIdList = new ArrayList<ServerIdInfo>(); final long contactIdBase = TestModule.generateRandomLong(); for (int i = 0; i < NUM_OF_CONTACTS; i++) { Contact c = mTestModule.createDummyContactData(); if (i == 2) { // Add duplicate server ID in database c.contactID = contactIdBase; } c.userID = TestModule.generateRandomLong(); ServiceStatus status = ContactsTable.addContact(c, writeableDb); assertEquals(ServiceStatus.SUCCESS, status); ServerIdInfo serverInfo = new ServerIdInfo(); serverInfo.localId = c.localContactID; serverInfo.serverId = contactIdBase + i; serverInfo.userId = c.userID; contactServerIdList.add(serverInfo); } // Add duplicate server ID in list from server Contact duplicateContact = mTestModule.createDummyContactData(); duplicateContact.userID = TestModule.generateRandomLong(); ServiceStatus status = ContactsTable.addContact(duplicateContact, writeableDb); assertEquals(ServiceStatus.SUCCESS, status); ServerIdInfo serverInfo = new ServerIdInfo(); serverInfo.localId = duplicateContact.localContactID; serverInfo.serverId = contactIdBase + 1; serverInfo.userId = duplicateContact.userID; contactServerIdList.add(serverInfo); List<ContactIdInfo> dupList = new ArrayList<ContactIdInfo>(); status = ContactsTable.syncSetServerIds(contactServerIdList, dupList, writeableDb); assertEquals(ServiceStatus.SUCCESS, status); // fetch server ids - ArrayList<Long> serverIds = new ArrayList<Long>(); + HashSet<Long> serverIds = new HashSet<Long>(); status = ContactsTable.fetchContactServerIdList(serverIds, readableDb); assertEquals(ServiceStatus.SUCCESS, status); // validate if lists have the same sizes assertEquals(2, dupList.size()); assertEquals(contactServerIdList.size() - 2, serverIds.size()); - final ListIterator<Long> serverIdsIt = serverIds.listIterator(); + final Iterator<Long> serverIdsIt = serverIds.iterator(); assertEquals(Long.valueOf(dupList.get(0).localId), contactServerIdList.get(0).localId); assertEquals(contactServerIdList.get(0).serverId, dupList.get(0).serverId); assertEquals(duplicateContact.localContactID, Long.valueOf(dupList.get(1).localId)); assertEquals(Long.valueOf(contactIdBase + 1), dupList.get(1).serverId); for (int i = 1; i < contactServerIdList.size() - 1; i++) { Long actServerId = serverIdsIt.next(); assertEquals(contactServerIdList.get(i).serverId, actServerId); } Log.i(LOG_TAG, "***********************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "***********************************************"); Log.i(LOG_TAG, ""); } @MediumTest public void testFetchContactFormNativeId() { final String fnName = "testFetchContactFormNativeId"; mTestStep = 1; Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****"); Log.i(LOG_TAG, "tests fetchContactFormNativeId a contact id"); SQLiteDatabase writableDb = mTestDatabase.getWritableDatabase(); startSubTest(fnName, "Creating table"); createTable(); startSubTest(fnName, "Add Contact"); Contact contact = mTestModule.createDummyContactData(); contact.userID = TestModule.generateRandomLong(); contact.nativeContactId = TestModule.generateRandomInt(); Long serverId = TestModule.generateRandomLong(); ServiceStatus status = ContactsTable.addContact(contact, writableDb); assertEquals(ServiceStatus.SUCCESS, status); assertTrue(ContactsTable.modifyContactServerId(contact.localContactID, serverId, contact.userID, writableDb)); ContactIdInfo idInfo = ContactsTable.fetchContactIdFromNative( contact.nativeContactId, writableDb); assertTrue(idInfo.localId == contact.localContactID); assertEquals(serverId, idInfo.serverId); Log.i(LOG_TAG, "***********************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "***********************************************"); Log.i(LOG_TAG, ""); } @MediumTest public void testSyncSetNativeIds() { final String fnName = "testSyncSetNativeIds"; mTestStep = 1; Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****"); SQLiteDatabase writableDb = mTestDatabase.getWritableDatabase(); SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase(); startSubTest(fnName, "Creating table"); createTable(); // add contacts and populate contactServerIdList ServiceStatus status; List<ContactIdInfo> contactIdList = new ArrayList<ContactIdInfo>(); for (int i = 0; i < NUM_OF_CONTACTS; i++) { Contact c = mTestModule.createDummyContactData(); c.userID = TestModule.generateRandomLong(); status = ContactsTable.addContact(c, writableDb); assertEquals(ServiceStatus.SUCCESS, status); ContactIdInfo contactInfo = new ContactIdInfo(); contactInfo.localId = c.localContactID; contactInfo.nativeId = TestModule.generateRandomInt(); contactIdList.add(contactInfo); } status = ContactsTable.syncSetNativeIds(contactIdList, writableDb); assertEquals(ServiceStatus.SUCCESS, status); for (ContactIdInfo contactIdInfo : contactIdList) { Contact fetchedContact = new Contact(); status = ContactsTable.fetchContact(contactIdInfo.localId, fetchedContact, readableDb); assertEquals(ServiceStatus.SUCCESS, status); assertEquals(contactIdInfo.nativeId, fetchedContact.nativeContactId); } } } diff --git a/tests/src/com/vodafone360/people/tests/engine/presence/ChatDbUtilsTest.java b/tests/src/com/vodafone360/people/tests/engine/presence/ChatDbUtilsTest.java new file mode 100644 index 0000000..b815f45 --- /dev/null +++ b/tests/src/com/vodafone360/people/tests/engine/presence/ChatDbUtilsTest.java @@ -0,0 +1,183 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the Common Development + * and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at + * src/com/vodafone360/people/VODAFONE.LICENSE.txt or + * http://github.com/360/360-Engine-for-Android + * See the License for the specific language governing permissions and + * limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each file and + * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. + * If applicable, add the following below this CDDL HEADER, with the fields + * enclosed by brackets "[]" replaced with your own identifying information: + * Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + * + * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. + * Use is subject to license terms. + */ + +package com.vodafone360.people.tests.engine.presence; + +import android.test.ApplicationTestCase; + +import com.vodafone360.people.MainApplication; +import com.vodafone360.people.database.DatabaseHelper; +import com.vodafone360.people.datatypes.ChatMessage; +import com.vodafone360.people.engine.presence.ChatDbUtils; +import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; + +/*** + * Tests for the ChatDbUtils class. + */ +public class ChatDbUtilsTest extends ApplicationTestCase<MainApplication> { + + /** Test network ID value, which should never be returned by the code. **/ + private static final int NETWORK_ID = -2; + /** Test local contact ID value, which can be returned by the code. **/ + private static final Long LOCAL_CONTACT_ID = -1L; + /** Reference to database. **/ + private DatabaseHelper mDatabaseHelper; + + /*** + * Constructor. + */ + public ChatDbUtilsTest() { + super(MainApplication.class); + } + + /*** + * Set up the DatabaseHelper. + */ + public final void setUp() { + createApplication(); + MainApplication mainApplication = getApplication(); + if (mainApplication == null) { + throw(new RuntimeException("ChatDbUtilsTest.setUp() " + + "Unable to create main application")); + } + mDatabaseHelper = mainApplication.getDatabase(); + } + + /*** + * Close the DatabaseHelper. + */ + public final void tearDown() { + mDatabaseHelper.getReadableDatabase().close(); + } + + /*** + * JUnit test for the ChatDbUtils.convertUserIds() method. + * + * @see com.vodafone360.people.tests.engine.presence.ChatDbUtils + * #convertUserIds(ChatMessage msg, DatabaseHelper databaseHelper) + */ + public final void testConvertUserIds() { + + /** SNS test. **/ + testConvertUserId( + "123456", NETWORK_ID, LOCAL_CONTACT_ID, + "123456", SocialNetwork.VODAFONE, -1L); + testConvertUserId( + "facebook.com::123456", NETWORK_ID, LOCAL_CONTACT_ID, + "123456", SocialNetwork.FACEBOOK_COM, -1L); + testConvertUserId( + "hyves.nl::123456", NETWORK_ID, LOCAL_CONTACT_ID, + "123456", SocialNetwork.HYVES_NL, -1L); + testConvertUserId( + "google::123456", NETWORK_ID, LOCAL_CONTACT_ID, + "123456", SocialNetwork.GOOGLE, -1L); + testConvertUserId( + "microsoft::123456", NETWORK_ID, LOCAL_CONTACT_ID, + "123456", SocialNetwork.MICROSOFT, -1L); + + /** Never happens. **/ + testConvertUserId( + "mobile::123456", NETWORK_ID, LOCAL_CONTACT_ID, + "123456", SocialNetwork.MOBILE, -1L); + testConvertUserId( + "pc::123456", NETWORK_ID, LOCAL_CONTACT_ID, + "123456", SocialNetwork.PC, -1L); + testConvertUserId( + "vodafone::123456", NETWORK_ID, LOCAL_CONTACT_ID, + "123456", SocialNetwork.VODAFONE, -1L); + + /** Parsing test. **/ + testConvertUserId( + "facebook.com::123456", NETWORK_ID, LOCAL_CONTACT_ID, + "123456", SocialNetwork.FACEBOOK_COM, -1L); + testConvertUserId( + "facebook_com::", NETWORK_ID, LOCAL_CONTACT_ID, + "", SocialNetwork.FACEBOOK_COM, -1L); + + /** Issue seen in PAND-2356. **/ + testConvertUserId( + "facebook_com::[email protected]", + NETWORK_ID, LOCAL_CONTACT_ID, + "[email protected]", + SocialNetwork.FACEBOOK_COM, -1L); + + /** Issue seen in PAND-2408. **/ + testConvertUserId( + "google::[email protected]", + NETWORK_ID, LOCAL_CONTACT_ID, + "[email protected]", SocialNetwork.GOOGLE, + -1L); + + /** Invalid tests. **/ + testConvertUserId( + "unknown_network::123456", NETWORK_ID, LOCAL_CONTACT_ID, + "123456", SocialNetwork.INVALID, -1L); + testConvertUserId( + "::123456", NETWORK_ID, LOCAL_CONTACT_ID, + "123456", SocialNetwork.INVALID, -1L); + testConvertUserId( + "unknown_network::", NETWORK_ID, LOCAL_CONTACT_ID, + "", SocialNetwork.INVALID, -1L); + testConvertUserId( + "::", NETWORK_ID, LOCAL_CONTACT_ID, + "", SocialNetwork.INVALID, -1L); + testConvertUserId( + "", NETWORK_ID, LOCAL_CONTACT_ID, + "", SocialNetwork.VODAFONE, -1L); + } + + /*** + * Test ChatDbUtils.convertUserIds() method with a given parameter + * combination. + * + * @param userId User ID. + * @param networkId Network ID. + * @param localContactId Local Contact ID. + * @param expectedUserId Expected User ID. + * @param expectedNetwork Expected Network ID. + * @param expectedLocalContactId Expected Local Contact ID. + */ + private void testConvertUserId(final String userId, + final int networkId, final Long localContactId, + final String expectedUserId, + final SocialNetwork expectedNetwork, + final Long expectedLocalContactId) { + + ChatMessage chatMessage = new ChatMessage(); + chatMessage.setUserId(userId); + chatMessage.setNetworkId(networkId); + chatMessage.setLocalContactId(localContactId); + + ChatDbUtils.convertUserIds(chatMessage, mDatabaseHelper); + + assertEquals("ChatDbUtilsTest.checkChatMessage() Unexpected user ID", + expectedUserId, chatMessage.getUserId()); + assertEquals("ChatDbUtilsTest.checkChatMessage() Unexpected network ID [" + + expectedNetwork + "]", + expectedNetwork.ordinal(), chatMessage.getNetworkId()); + assertEquals("ChatDbUtilsTest.checkChatMessage() Unexpected local contact ID", + expectedLocalContactId, chatMessage.getLocalContactId()); + } +} diff --git a/tests/src/com/vodafone360/people/tests/engine/PresenceEngineTest.java b/tests/src/com/vodafone360/people/tests/engine/presence/PresenceEngineTest.java similarity index 94% rename from tests/src/com/vodafone360/people/tests/engine/PresenceEngineTest.java rename to tests/src/com/vodafone360/people/tests/engine/presence/PresenceEngineTest.java index 43f032e..22c9c01 100644 --- a/tests/src/com/vodafone360/people/tests/engine/PresenceEngineTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/presence/PresenceEngineTest.java @@ -1,256 +1,258 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ -package com.vodafone360.people.tests.engine; +package com.vodafone360.people.tests.engine.presence; import android.test.InstrumentationTestCase; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.PresenceEngine; +import com.vodafone360.people.tests.engine.EngineTestFramework; +import com.vodafone360.people.tests.engine.IEngineTestFrameworkObserver; public class PresenceEngineTest extends InstrumentationTestCase implements IEngineTestFrameworkObserver{ /** * States for test harness */ enum PresenceTestState { IDLE, GET_PRESENCE, GET_PRESENCE_FAIL, SET_AVAILBAILITY, GET_NEXT_RUNTIME } private EngineTestFramework mEngineTester = null; private PresenceEngine mEng = null; //private MainApplication mApplication = null; //private PresenceTestState mState = PresenceTestState.IDLE; @Override protected void setUp() throws Exception { super.setUp(); mEngineTester = new EngineTestFramework(this); mEng = new PresenceEngine(mEngineTester, null); //mApplication = (MainApplication)Instrumentation.newApplication(MainApplication.class, getInstrumentation().getTargetContext()); mEngineTester.setEngine(mEng); //mState = PresenceTestState.IDLE; } @Override protected void tearDown() throws Exception { // stop our dummy thread? mEngineTester.stopEventThread(); mEngineTester = null; mEng = null; // call at the end!!! super.tearDown(); } // @MediumTest // public void testFetchIdentities(){ // // mState = IdentityTestState.FETCH_IDENTITIES; // Bundle fbund = new Bundle(); // // NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); // mEng.addUiFetchIdentities(fbund); // //mEng.run(); // ServiceStatus status = mEngineTester.waitForEvent(); // if(status != ServiceStatus.SUCCESS){ // throw(new RuntimeException("Expected SUCCESS")); // } // // Object data = mEngineTester.data(); // assertTrue(data!=null); // try{ // ArrayList<Identity> identityList = ((Bundle) data).getParcelableArrayList("data"); // assertTrue(identityList.size()==1); // } // catch(Exception e){ // throw(new RuntimeException("Expected identity list with 1 item")); // } // // } // @MediumTest // public void testFetchIdentitiesFail(){ // mState = IdentityTestState.FETCH_IDENTITIES_FAIL; // Bundle fbund = new Bundle(); // // NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); // mEng.addUiFetchIdentities(fbund); // //mEng.run(); // ServiceStatus status = mEngineTester.waitForEvent(); // if(status == ServiceStatus.SUCCESS){ // throw(new RuntimeException("Expected FAILURE")); // } // // Object data = mEngineTester.data(); // assertTrue(data==null); // } // // // @MediumTest // public void testSetIdentityCapability(){ // mState = IdentityTestState.SET_IDENTITY_CAPABILTY; // // String network = "facebook"; // Bundle fbund = new Bundle(); // fbund.putBoolean("sync_contacts", true); // String identityId = "mikeyb"; // // NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); // mEng.addUiSetIdentityCapabilityStatus(network, identityId, fbund); // ServiceStatus status = mEngineTester.waitForEvent(); // if(status != ServiceStatus.SUCCESS){ // throw(new RuntimeException("Expected SUCCESS")); // } // // Object data = mEngineTester.data(); // assertTrue(data!=null); // try{ // ArrayList<StatusMsg> identityList = ((Bundle) data).getParcelableArrayList("data"); // assertTrue(identityList.size()==1); // } // catch(Exception e){ // throw(new RuntimeException("Expected identity list with 1 item")); // } // } // // // @MediumTest // public void testValidateIDCredentialsSuccess(){ // mState = IdentityTestState.VALIDATE_ID_CREDENTIALS_SUCCESS; // // NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); // mEng.addUiValidateIdentityCredentials(false, "bob", "password", "", new Bundle()); // ServiceStatus status = mEngineTester.waitForEvent(); // if(status != ServiceStatus.SUCCESS){ // throw(new RuntimeException("Expected SUCCESS")); // } // // Object data = mEngineTester.data(); // assertTrue(data!=null); // } // // // @MediumTest // public void testValidateIDCredentialsFail(){ // mState = IdentityTestState.VALIDATE_ID_CREDENTIALS_FAIL; // // NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); // mEng.addUiValidateIdentityCredentials(false, "bob", "password", "", new Bundle()); // // ServiceStatus status = mEngineTester.waitForEvent(); // if(status == ServiceStatus.SUCCESS){ // throw(new RuntimeException("Expected SUCCESS")); // } // // Object data = mEngineTester.data(); // assertTrue(data==null); // } // // // @MediumTest // public void testGetNextRuntime(){ // mState = IdentityTestState.GET_NEXT_RUNTIME; // long runtime = mEng.getNextRunTime(); // } // // @Override // public void reportBackToEngine(int reqId, EngineId engine) { // Log.d("TAG","IdentityEngineTest.reportBackToEngine"); // ResponseQueue respQueue = ResponseQueue.getInstance(); // List<BaseDataType> data = new ArrayList<BaseDataType>(); // // switch(mState){ // case IDLE: // break; // case FETCH_IDENTITIES: // Log.d("TAG","IdentityEngineTest.reportBackToEngine FETCH ids"); // Identity id = new Identity(); // data.add(id); // respQueue.addToResponseQueue(reqId, data, engine); // Log.d("TAG","IdentityEngineTest.reportBackToEngine add to Q"); // mEng.onCommsInMessage(); // break; // case FETCH_IDENTITIES_FAIL: // ServerError err = new ServerError(); // err.errorType = "Catastrophe"; // err.errorValue = "Fail"; // data.add(err); // respQueue.addToResponseQueue(reqId, data, engine); // mEng.onCommsInMessage(); // break; // case SET_IDENTITY_CAPABILTY: // StatusMsg msg = new StatusMsg(); // msg.mCode = "ok"; // msg.mDryRun = false; // msg.mStatus = true; // data.add(msg); // respQueue.addToResponseQueue(reqId, data, engine); // mEng.onCommsInMessage(); // break; // case VALIDATE_ID_CREDENTIALS_SUCCESS: // StatusMsg msg2 = new StatusMsg(); // msg2.mCode = "ok"; // msg2.mDryRun = false; // msg2.mStatus = true; // data.add(msg2); // respQueue.addToResponseQueue(reqId, data, engine); // mEng.onCommsInMessage(); // break; // case VALIDATE_ID_CREDENTIALS_FAIL: // ServerError err2 = new ServerError(); // err2.errorType = "Catastrophe"; // err2.errorValue = "Fail"; // data.add(err2); // respQueue.addToResponseQueue(reqId, data, engine); // mEng.onCommsInMessage(); // break; // case GET_NEXT_RUNTIME: // break; // default: // } // // } @Override public void reportBackToEngine(int reqId, EngineId engine) { // TODO Auto-generated method stub } @Override public void onEngineException(Exception exp) { // TODO Auto-generated method stub } }
360/360-Engine-for-Android
d08982eaeb0d6bc3775c6de1f74e3feadef962fd
Added hasContactDetail
diff --git a/src/com/vodafone360/people/datatypes/Contact.java b/src/com/vodafone360/people/datatypes/Contact.java index 941c8e3..72f5753 100644 --- a/src/com/vodafone360/people/datatypes/Contact.java +++ b/src/com/vodafone360/people/datatypes/Contact.java @@ -117,537 +117,551 @@ public class Contact extends BaseDataType implements Parcelable, Persistable { /** * The user ID if the contact has been sychronised with the server and the * contact is associated with a user */ @Column(name = "UserId") public Long userID = null; /** * A list of sources which has been fetched from the sources sub-table */ public List<String> sources = null; /** * The timestamp when the contact was last updated on the server */ @Column(name = "Updated") public Long updated = null; /** * The path of the contact thumbnail/avatar on the server */ public String profilePath = null; // only for user profile /** * The gender of the contact received from the server */ @Column(name = "Gender") public Integer gender = null; // only for user profile /** * Contains true if the contacts is marked as a friend */ @Column(name = "Friend") public Boolean friendOfMine = null; /** * Contains true if the contact has been deleted on the server */ public Boolean deleted = null; /** * Internal value which is used to store the primary key of the contact * stored in the native Android addressbook. */ @Column(name = "NativeContactId") public Integer nativeContactId = null; /** * A list of contact details (this contains the main information stored in * the contact such as name, phone number, email, etc.) */ public final List<ContactDetail> details = new ArrayList<ContactDetail>(); /** * A list groups (server IDs) which the contact is a member of */ public List<Long> groupList = null; /** * Set to true if this contact should be synchronised with the native * address book. * <p> * Also determines which contacts are shown in the phonebook group in the * UI. */ @Column(name = "Synctophone") public Boolean synctophone = null; /** * Find Tags item for specified String * * @param tag String value to find Tags item for * @return Tags item for specified String, null otherwise */ private Tags findTag(String tag) { for (Tags tags : Tags.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } LogUtils.logE("Contact.findTag - Unsupported contact tag: " + tag); return null; } /** {@inheritDoc} */ @Override public int getType() { return CONTACT_DATA_TYPE; } /** {@inheritDoc} */ @Override public String toString() { Date time = null; if (updated != null) { time = new Date(updated * 1000); } else { time = new Date(0); } StringBuffer sb = new StringBuffer("--\nContact data:"); sb.append("\n\tLocal Contact ID: "); sb.append(localContactID); sb.append("\n\tContact ID: "); sb.append(contactID); sb.append("\n\tUser ID: "); sb.append(userID); sb.append("\n\tAbout me: "); sb.append(aboutMe); sb.append("\n\tFriend of mine: "); sb.append(friendOfMine); sb.append("\n\tDeleted: "); sb.append(deleted); sb.append("\n\tGender: "); sb.append(gender); sb.append("\n\tSynctophone: "); sb.append(synctophone); sb.append("\n\tNative Contact ID: "); sb.append(nativeContactId); sb.append("\n\tupdated: "); sb.append(updated); sb.append(" Date: "); sb.append(time.toGMTString()); sb.append("\n"); if (sources != null) { sb.append("Sources ("); sb.append(sources.size()); sb.append("): "); for (int i = 0; i < sources.size(); i++) { sb.append(sources.get(i)); sb.append(","); } sb.append("\n"); } if (groupList != null) { sb.append("Group id list = ["); for (int i = 0; i < groupList.size(); i++) { sb.append(groupList.get(i)); if (i < groupList.size() - 1) { sb.append(","); } } sb.append("\n"); } sb.append("Contact details ("); sb.append(details.size()); sb.append("):\n"); for (int i = 0; i < details.size(); i++) { sb.append(details.get(i).toString()); sb.append("\n"); } sb.append("\n--------------------------------------------------"); return sb.toString(); } /** * Create Hashtable representing Contact parameters. This is used to create * Hessian encoded payload for Contacts upload. * * @return Hashtable containing contact parameters. */ public Hashtable<String, Object> createHashtable() { Hashtable<String, Object> htab = new Hashtable<String, Object>(); if (aboutMe != null) { htab.put(Tags.ABOUT_ME.tag(), aboutMe); } if (contactID != null) { htab.put(Tags.CONTACT_ID.tag(), contactID); } if (userID != null) { htab.put(Tags.USER_ID.tag(), userID); } if (updated != null && updated != 0) { htab.put(Tags.UPDATED.tag(), updated); } if (profilePath != null && profilePath.length() > 0) { htab.put(Tags.PROFILE_PATH.tag(), profilePath); } if (friendOfMine != null) { htab.put(Tags.FRIEND.tag(), friendOfMine); } if (deleted != null) { htab.put(Tags.DELETED.tag(), deleted); } if (synctophone != null) { htab.put(Tags.SYNCTOPHONE.tag(), synctophone); } if (groupList != null) { Vector<Long> vL = new Vector<Long>(); for (Long l : groupList) { vL.add(l); } htab.put(Tags.GROUP_LIST.tag(), vL); } if (details != null && details.size() > 0) { Vector<Object> v = new Vector<Object>(); for (int i = 0; i < details.size(); i++) { v.add(details.get(i).createHashtable()); } htab.put(Tags.DETAIL_LIST.tag(), v); } return htab; } /** * Create Contact item from Hashtable generated by Hessian-decoder * * @param hash Hashtable containing Contact parameters * @return Contact item created from hashtable or null if hash was corrupted */ public static Contact createFromHashtable(Hashtable<String, Object> hash) { Contact cont = new Contact(); Enumeration<String> e = hash.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); Object value = hash.get(key); Tags tag = cont.findTag(key); cont.setValue(tag, value); } return cont; } /** * Sets the value of the member data item associated with the specified tag. * * @param tag Current tag * @param val Value associated with the tag */ private void setValue(Tags tag, Object value) { if (tag == null) { LogUtils.logE("Contact setValue tag is null"); return; } switch (tag) { case ABOUT_ME: aboutMe = (String)value; break; case CONTACT_ID: contactID = (Long)value; break; case DETAIL_LIST: @SuppressWarnings("unchecked") Vector<Hashtable<String, Object>> detailsList = (Vector<Hashtable<String, Object>>)value; for (Hashtable<String, Object> detailHashtable : detailsList) { try { // let's try to create the ContactDetail // if failing, the detail will just be skipped final ContactDetail detail = new ContactDetail(); detail.createFromHashtable(detailHashtable); details.add(detail); } catch (Exception e) { LogUtils.logE("Contact.setValue(), the error [" + e + "] occured while adding a detail to the following contact:" + toString()); } } break; case DETAIL: break; case GROUP_LIST: @SuppressWarnings("unchecked") Vector<Long> gL = (Vector<Long>)value; groupList = new ArrayList<Long>(); for (Long l : gL) { groupList.add(l); } break; case UPDATED: updated = (Long)value; break; case USER_ID: userID = (Long)value; break; case SOURCES: if (sources == null) { sources = new ArrayList<String>(); } @SuppressWarnings("unchecked") Vector<String> vals = (Vector<String>)value; for (String source : vals) { sources.add(source); } break; case DELETED: deleted = (Boolean)value; break; case FRIEND: friendOfMine = (Boolean)value; break; case GENDER: if (gender == null) { gender = (Integer)value; } break; case SYNCTOPHONE: synctophone = (Boolean)value; break; default: // Do nothing. break; } } /** * Copy parameters from UserProfile object. * * @param source UserProfile object to populate Contact with. */ public void copy(UserProfile source) { userID = source.userID; profilePath = source.profilePath; contactID = source.contactID; if (source.sources != null && source.sources.size() > 0) { if (sources == null) { sources = new ArrayList<String>(); } else { sources.clear(); } sources.addAll(source.sources); } else { sources = null; } gender = source.gender; details.clear(); details.addAll(source.details); aboutMe = source.aboutMe; friendOfMine = source.friendOfMine; updated = source.updated; localContactID = null; deleted = null; nativeContactId = null; groupList = null; synctophone = null; } /** * Member data definitions used when reading and writing Contact from/to * Parcels. */ private enum MemberData { LOCALID, NAME, ABOUTME, CONTACTID, USERID, SOURCES, GENDER, UPDATED, PROFILEPATH, FRIENDOFMINE, DELETED, NATIVE_CONTACT_ID, SYNCTOPHONE; } /** * Read Contact from Parcel. * Note: only called from tests. * * @param in Parcel containing Contact item. */ public void readFromParcel(Parcel in) { aboutMe = null; contactID = null; userID = null; sources = null; gender = null; updated = null; profilePath = null; friendOfMine = null; deleted = null; nativeContactId = null; groupList = null; synctophone = null; boolean[] validDataList = new boolean[MemberData.values().length]; in.readBooleanArray(validDataList); if (validDataList[MemberData.LOCALID.ordinal()]) { localContactID = in.readLong(); } if (validDataList[MemberData.ABOUTME.ordinal()]) { aboutMe = in.readString(); } if (validDataList[MemberData.CONTACTID.ordinal()]) { contactID = in.readLong(); } if (validDataList[MemberData.USERID.ordinal()]) { userID = in.readLong(); } if (validDataList[MemberData.SOURCES.ordinal()]) { sources = new ArrayList<String>(); in.readStringList(sources); } if (validDataList[MemberData.GENDER.ordinal()]) { gender = in.readInt(); } if (validDataList[MemberData.SYNCTOPHONE.ordinal()]) { synctophone = (in.readByte() == 0 ? false : true); } if (validDataList[MemberData.UPDATED.ordinal()]) { updated = in.readLong(); } if (validDataList[MemberData.PROFILEPATH.ordinal()]) { profilePath = in.readString(); } if (validDataList[MemberData.FRIENDOFMINE.ordinal()]) { friendOfMine = (in.readByte() == 0 ? false : true); } if (validDataList[MemberData.DELETED.ordinal()]) { deleted = (in.readByte() == 0 ? false : true); } if (validDataList[MemberData.NATIVE_CONTACT_ID.ordinal()]) { nativeContactId = in.readInt(); } int noOfDetails = in.readInt(); details.clear(); for (int i = 0; i < noOfDetails; i++) { ContactDetail detail = ContactDetail.CREATOR.createFromParcel(in); details.add(detail); } } /** {@inheritDoc} */ @Override public int describeContents() { return 1; } /** {@inheritDoc} * * Note: only called from tests. */ @Override public void writeToParcel(Parcel dest, int flags) { boolean[] validDataList = new boolean[MemberData.values().length]; int validDataPos = dest.dataPosition(); dest.writeBooleanArray(validDataList); // placeholder for real array if (localContactID != null) { validDataList[MemberData.LOCALID.ordinal()] = true; dest.writeLong(localContactID); } if (aboutMe != null) { validDataList[MemberData.ABOUTME.ordinal()] = true; dest.writeString(aboutMe); } if (contactID != null) { validDataList[MemberData.CONTACTID.ordinal()] = true; dest.writeLong(contactID); } if (userID != null) { validDataList[MemberData.USERID.ordinal()] = true; dest.writeLong(userID); } if (sources != null && sources.size() > 0) { validDataList[MemberData.SOURCES.ordinal()] = true; dest.writeStringList(sources); } if (gender != null) { validDataList[MemberData.GENDER.ordinal()] = true; dest.writeInt(gender); } if (updated != null) { validDataList[MemberData.UPDATED.ordinal()] = true; dest.writeLong(updated); } if (profilePath != null) { validDataList[MemberData.PROFILEPATH.ordinal()] = true; dest.writeString(profilePath); } if (friendOfMine != null) { validDataList[MemberData.FRIENDOFMINE.ordinal()] = true; dest.writeByte((byte)(friendOfMine ? 1 : 0)); } if (deleted != null) { validDataList[MemberData.DELETED.ordinal()] = true; dest.writeByte((byte)(deleted ? 1 : 0)); } if (synctophone != null) { validDataList[MemberData.SYNCTOPHONE.ordinal()] = true; dest.writeByte((byte)(synctophone ? 1 : 0)); } if (nativeContactId != null) { validDataList[MemberData.NATIVE_CONTACT_ID.ordinal()] = true; dest.writeInt(nativeContactId); } int currentPos = dest.dataPosition(); dest.setDataPosition(validDataPos); dest.writeBooleanArray(validDataList); // real array dest.setDataPosition(currentPos); dest.writeInt(details.size()); for (ContactDetail detail : details) { detail.writeToParcel(dest, 0); } } /** * Fetches the preffered ContactDetail for this Contact for example the * preffered phone number or email address If no such is found, an * unpreffered contact will be taken * * @param detailKey The type of the Detail (PHONE, EMAIL_ADDRESS) * @return preffered ContactDetail, any ContactDetail if no preferred is * found or null if no detail at all is found */ public ContactDetail getContactDetail(ContactDetail.DetailKeys detailKey) { ContactDetail preffered = getPrefferedContactDetail(detailKey); if (preffered != null) return preffered; for (ContactDetail detail : details) { if (detail != null && detail.key == detailKey) return detail; } return null; } + /** + * Checks if the specified contact detail is available. + * @return <code>true</code> if the contact detail has been found, <code>false</code> otherwise. + */ + public boolean hasContactDetail(ContactDetail.DetailKeys detailKey) { + for (final ContactDetail detail : details) { + if (detail != null && detail.key == detailKey) { + return true; + } + } + return false; + } + + /** * Fetches the preffered ContactDetail for this Contact and a DetailKey for * example the preffered phone number or email address * * @param detailKey The type of the Detail (PHONE, EMAIL_ADDRESS) * @return preffered ContactDetail or null if no such is found */ private ContactDetail getPrefferedContactDetail(ContactDetail.DetailKeys detailKey) { for (ContactDetail detail : details) { if (detail != null && detail.key == detailKey && detail.order == ContactDetail.ORDER_PREFERRED) return detail; } return null; } public String getDetailString() { StringBuilder sb = new StringBuilder(); for (ContactDetail detail : details) { sb.append(detail.getValue()); sb.append("|"); } return sb.toString(); } }
360/360-Engine-for-Android
459ef2be796c95a869c28ce91f5b97f35836f2d8
Fix for PAND-1184: Date of birth not synced when possible
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index 1f4d3fd..42c52bc 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,1760 +1,1783 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import android.accounts.AccountManager; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.OperationApplicationException; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.provider.ContactsContract; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.Settings; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Event; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.Website; import android.text.TextUtils; import android.util.SparseArray; import com.vodafone360.people.R; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.VCardHelper.Name; import com.vodafone360.people.datatypes.VCardHelper.Organisation; import com.vodafone360.people.datatypes.VCardHelper.PostalAddress; import com.vodafone360.people.service.SyncAdapter; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * The implementation of the NativeContactsApi for the Android 2.X platform. */ public class NativeContactsApi2 extends NativeContactsApi { /** * Convenience Projection to fetch only a Raw Contact's ID and Native * Account Type */ private static final String[] CONTACTID_PROJECTION = new String[] { RawContacts._ID, RawContacts.ACCOUNT_TYPE }; /** * Raw ID Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_RAW_ID = 0; /** * Account Type Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_ACCOUNT_TYPE = 1; /** * Group ID Projection */ private static final String[] GROUPID_PROJECTION = new String[] { Groups._ID }; /** * Vendor specific account. Only used in 2.x API. */ private static Account sPhoneAccount = null; /** * Regular expression for a date that can be handled by the People Client at * present. Matches the following cases: N-n-n n-n-N Where: - 'n' * corresponds to one or two digits - 'N' corresponds to two or 4 digits */ - private static final String COMPLETE_DATE_REGEX = "(?:^\\d{2,4}-\\d{1,2}-\\d{1,2}$|^\\d{1,2}-\\d{1,2}-\\d{2,4}$)"; + public static final String COMPLETE_DATE_REGEX = + "(\\d{1,4}-\\d{1,2}-\\d{1,2}|\\d{1,2}-\\d{1,2}-\\d{1,4})"; /** * 'My Contacts' System group where clause */ private static final String MY_CONTACTS_GROUP_WHERE_CLAUSE = Groups.SYSTEM_ID + "=\"Contacts\""; /** * Selection where clause for a NULL Account */ private static final String NULL_ACCOUNT_WHERE_CLAUSE = RawContacts.ACCOUNT_NAME + " IS NULL AND " + RawContacts.ACCOUNT_TYPE + " IS NULL"; /** * Selection where clause for an Organization detail. */ private static final String ORGANIZATION_DETAIL_WHERE_CLAUSE = RawContacts.Data.MIMETYPE + "=\"" + Organization.CONTENT_ITEM_TYPE + "\""; /** * The list of Uri that need to be listened to for contacts changes on * native side. */ private static final Uri[] sUri = { ContactsContract.RawContacts.CONTENT_URI, ContactsContract.Data.CONTENT_URI }; /** * Holds mapping from a NAB type (MIME) to a VCard Key */ private static final HashMap<String, Integer> sFromNabContentTypeToKeyMap; /** * Holds mapping from a VCard Key to a NAB type (MIME) */ private static final SparseArray<String> sFromKeyToNabContentTypeArray; static { sFromNabContentTypeToKeyMap = new HashMap<String, Integer>(9, 1); sFromNabContentTypeToKeyMap.put(StructuredName.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NAME); sFromNabContentTypeToKeyMap.put(Nickname.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NICKNAME); sFromNabContentTypeToKeyMap.put(Phone.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_PHONE); sFromNabContentTypeToKeyMap.put(Email.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_EMAIL); sFromNabContentTypeToKeyMap.put(StructuredPostal.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ADDRESS); sFromNabContentTypeToKeyMap.put(Organization.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ORG); sFromNabContentTypeToKeyMap.put(Website.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_URL); sFromNabContentTypeToKeyMap.put(Note.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NOTE); sFromNabContentTypeToKeyMap.put(Event.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_DATE); // sFromNabContentTypeToKeyMap.put(Photo.CONTENT_ITEM_TYPE, ContactChange.KEY_PHOTO); sFromKeyToNabContentTypeArray = new SparseArray<String>(10); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NAME, StructuredName.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NICKNAME, Nickname.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_PHONE, Phone.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_EMAIL, Email.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ADDRESS, StructuredPostal.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ORG, Organization.CONTENT_ITEM_TYPE); // Special case: VCARD_TITLE maps to the same NAB type as sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_TITLE, Organization.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_URL, Website.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NOTE, Note.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_DATE, Event.CONTENT_ITEM_TYPE); // sFromKeyToNabContentTypeArray.append(ContactChange.KEY_PHOTO, Photo.CONTENT_ITEM_TYPE); } /** * The observer registered by the upper layer. */ private ContactsObserver mAbstractedObserver; /** * Content values used for writing to NAB. */ private final ContentValues mValues = new ContentValues(); /** * The content observers that listens for native contacts changes. */ private final ContentObserver[] mContentObservers = new ContentObserver[sUri.length]; /** * Array of row ID in the groups table to the "My Contacts" System Group. * The reason for this being an array is because there may be multiple * "My Contacts" groups (Platform Bug!?). */ private long[] mMyContactsGroupRowIds = null; /** * Arguably another example where Organization and Title force us into extra * effort. We use this value to pass the correct detail ID when an 'add * detail' is done for one the two although the other is already present. * Make sure to reset this value for every UpdateContact operation */ private long mExistingOrganizationId = ContactChange.INVALID_ID; /** * Flag to check if we have already read a Birthday detail */ private boolean mHaveReadBirthday = false; /** * Yield value for our ContentProviderOperations. */ private boolean mYield = true; /** * Batch used for Contact Writing operations. */ private BatchOperation mBatch = new BatchOperation(); /** * Inner class for applying batches. TODO: Move to own class if batches * become supported in other areas */ private class BatchOperation { // List for storing the batch mOperations ArrayList<ContentProviderOperation> mOperations; /** * Default constructor */ public BatchOperation() { mOperations = new ArrayList<ContentProviderOperation>(); } /** * Current size of the batch * * @return Size of the batch */ public int size() { return mOperations.size(); } /** * Adds a new operation to the batch * * @param cpo The */ public void add(ContentProviderOperation cpo) { mOperations.add(cpo); } /** * Clears all operations in the batch Effectively resets the batch. */ public void clear() { mOperations.clear(); } public ContentProviderResult[] execute() { ContentProviderResult[] resultArray = null; if (mOperations.size() > 0) { // Apply the mOperations to the content provider try { resultArray = mCr.applyBatch(ContactsContract.AUTHORITY, mOperations); } catch (final OperationApplicationException e1) { LogUtils.logE("storing contact data failed", e1); } catch (final RemoteException e2) { LogUtils.logE("storing contact data failed", e2); } mOperations.clear(); } return resultArray; } } /** * Convenience interface to map the generic DATA column names to the People * profile detail column names. */ private interface PeopleProfileColumns { /** * 360 People profile MIME Type */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/com.vodafone360.people.profile"; /** * 360 People Contact's profile ID (Corresponds to Contact's Internal * Contact ID) */ public static final String DATA_PID = Data.DATA1; /** * 360 People Contact profile Summary */ public static final String DATA_SUMMARY = Data.DATA2; /** * 360 People Contact profile detail */ public static final String DATA_DETAIL = Data.DATA3; } /** * This class holds a native content observer that will be notified in case * of changes on the registered URI. */ private class NativeContentObserver extends ContentObserver { public NativeContentObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { LogUtils.logI("NativeContactsApi2.NativeContentObserver.onChange(" + selfChange + ")"); mAbstractedObserver.onChange(); } } /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { LogUtils.logI("NativeContactsApi2.registerObserver()"); if (mAbstractedObserver != null) { throw new RuntimeException( "Only one observer at a time supported... Please unregister first."); } mAbstractedObserver = observer; final ContentResolver cr = mContext.getContentResolver(); for (int i = 0; i < mContentObservers.length; i++) { mContentObservers[i] = new NativeContentObserver(); cr.registerContentObserver(sUri[i], true, mContentObservers[i]); } } /** * @see NativeContactsApi#unregisterObserver(ContactsObserver) */ @Override public void unregisterObserver() { LogUtils.logI("NativeContactsApi2.unregisterObserver()"); if (mCr != null) { mAbstractedObserver = null; for (int i = 0; i < mContentObservers.length; i++) { if (mContentObservers[i] != null) { mCr.unregisterContentObserver(mContentObservers[i]); mContentObservers[i] = null; } } } } /** * @see NativeContactsApi#initialize() */ @Override protected void initialize() { // perform here any one time initialization sPhoneAccount = getVendorSpecificAccount(); } /** * @see NativeContactsApi#getAccounts() */ @Override public Account[] getAccounts() { AccountManager accountManager = AccountManager.get(mContext); final android.accounts.Account[] accounts2xApi = accountManager.getAccounts(); Account[] accounts = null; if (accounts2xApi.length > 0) { accounts = new Account[accounts2xApi.length]; for (int i = 0; i < accounts2xApi.length; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } } return accounts; } /** * Reads vendor specific accounts from settings and through accountmanager. * Some phones with custom ui like sense have additional account that we * have to take care of. This method tryes to read them * * @return Account object if vendor specific account is found, null * otherwise */ public Account getVendorSpecificAccount() { // first read the settings String[] PROJECTION = { Settings.ACCOUNT_NAME, Settings.ACCOUNT_TYPE, Settings.UNGROUPED_VISIBLE }; // Get a cursor with all people Cursor cursor = mCr.query(Settings.CONTENT_URI, PROJECTION, null, null, null); // Got no cursor? Return with null! if (null == cursor) { return null; } try { String[] values = new String[cursor.getCount()]; for (int i = 0; i < values.length; i++) { cursor.moveToNext(); if (isVendorSpecificAccount(cursor.getString(1))) { return new Account(cursor.getString(0), cursor.getString(1)); } } } catch (Exception exc) { return null; } CursorUtils.closeCursor(cursor); // nothing found in the settings? try accountmanager Account[] accounts = getAccounts(); if (accounts == null) { return null; } for (Account account : accounts) { if (isVendorSpecificAccount(account.getType())) { return account; } } return null; } /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override public Account[] getAccountsByType(int type) { switch (type) { // people and google type lead to the same block the difference is // then handled inside in two if statements. // Otherwise we would have a lot of redundant code, case PEOPLE_ACCOUNT_TYPE: case GOOGLE_ACCOUNT_TYPE: { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts2xApi = null; // For people account set the people account type string... if (PEOPLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); } // .. and for google the same only with google string. if (GOOGLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(GOOGLE_ACCOUNT_TYPE_STRING); } final int numAccounts = accounts2xApi.length; if (numAccounts > 0) { Account[] accounts = new Account[numAccounts]; for (int i = 0; i < numAccounts; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } return accounts; } else { return null; } } case PHONE_ACCOUNT_TYPE: { if (sPhoneAccount == null) { return null; } return new Account[] { sPhoneAccount }; } default: return null; } } /** * @see NativeContactsApi#addPeopleAccount(String) */ @Override public boolean addPeopleAccount(String username) { boolean isAdded = false; try { android.accounts.Account account = new android.accounts.Account(username, PEOPLE_ACCOUNT_TYPE_STRING); AccountManager accountMan = AccountManager.get(mContext); isAdded = accountMan.addAccountExplicitly(account, null, null); if (isAdded) { if (VersionUtils.isHtcSenseDevice(mContext)) { createSettingsEntryForAccount(username); requestSyncAdapterInitialization(account); } // Need to do our Sync Adapter initialization logic here SyncAdapter.initialize(account, ContactsContract.AUTHORITY); } } catch (Exception ex) { LogUtils.logE("People Account creation failed because of exception:\n", ex); } - if (isAdded) { - // Updating MyContacts Group IDs here for now because it needs to be - // done one time just before first time sync. - // In the future, this code may change if we modify - // the way we retrieve contact IDs. - fetchMyContactsGroupRowIds(); - } + +// Commented out 'My Contacts' Group Row IDs call as it is not currently used +// if (isAdded) { +// // Updating MyContacts Group IDs here for now because it needs to be +// // done one time just before first time sync. +// // In the future, this code may change if we modify +// // the way we retrieve contact IDs. +// fetchMyContactsGroupRowIds(); +// } return isAdded; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { return getPeopleAccount() != null; } /** * @see NativeContactsApi#removePeopleAccount() */ @Override public void removePeopleAccount() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); if (accounts != null && accounts.length > 0) { accountMan.removeAccount(accounts[0], null, null); } } /** * @see NativeContactsApi#getContactIds(Account) */ @Override public long[] getContactIds(Account account) { // Need to construct a where clause if (account != null) { final StringBuffer clauseBuffer = new StringBuffer(); clauseBuffer.append(RawContacts.ACCOUNT_NAME); clauseBuffer.append("=\""); clauseBuffer.append(account.getName()); clauseBuffer.append("\" AND "); clauseBuffer.append(RawContacts.ACCOUNT_TYPE); clauseBuffer.append("=\""); clauseBuffer.append(account.getType()); clauseBuffer.append('\"'); return getContactIds(clauseBuffer.toString()); } else { return getContactIds(NULL_ACCOUNT_WHERE_CLAUSE); } } /** * @see NativeContactsApi#getContact(long) */ @Override public ContactChange[] getContact(long nabContactId) { // Reset the boolean flags mHaveReadOrganization = false; mHaveReadBirthday = false; final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, nabContactId); final Uri dataUri = Uri.withAppendedPath(rawContactUri, RawContacts.Data.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(dataUri, null, null, null, null); try { if (cursor != null && cursor.getCount() > 0) { final List<ContactChange> ccList = new ArrayList<ContactChange>(); while (cursor.moveToNext()) { readDetail(cursor, ccList, nabContactId); } return ccList.toArray(new ContactChange[ccList.size()]); } } finally { CursorUtils.closeCursor(cursor); } return null; } /** * @see NativeContactsApi#addContact(Account, ContactChange[]) */ @Override public ContactChange[] addContact(Account account, ContactChange[] ccList) { // Make sure to reset all the member variables we need mYield = true; mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mValues.clear(); mBatch.clear(); mValues.put(RawContacts.ACCOUNT_TYPE, account.getType()); mValues.put(RawContacts.ACCOUNT_NAME, account.getName()); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI)).withYieldAllowed(mYield) .withValues(mValues); mBatch.add(builder.build()); // according to the calling method ccList here has at least 1 element, ccList[0] is not null final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc != null) { final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } putDetail(cc); addValuesToBatch(ContactChange.INVALID_ID); } } // Special case for the organization/title if it was flagged in the // putDetail call putOrganization(ccList); addValuesToBatch(ContactChange.INVALID_ID); // Add 360 profile detail addProfileAction(ccList[0].getInternalContactId()); // Execute the batch and Generate ID changes from it return executeNewContactBatch(ccList); } /** * @see NativeContactsApi#updateContact(ContactChange[]) */ @Override public ContactChange[] updateContact(ContactChange[] ccList) { if (ccList == null || ccList.length == 0) { LogUtils.logW("NativeContactsApi2.updateContact() nothing to update - empty ccList!"); return null; } // Make sure to reset all the member variables we need mYield = true; mBatch.clear(); mValues.clear(); mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mExistingOrganizationId = ContactChange.INVALID_ID; final long nabContactId = ccList[0].getNabContactId(); if (nabContactId == ContactChange.INVALID_ID) { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update request because of invalid NAB Contact ID. Internal Contact ID is " + ccList[0].getInternalContactId()); return null; } final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } switch (cc.getType()) { case ContactChange.TYPE_ADD_DETAIL: putDetail(cc); addValuesToBatch(nabContactId); // not a new contact break; case ContactChange.TYPE_UPDATE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { putDetail(cc); addUpdateValuesToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update to detail for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; case ContactChange.TYPE_DELETE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { addDeleteDetailToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring detail deletion for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; default: break; } } updateOrganization(ccList, nabContactId); // Execute the batch and Generate ID changes from it return executeUpdateContactBatch(ccList); } /** * @see NativeContactsApi#removeContact(long) */ @Override public void removeContact(long nabContactId) { mCr.delete(addCallerIsSyncAdapterParameter(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId)), null, null); } /** * @see NativeContactsApi#getMasterSyncAutomatically */ @Override public boolean getMasterSyncAutomatically() { return ContentResolver.getMasterSyncAutomatically(); } /** * @see NativeContactsApi#setSyncable(boolean) */ @Override public void setSyncable(boolean syncable) { android.accounts.Account account = getPeopleAccount(); if(account != null) { ContentResolver. setIsSyncable(account, ContactsContract.AUTHORITY, syncable ? 1 : 0); } } /** * @see NativeContactsApi#setSyncAutomatically(boolean) */ @Override public void setSyncAutomatically(boolean syncAutomatically) { android.accounts.Account account = getPeopleAccount(); if(account != null) { ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, syncAutomatically); if(syncAutomatically) { // Kick start sync ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); } else { // Cancel ongoing just in case ContentResolver.cancelSync(account, ContactsContract.AUTHORITY); } } } /** * @see NativeContactsApi#isKeySupported(int) */ @Override public boolean isKeySupported(int key) { // Only supported if in the SparseArray return sFromKeyToNabContentTypeArray.indexOfKey(key) >= 0; } /** * Inner (private) method for getting contact ids. Allows a cleaner * separation the public API method. * * @param selection The where clause for the operation * @return An array containing the Contact IDs that have been found */ private long[] getContactIds(final String selection) { // Store ids in a temporary array because of possible null values long[] tempIds = null; int idCount = 0; final Cursor cursor = mCr.query(RawContacts.CONTENT_URI, CONTACTID_PROJECTION, selection, null, null); if (cursor == null) { return null; } try { final int cursorCount = cursor.getCount(); if (cursorCount > 0) { tempIds = new long[cursorCount]; while (cursor.moveToNext()) { final long id = cursor.getLong(CONTACTID_PROJECTION_RAW_ID); final String accountType = cursor.getString(CONTACTID_PROJECTION_ACCOUNT_TYPE); // TODO: Remove hardcoding (if statement) if (TextUtils.isEmpty(accountType) || accountType.equals(NativeContactsApi.PEOPLE_ACCOUNT_TYPE_STRING) || isVendorSpecificAccount(accountType)) { //PAND-2125 || isContactInMyContactsGroup(id)) { tempIds[idCount] = id; idCount++; } } } } finally { CursorUtils.closeCursor(cursor); } if (idCount > 0) { // Here we copy the array to strip any eventual nulls at the end of // the tempIds array final long[] ids = new long[idCount]; System.arraycopy(tempIds, 0, ids, 0, idCount); return ids; } return null; } /** * Fetches the IDs corresponding to the "My Contacts" System Group The * reason why we return an array is because there may be multiple * "My Contacts" groups. * * @return Array containing all IDs of the "My Contacts" group or null if * none exist */ private void fetchMyContactsGroupRowIds() { final Cursor cursor = mCr.query(Groups.CONTENT_URI, GROUPID_PROJECTION, MY_CONTACTS_GROUP_WHERE_CLAUSE, null, null); if (cursor == null) { return; } try { final int count = cursor.getCount(); if (count > 0) { mMyContactsGroupRowIds = new long[count]; for (int i = 0; i < count; i++) { cursor.moveToNext(); mMyContactsGroupRowIds[i] = cursor.getLong(0); } } } finally { CursorUtils.closeCursor(cursor); } } /** * Checks if a Contact is in the "My Contacts" System Group * * @param nabContactId ID of the Contact to check * @return true if the Contact is in the Group, false if not */ /** * PAND-2125 * The decision has been made to stop the import of Google contacts on 2.x devices. * From now on, we will only import native addressbook contacts. */ /* private boolean isContactInMyContactsGroup(long nabContactId) { boolean belongs = false; if (mMyContactsGroupRowIds != null) { final Uri dataUri = Uri.withAppendedPath(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId), RawContacts.Data.CONTENT_DIRECTORY); // build query containing row ID values final StringBuilder sb = new StringBuilder(); sb.append(MY_CONTACTS_MULTI_GROUP_MEMBERSHIP); final int rowIdCount = mMyContactsGroupRowIds.length; for (int i = 0; i < rowIdCount; i++) { sb.append(mMyContactsGroupRowIds[i]); if (i < rowIdCount - 1) { sb.append(','); } } sb.append(')'); final Cursor cursor = mCr.query(dataUri, null, sb.toString(), null, null); try { belongs = cursor != null && cursor.getCount() > 0; } finally { CursorUtils.closeCursor(cursor); } } return belongs; } */ /** * Reads a Contact Detail from a Cursor into the supplied Contact Change * List. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to read Detail into * @param nabContactId NAB ID of the Contact */ private void readDetail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String mimetype = CursorUtils.getString(cursor, Data.MIMETYPE); final Integer key = sFromNabContentTypeToKeyMap.get(mimetype); if (key != null) { switch (key.intValue()) { case ContactChange.KEY_VCARD_NAME: readName(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_NICKNAME: readNickname(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_PHONE: readPhone(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_EMAIL: readEmail(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ADDRESS: readAddress(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ORG: // Only one Organization can be read (CAB limitation!) if (!mHaveReadOrganization) { readOrganization(cursor, ccList, nabContactId); } break; case ContactChange.KEY_VCARD_URL: readWebsite(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_DATE: if (!mHaveReadBirthday) { readBirthday(cursor, ccList, nabContactId); } break; default: // The default case is also a valid key final String value = CursorUtils.getString(cursor, Data.DATA1); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Data._ID); final ContactChange cc = new ContactChange(key, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } break; } } } /** * Reads an name detail as a {@link ContactChange} from the provided cursor. * For this type of detail we need to use a VCARD (semicolon separated) * value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readName(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using display name only to check if there is a valid name to read final String displayName = CursorUtils.getString(cursor, StructuredName.DISPLAY_NAME); if (!TextUtils.isEmpty(displayName)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredName._ID); // VCard Helper data type (CAB) final Name name = new Name(); // NAB: Given name -> CAB: First name name.firstname = CursorUtils.getString(cursor, StructuredName.GIVEN_NAME); // NAB: Family name -> CAB: Surname name.surname = CursorUtils.getString(cursor, StructuredName.FAMILY_NAME); // NAB: Prefix -> CAB: Title name.title = CursorUtils.getString(cursor, StructuredName.PREFIX); // NAB: Middle name -> CAB: Middle name name.midname = CursorUtils.getString(cursor, StructuredName.MIDDLE_NAME); // NAB: Suffix -> CAB: Suffixes name.suffixes = CursorUtils.getString(cursor, StructuredName.SUFFIX); // NOTE: Ignoring Phonetics (DATA7, DATA8 and DATA9)! // TODO: Need to get middle name and concatenate into value final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NAME, VCardHelper .makeName(name), ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an nickname detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readNickname(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Nickname.NAME); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Nickname._ID); /* * TODO: Decide what to do with nickname: Can only have one in VF360 * but NAB Allows more than one! */ final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NICKNAME, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an phone detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readPhone(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Phone.NUMBER); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Phone._ID); final int type = CursorUtils.getInt(cursor, Phone.TYPE); int flags = mapFromNabPhoneType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Phone.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // assuming raw value is good enough for us final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_PHONE, value, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an email detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readEmail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Email.DATA); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Email._ID); final int type = CursorUtils.getInt(cursor, Email.TYPE); int flags = mapFromNabEmailType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Email.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // assuming raw value is good enough for us final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_EMAIL, value, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an address detail as a {@link ContactChange} from the provided * cursor. For this type of detail we need to use a VCARD (semicolon * separated) value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readAddress(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using formatted address only to check if there is a valid address to // read final String formattedAddress = CursorUtils.getString(cursor, StructuredPostal.FORMATTED_ADDRESS); if (!TextUtils.isEmpty(formattedAddress)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredPostal._ID); final int type = CursorUtils.getInt(cursor, StructuredPostal.TYPE); int flags = mapFromNabAddressType(type); final boolean isPrimary = CursorUtils.getInt(cursor, StructuredPostal.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // VCard Helper data type (CAB) final PostalAddress address = new PostalAddress(); // NAB: Street -> CAB: AddressLine1 address.addressLine1 = CursorUtils.getString(cursor, StructuredPostal.STREET); // NAB: PO Box -> CAB: postOfficeBox address.postOfficeBox = CursorUtils.getString(cursor, StructuredPostal.POBOX); // NAB: Neighborhood -> CAB: AddressLine2 address.addressLine2 = CursorUtils.getString(cursor, StructuredPostal.NEIGHBORHOOD); // NAB: City -> CAB: City address.city = CursorUtils.getString(cursor, StructuredPostal.CITY); // NAB: Region -> CAB: County address.county = CursorUtils.getString(cursor, StructuredPostal.REGION); // NAB: Post code -> CAB: Post code address.postCode = CursorUtils.getString(cursor, StructuredPostal.POSTCODE); // NAB: Country -> CAB: Country address.country = CursorUtils.getString(cursor, StructuredPostal.COUNTRY); final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_ADDRESS, VCardHelper .makePostalAddress(address), flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an organization detail as a {@link ContactChange} from the provided * cursor. For this type of detail we need to use a VCARD (semicolon * separated) value. In reality two different changes may be read if a title * is also present. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readOrganization(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final int type = CursorUtils.getInt(cursor, Organization.TYPE); int flags = mapFromNabOrganizationType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Organization.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } final long nabDetailId = CursorUtils.getLong(cursor, Organization._ID); if (!mHaveReadOrganization) { // VCard Helper data type (CAB) final Organisation organization = new Organisation(); // Company organization.name = CursorUtils.getString(cursor, Organization.COMPANY); // Department final String department = CursorUtils.getString(cursor, Organization.DEPARTMENT); if (!TextUtils.isEmpty(department)) { organization.unitNames.add(department); } if ((organization.unitNames != null && organization.unitNames.size() > 0) || !TextUtils.isEmpty(organization.name)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_ORG, VCardHelper .makeOrg(organization), flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } // Title final String title = CursorUtils.getString(cursor, Organization.TITLE); if (!TextUtils.isEmpty(title)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_TITLE, title, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } } } /** * Reads an Website detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readWebsite(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String url = CursorUtils.getString(cursor, Website.URL); if (!TextUtils.isEmpty(url)) { final long nabDetailId = CursorUtils.getLong(cursor, Website._ID); final int type = CursorUtils.getInt(cursor, Website.TYPE); int flags = mapFromNabWebsiteType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Website.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_URL, url, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an Birthday detail as a {@link ContactChange} from the provided * cursor. Note that since the Android Type is the Generic "Event", it may * be the case that nothing is read if this is not actually a Birthday * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ - public void readBirthday(Cursor cursor, List<ContactChange> ccList, long nabContactId) { + private void readBirthday(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final int type = CursorUtils.getInt(cursor, Event.TYPE); - if (type == Event.TYPE_BIRTHDAY) { - final String date = CursorUtils.getString(cursor, Event.START_DATE); - // Ignoring birthdays without year, day and month! - // FIXME: Remove this check when/if the backend becomes able to - // handle incomplete birthdays - if (date != null && date.matches(COMPLETE_DATE_REGEX)) { - final long nabDetailId = CursorUtils.getLong(cursor, Event._ID); - final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_DATE, date, - ContactChange.FLAG_BIRTHDAY); - cc.setNabContactId(nabContactId); - cc.setNabDetailId(nabDetailId); - ccList.add(cc); - mHaveReadBirthday = true; - } + if (type != Event.TYPE_BIRTHDAY) { + // Not a Birthday, return + return; } + + final String date = CursorUtils.getString(cursor, Event.START_DATE); + + if(TextUtils.isEmpty(date)) { + // Empty date, do nothing + return; + } + + // Ignoring birthdays without year, day and month! + // FIXME: Remove this check when/if the backend becomes able to + // handle incomplete birthdays + Matcher matcher = Pattern.compile(NativeContactsApi2.COMPLETE_DATE_REGEX).matcher(date); + + if(!matcher.find()) { + // No matching date, log and return + LogUtils.logD("NativeContactsApi2.readBirthday() - Unsupported '"+ + date+"' Date skipped for NAB Contact ID:"+nabContactId); + return; + } + + final long nabDetailId = CursorUtils.getLong(cursor, Event._ID); + final ContactChange cc = new ContactChange( + ContactChange.KEY_VCARD_DATE, + matcher.group(), + ContactChange.FLAG_BIRTHDAY); + cc.setNabContactId(nabContactId); + cc.setNabDetailId(nabDetailId); + ccList.add(cc); + mHaveReadBirthday = true; } /** * Adds current values to the batch. * * @param nabContactId The existing NAB Contact ID if it is an update or an * invalid id if a new contact */ private void addValuesToBatch(long nabContactId) { // Add to batch if (mValues.size() > 0) { final boolean isNewContact = nabContactId == ContactChange.INVALID_ID; if (!isNewContact) { // Updating a Contact, need to add the ID to the Values mValues.put(Data.RAW_CONTACT_ID, nabContactId); } ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( addCallerIsSyncAdapterParameter(Data.CONTENT_URI)).withYieldAllowed(mYield) .withValues(mValues); if (isNewContact) { // New Contact needs Back Reference builder.withValueBackReference(Data.RAW_CONTACT_ID, 0); } mYield = false; mBatch.add(builder.build()); } } /** * Adds current update values to the batch. * * @param nabDetailId The NAB ID of the detail to update */ private void addUpdateValuesToBatch(long nabDetailId) { if (mValues.size() > 0) { final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, nabDetailId); ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate( addCallerIsSyncAdapterParameter(uri)).withYieldAllowed(mYield).withValues( mValues); mYield = false; mBatch.add(builder.build()); } } /** * Adds a delete detail operation to the batch. * * @param nabDetailId The NAB Id of the detail to delete */ private void addDeleteDetailToBatch(long nabDetailId) { final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, nabDetailId); ContentProviderOperation.Builder builder = ContentProviderOperation.newDelete( addCallerIsSyncAdapterParameter(uri)).withYieldAllowed(mYield); mYield = false; mBatch.add(builder.build()); } /** * Adds the profile action detail to a (assumed) pending new Contact Batch * operation. * * @param internalContactId The Internal Contact ID used as the Profile ID */ private void addProfileAction(long internalContactId) { mValues.clear(); mValues.put(Data.MIMETYPE, PeopleProfileColumns.CONTENT_ITEM_TYPE); mValues.put(PeopleProfileColumns.DATA_PID, internalContactId); mValues.put(PeopleProfileColumns.DATA_SUMMARY, mContext .getString(R.string.android_contact_profile_summary)); mValues.put(PeopleProfileColumns.DATA_DETAIL, mContext .getString(R.string.android_contact_profile_detail)); addValuesToBatch(ContactChange.INVALID_ID); } // PRESENCE TEXT NOT USED // /** // * Returns the Data id for a sample SyncAdapter contact's profile row, or // 0 // * if the sample SyncAdapter user isn't found. // * // * @param resolver a content resolver // * @param userId the sample SyncAdapter user ID to lookup // * @return the profile Data row id, or 0 if not found // */ // private long lookupProfile(long internalContactId) { // long profileId = -1; // final Cursor c = // mCr.query(Data.CONTENT_URI, ProfileQuery.PROJECTION, // ProfileQuery.SELECTION, new String[] {String.valueOf(internalContactId)}, // null); // try { // if (c != null && c.moveToFirst()) { // profileId = c.getLong(ProfileQuery.COLUMN_ID); // } // } finally { // if (c != null) { // c.close(); // } // } // return profileId; // } // // /** // * Constants for a query to find a contact given a sample SyncAdapter user // * ID. // */ // private interface ProfileQuery { // public final static String[] PROJECTION = new String[] {Data._ID}; // // public final static int COLUMN_ID = 0; // // public static final String SELECTION = // Data.MIMETYPE + "='" + PeopleProfileColumns.CONTENT_ITEM_TYPE // + "' AND " + PeopleProfileColumns.DATA_PID + "=?"; // } // // private void addPresence(long internalContactId, String presenceText) { // long profileId = lookupProfile(internalContactId); // if(profileId > -1) { // mValues.clear(); // mValues.put(StatusUpdates.DATA_ID, profileId); // mValues.put(StatusUpdates.STATUS, presenceText); // mValues.put(StatusUpdates.PROTOCOL, Im.PROTOCOL_CUSTOM); // mValues.put(StatusUpdates.IM_ACCOUNT, LoginPreferences.getUsername()); // mValues.put(StatusUpdates.STATUS_ICON, R.drawable.pt_launcher_icon); // mValues.put(StatusUpdates.STATUS_RES_PACKAGE, mContext.getPackageName()); // // ContentProviderOperation.Builder builder = // ContentProviderOperation.newInsert( // addCallerIsSyncAdapterParameter(StatusUpdates.CONTENT_URI)). // withYieldAllowed(mYield).withValues(mValues); // BatchOperation batch = new BatchOperation(); // batch.add(builder.build()); // batch.execute(); // } // } /** * Put values for a detail from a {@link ContactChange} into pending values. * * @param cc {@link ContactChange} to read values from */ private void putDetail(ContactChange cc) { mValues.clear(); switch (cc.getKey()) { case ContactChange.KEY_VCARD_PHONE: putPhone(cc); break; case ContactChange.KEY_VCARD_EMAIL: putEmail(cc); break; case ContactChange.KEY_VCARD_NAME: putName(cc); break; case ContactChange.KEY_VCARD_NICKNAME: putNickname(cc); break; case ContactChange.KEY_VCARD_ADDRESS: putAddress(cc); break; case ContactChange.KEY_VCARD_URL: putWebsite(cc); break; case ContactChange.KEY_VCARD_NOTE: putNote(cc); break; case ContactChange.KEY_VCARD_DATE: // Date only means Birthday currently putBirthday(cc); break; default: break; } } /** * Put Name detail into the values * * @param cc {@link ContactChange} to read values from */ private void putName(ContactChange cc) { final Name name = VCardHelper.getName(cc.getValue()); if (name == null) { // Nothing to do return; } mValues.put(StructuredName.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); mValues.put(StructuredName.GIVEN_NAME, name.firstname); mValues.put(StructuredName.FAMILY_NAME, name.surname); mValues.put(StructuredName.PREFIX, name.title); mValues.put(StructuredName.MIDDLE_NAME, name.midname); mValues.put(StructuredName.SUFFIX, name.suffixes); } /** * Put Nickname detail into the values * * @param cc {@link ContactChange} to read values from */ private void putNickname(ContactChange cc) { mValues.put(Nickname.NAME, cc.getValue()); mValues.put(Nickname.MIMETYPE, Nickname.CONTENT_ITEM_TYPE); } /** * Put Phone detail into the values * * @param cc {@link ContactChange} to read values from */ private void putPhone(ContactChange cc) { mValues.put(Phone.NUMBER, cc.getValue()); final int flags = cc.getFlags(); mValues.put(Phone.TYPE, mapToNabPhoneType(flags)); mValues.put(Phone.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(Phone.MIMETYPE, Phone.CONTENT_ITEM_TYPE); } /** * Put Email detail into the values * * @param cc {@link ContactChange} to read values from */ private void putEmail(ContactChange cc) { mValues.put(Email.DATA, cc.getValue()); final int flags = cc.getFlags(); mValues.put(Email.TYPE, mapToNabEmailType(flags)); mValues.put(Email.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(Email.MIMETYPE, Email.CONTENT_ITEM_TYPE); } /** * Put Address detail into the values * * @param cc {@link ContactChange} to read values from */ private void putAddress(ContactChange cc) { final PostalAddress address = VCardHelper.getPostalAddress(cc.getValue()); if (address == null) { // Nothing to do return; } mValues.put(StructuredPostal.STREET, address.addressLine1); mValues.put(StructuredPostal.POBOX, address.postOfficeBox); mValues.put(StructuredPostal.NEIGHBORHOOD, address.addressLine2); mValues.put(StructuredPostal.CITY, address.city); mValues.put(StructuredPostal.REGION, address.county); mValues.put(StructuredPostal.POSTCODE, address.postCode); mValues.put(StructuredPostal.COUNTRY, address.country); final int flags = cc.getFlags(); mValues.put(StructuredPostal.TYPE, mapToNabAddressType(flags)); mValues.put(StructuredPostal.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(StructuredPostal.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE); } /** * Put Website detail into the values * * @param cc {@link ContactChange} to read values from */ private void putWebsite(ContactChange cc) { mValues.put(Website.URL, cc.getValue()); final int flags = cc.getFlags(); mValues.put(Website.TYPE, mapToNabWebsiteType(flags)); mValues.put(Website.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(Website.MIMETYPE, Website.CONTENT_ITEM_TYPE); } /** * Put Note detail into the values * * @param cc {@link ContactChange} to read values from */ private void putNote(ContactChange cc) { mValues.put(Note.NOTE, cc.getValue()); mValues.put(Note.MIMETYPE, Note.CONTENT_ITEM_TYPE); } /** * Put Birthday detail into the values * * @param cc {@link ContactChange} to read values from */ private void putBirthday(ContactChange cc) { if ((cc.getFlags() & ContactChange.FLAG_BIRTHDAY) == ContactChange.FLAG_BIRTHDAY) { mValues.put(Event.START_DATE, cc.getValue()); mValues.put(Event.TYPE, Event.TYPE_BIRTHDAY); mValues.put(Event.MIMETYPE, Event.CONTENT_ITEM_TYPE); } } // PHOTO NOT USED // /** // * Do a GET request and retrieve up to maxBytes bytes // * // * @param url // * @param maxBytes // * @return // * @throws IOException // */ // public static byte[] doGetAndReturnBytes(URL url, int maxBytes) throws // IOException { // HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // conn.setRequestMethod("GET"); // InputStream istr = null; // try { // int rc = conn.getResponseCode(); // if (rc != 200) { // throw new IOException("code " + rc + " '" + conn.getResponseMessage() + // "'"); // } // istr = new BufferedInputStream(conn.getInputStream(), 512); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // copy(istr, baos, maxBytes); // return baos.toByteArray(); // } finally { // if (istr != null) { // istr.close(); // } // } // } // // /** // * Copy maxBytes from an input stream to an output stream. // * @param in // * @param out // * @param maxBytes // * @return // * @throws IOException // */ // private static int copy(InputStream in, OutputStream out, int maxBytes) // throws IOException { // byte[] buf = new byte[512]; // int bytesRead = 1; // int totalBytes = 0; // while (bytesRead > 0) { // bytesRead = in.read(buf, 0, Math.min(512, maxBytes - totalBytes)); // if (bytesRead > 0) { // out.write(buf, 0, bytesRead); // totalBytes += bytesRead; // } // } // return totalBytes; // } // // /** // * Put Photo detail into the values // * @param cc {@link ContactChange} to read values from // */ // private void putPhoto(ContactChange cc) { // try { // // File file = new File(cc.getValue()); // // InputStream is = new FileInputStream(file); // // byte[] bytes = new byte[(int) file.length()]; // // is.read(bytes); // // is.close(); // final URL url = new URL(cc.getValue()); // byte[] bytes = doGetAndReturnBytes(url, 1024 * 100); // mValues.put(Photo.PHOTO, bytes); // mValues.put(Photo.MIMETYPE, Photo.CONTENT_ITEM_TYPE); // } catch(Exception ex) { // LogUtils.logE("Unable to put Photo detail because of exception:"+ex); // } // } /** * Put Organization detail into the values * * @param cc {@link ContactChange} to read values from */ private void putOrganization(ContactChange[] ccList) { mValues.clear(); int flags = ContactChange.FLAG_NONE; if (mMarkedOrganizationIndex > -1) { final ContactChange cc = ccList[mMarkedOrganizationIndex]; flags |= cc.getFlags(); final Organisation organization = VCardHelper.getOrg(cc.getValue()); if (organization != null) { mValues.put(Organization.COMPANY, organization.name); if (organization.unitNames.size() > 0) { // Only considering one unit name (department) as that's all // we support mValues.put(Organization.DEPARTMENT, organization.unitNames.get(0)); } else { mValues.putNull(Organization.DEPARTMENT); } } } if (mMarkedTitleIndex > -1) { final ContactChange cc = ccList[mMarkedTitleIndex]; flags |= cc.getFlags(); // No need to check for empty values as there is only one mValues.put(Organization.TITLE, cc.getValue()); } if (mValues.size() > 0) { mValues.put(Organization.LABEL, (String)null); mValues.put(Organization.TYPE, mapToNabOrganizationType(flags)); mValues.put(Organization.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(Organization.MIMETYPE, Organization.CONTENT_ITEM_TYPE); } } /** * Updates the Organization detail in the context of a Contact Update * operation. The end of result of this is that the Organization may be * inserted, updated or deleted depending on the update data. For example, * if the title is deleted but there is also a company name then the * Organization is just updated. However, if there was no company name then * the detail should be deleted altogether. * * @param ccList {@link ContactChange} list where Organization and Title may * be found * @param nabContactId The NAB ID of the Contact */ private void updateOrganization(ContactChange[] ccList, long nabContactId) { if (mMarkedOrganizationIndex < 0 && mMarkedTitleIndex < 0) { // no organization or title to update - do nothing return; } // First we check if there is an existing Organization detail in NAB final Uri uri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI, nabContactId), RawContacts.Data.CONTENT_DIRECTORY); Cursor cursor = mCr.query(uri, null, ORGANIZATION_DETAIL_WHERE_CLAUSE, null, RawContacts.Data._ID); String company = null; String department = null; String title = null; int flags = ContactChange.FLAG_NONE; try { if (cursor != null && cursor.moveToNext()) { // Found an organization detail company = CursorUtils.getString(cursor, Organization.COMPANY); department = CursorUtils.getString(cursor, Organization.DEPARTMENT); title = CursorUtils.getString(cursor, Organization.TITLE); flags = mapFromNabOrganizationType(CursorUtils.getInt(cursor, Organization.TYPE)); final boolean isPrimary = CursorUtils.getInt(cursor, Organization.IS_PRIMARY) > 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } mExistingOrganizationId = CursorUtils.getLong(cursor, Organization._ID); } } finally { CursorUtils.closeCursor(cursor); cursor = null; // make it a candidate for the GC } if (mMarkedOrganizationIndex >= 0) { // Have an Organization (Company + Department) to update final ContactChange cc = ccList[mMarkedOrganizationIndex]; if (cc.getType() != ContactChange.TYPE_DELETE_DETAIL) { final String value = cc.getValue(); if (value != null) { final Organisation organization = VCardHelper.getOrg(value); company = organization.name; if (organization.unitNames.size() > 0) { department = organization.unitNames.get(0); } } flags = cc.getFlags(); } else { // Delete case company = null; department = null; } } if (mMarkedTitleIndex >= 0) { // Have a Title to update final ContactChange cc = ccList[mMarkedTitleIndex]; title = cc.getValue(); if (cc.getType() != ContactChange.TYPE_UPDATE_DETAIL) { flags = cc.getFlags(); } } if (company != null || department != null || title != null) { /* * If any of the above are present we assume a insert or update is * needed. */ mValues.clear(); mValues.put(Organization.LABEL, (String)null); mValues.put(Organization.COMPANY, company); mValues.put(Organization.DEPARTMENT, department); mValues.put(Organization.TITLE, title); mValues.put(Organization.TYPE, mapToNabOrganizationType(flags)); mValues.put(Organization.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(Organization.MIMETYPE, Organization.CONTENT_ITEM_TYPE); if (mExistingOrganizationId != ContactChange.INVALID_ID) { // update is needed diff --git a/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeContactsApiTest.java b/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeContactsApiTest.java index b6a2883..c6fd6e9 100644 --- a/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeContactsApiTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeContactsApiTest.java @@ -1,844 +1,868 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.tests.engine.contactsync; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import com.vodafone360.people.MainApplication; import com.vodafone360.people.engine.contactsync.ContactChange; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.engine.contactsync.NativeContactsApi.Account; import com.vodafone360.people.engine.contactsync.NativeContactsApi.ContactsObserver; import com.vodafone360.people.engine.contactsync.NativeContactsApi1; import com.vodafone360.people.engine.contactsync.NativeContactsApi2; import com.vodafone360.people.tests.engine.contactsync.NativeContactsApiTestHelper.IPeopleAccountChangeObserver; import com.vodafone360.people.utils.VersionUtils; import android.app.Instrumentation; import android.database.ContentObserver; import android.os.Handler; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; public class NativeContactsApiTest extends InstrumentationTestCase { private static final String LOG_TAG = "NativeContactsApiTest"; NativeContactsApi mNabApi; NativeContactsApiTestHelper mNabApiHelper; static final int NUM_ACCOUNTS_TO_CREATE = 5; /** * 360 client account type. */ private static final int PEOPLE_ACCOUNT_TYPE = 1; /** * Google account type. */ private static final int GOOGLE_ACCOUNT_TYPE = 2; /** * Vendor specific type. */ private static final int PHONE_ACCOUNT_TYPE = 3; /** * Account type for 360 People in the Native Accounts. * MUST be a copy of type in 'res/xml/authenticator.xml' */ protected static final String PEOPLE_ACCOUNT_TYPE_STRING = "com.vodafone360.people.android.account"; /** * Google account, there can be more than one of these */ protected static final String GOOGLE_ACCOUNT_TYPE_STRING = "com.google"; private static final String PEOPLE_USERNAME = "john.doe"; private static final Account s360PeopleAccount = new Account( PEOPLE_USERNAME, PEOPLE_ACCOUNT_TYPE_STRING); private final boolean mUsing2xApi = VersionUtils.is2XPlatform(); private ContactsObserver mContactsObserver = new ContactsObserver() { @Override public void onChange() { synchronized(this) { sNabChanged = true; } } }; static boolean sNabChanged = false; - - class AccountsObserver implements IPeopleAccountChangeObserver { - - private int mCurrentNumAccounts = 0; - @Override - public void onPeopleAccountsChanged(int currentNumAccounts) { - mCurrentNumAccounts = currentNumAccounts; - Thread.currentThread().interrupt(); - } - public int getCurrentNumAccounts() { - return mCurrentNumAccounts; - } - } - class ObserverThread extends Thread { private ContactsObserver mObserver = new ContactsObserver() { @Override public void onChange() { synchronized(this) { sNabChanged = true; } } }; public synchronized ContactsObserver getObserver() { return mObserver; } } @Override protected void setUp() throws Exception { super.setUp(); NativeContactsApi.createInstance(getInstrumentation().getTargetContext()); mNabApi = NativeContactsApi.getInstance(); mNabApiHelper = NativeContactsApiTestHelper.getInstance(getInstrumentation().getContext()); //mNabApiHelper.wipeNab(mCr); } @Override protected void tearDown() throws Exception { mNabApiHelper.wipeNab(); mNabApiHelper = null; NativeContactsApi.destroyInstance(); mNabApi = null; super.tearDown(); } /** * Tests API functionality to do the following: * - Create Instance * - Get Instance * - Destroy Instance */ @SmallTest public void testInstance() { // Need to destroy instance first for this test! NativeContactsApi.destroyInstance(); NativeContactsApi nabApi = null; boolean caughtException = false; try { nabApi = NativeContactsApi.getInstance(); } catch(InvalidParameterException ex) { caughtException = true; } assertNull(nabApi); assertTrue(caughtException); NativeContactsApi.createInstance(getInstrumentation().getContext()); try { nabApi = NativeContactsApi.getInstance(); caughtException = false; } catch(InvalidParameterException ex) { } assertFalse(caughtException); assertNotNull(nabApi); NativeContactsApi.destroyInstance(); // Double Destroy NativeContactsApi.destroyInstance(); try { nabApi = NativeContactsApi.getInstance(); } catch(InvalidParameterException ex) { caughtException = true; } assertTrue(caughtException); NativeContactsApi.createInstance(getInstrumentation().getContext()); try { nabApi = NativeContactsApi.getInstance(); caughtException = false; } catch(InvalidParameterException ex) { } assertFalse(caughtException); if(mUsing2xApi) { assertTrue(nabApi instanceof NativeContactsApi2); } else { assertTrue(nabApi instanceof NativeContactsApi1); } } /** * Tests the plain Account inner class */ @SmallTest public void testAccountDataType() { // Account with null name and type Account emptyAccount = new Account(null, null); assertNotNull(emptyAccount); assertNull(emptyAccount.getName()); assertNull(emptyAccount.getType()); emptyAccount = null; // Array of accounts final int NUM_OBJS_TO_CREATE = 4; final String baseName = "AccountBaseName"; final String baseType = "AccountBaseType"; for(int i = 0; i < NUM_OBJS_TO_CREATE; i++) { Account account = new Account(baseName+i, baseType+i); assertNotNull(account); assertNotNull(account.getName()); assertNotNull(account.getType()); assertNotNull(account.toString()); assertEquals("Account: name="+baseName+i+", type="+baseType+i, account.toString()); assertEquals(baseName+i, account.getName()); assertEquals(baseType+i, account.getType()); assertFalse(account.isPeopleAccount()); } } /** * Tests the GetAccounts API functionality. * Now that this also makes indirect use of Add and Remove functionality */ @SmallTest @Suppress public void testGetAccounts() { Account[] accounts = mNabApi.getAccounts(); int initialNumAccounts = 0; if(accounts != null) { final int numAccounts = initialNumAccounts = accounts.length; for(int i = 0; i < numAccounts; i++) { assertFalse(accounts[i].isPeopleAccount()); } } if(mUsing2xApi) { for(int i = 0; i < NUM_ACCOUNTS_TO_CREATE; i++) { mNabApi.addPeopleAccount(PEOPLE_USERNAME+(i+1)); threadWait(100); accounts = mNabApi.getAccounts(); assertNotNull(accounts); assertEquals(accounts.length, initialNumAccounts + (i+1)); } for(int j = NUM_ACCOUNTS_TO_CREATE; j > 0 ; j--) { mNabApi.removePeopleAccount(); threadWait(3000); accounts = mNabApi.getAccounts(); assertEquals(j > 1, accounts != null); int numAccounts = 0; if(accounts != null) { numAccounts = accounts.length; } assertEquals(initialNumAccounts + j-1, numAccounts); } accounts = mNabApi.getAccounts(); assertEquals(accounts != null, initialNumAccounts > 0); } } /** * Tests getAccountsByType functionality */ @SmallTest @Suppress public void testGetAccountsByType() { assertNull(mNabApi.getAccountsByType(5)); assertNull(mNabApi.getAccountsByType(6)); assertNull(mNabApi.getAccountsByType(PEOPLE_ACCOUNT_TYPE)); if(mUsing2xApi) { for(int i = 0; i < NUM_ACCOUNTS_TO_CREATE; i++) { mNabApi.addPeopleAccount(PEOPLE_USERNAME+(i+1)); threadWait(100); Account[] accounts = mNabApi.getAccountsByType(PEOPLE_ACCOUNT_TYPE); assertNotNull(accounts); assertNull(mNabApi.getAccountsByType(9)); assertEquals(accounts.length, i+1); } for(int j = NUM_ACCOUNTS_TO_CREATE; j > 0 ; j--) { mNabApi.removePeopleAccount(); threadWait(3000); Account[] accounts = mNabApi.getAccountsByType(PEOPLE_ACCOUNT_TYPE); assertEquals(j > 1, accounts != null); assertNull(mNabApi.getAccountsByType(9)); int numAccounts = 0; if(accounts != null) { numAccounts = accounts.length; } assertEquals(j-1, numAccounts); } assertNull(mNabApi.getAccountsByType(PEOPLE_ACCOUNT_TYPE)); } } /** * Tests the following API functionality around manipulating Native People Accounts. * - Add a People Account * - Remove a People Account * It is not possible to test adding/removing other types of accounts explicitly */ @SmallTest @Suppress public void testAddRemoveAccount() { verifyPeopleAccountPresence(0); // Try delete here just for good measure mNabApi.removePeopleAccount(); verifyPeopleAccountPresence(0); final int numAccountsToCreate = 5; // *** ADD *** if(mUsing2xApi) { for(int i = 0 ; i < numAccountsToCreate; i++) { assertTrue(mNabApi.addPeopleAccount(PEOPLE_USERNAME+(i+1))); threadWait(100); // Double add, should fail assertFalse(mNabApi.addPeopleAccount(PEOPLE_USERNAME+(i+1))); threadWait(100); verifyPeopleAccountPresence(i+1); } } else { // Try on 1.X just in case assertFalse(mNabApi.addPeopleAccount(PEOPLE_USERNAME)); verifyPeopleAccountPresence(0); } // *** DELETE *** if(mUsing2xApi) { for(int j = numAccountsToCreate; j > 0 ; j--) { mNabApi.removePeopleAccount(); threadWait(3000); verifyPeopleAccountPresence(j-1); } } else { // Try on 1.X just in case verifyPeopleAccountPresence(0); mNabApi.removePeopleAccount(); verifyPeopleAccountPresence(0); } } /** * Tests registering and unregistering a ContactsObserver. * * Note: The code that checks if change events are sent is commented out * and needs more development time to be completed. */ @SmallTest @Suppress public void testContactsChangeObserver() { //ObserverThread observerThread = new ObserverThread(); /** * The following code could be used to make the current thread process all the * pending messages in the queue and then check that the change event has been called * on the provided ContactsObserver. * * final Looper looper = Looper.myLooper(); * final MessageQueue queue = Looper.myQueue(); * queue.addIdleHandler(new MessageQueue.IdleHandler() { * * @Override * public boolean queueIdle() { * // message has been processed and the looper is now in idle * // state * // quit the loop() otherwise we would not be able to carry on * looper.quit(); * * return false; * } * * }); * * // get the message processed by the thread event loop * Looper.loop(); * */ boolean caughtException = false; mNabApi.unregisterObserver(); try { mNabApi.registerObserver(mContactsObserver); } catch(RuntimeException ex) { caughtException = true; } assertFalse(caughtException); try { mNabApi.registerObserver(mContactsObserver); } catch(RuntimeException ex) { caughtException = true; } assertTrue(caughtException); mNabApi.unregisterObserver(); try { mNabApi.registerObserver(mContactsObserver); caughtException = false; } catch(RuntimeException ex) { } assertFalse(caughtException); // Account account = null; // if(mUsing2xApi) { // // Add Account for the case where we are in 2.X // mNabApi.addPeopleAccount(PEOPLE_USERNAME); // account = s360PeopleAccount; // threadWait(100); // } // // final int numRandomContacts = 10; // long ids[] = null; // boolean unregister = false; // for(int i = 0 ; i < numRandomContacts; i++) { // // if(unregister) { // mNabApi.unregisterObserver(observerThread.getObserver()); // } // assertFalse(sNabChanged); // final ContactChange[] newContactCcList = ContactChangeHelper.randomContact(-1, -1, -1); // mNabApi.addContact(account, newContactCcList); //threadWait(10000); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // assertTrue(unregister ^ sNabChanged); // sNabChanged = false; // ids = getContactIdsForAllAccounts(); // assertNotNull(ids); // assertEquals(1, ids.length); // mNabApi.removeContact(ids[0]); // threadWait(500); // assertTrue(unregister ^ sNabChanged); // sNabChanged = false; // unregister = !unregister; // if(!unregister) { // mNabApi.registerObserver(observerThread.getObserver()); // } // } mNabApi.unregisterObserver(); } @MediumTest @Suppress public void testAddGetRemoveContacts() { Account account = null; if(mUsing2xApi) { // Add Account for the case where we are in 2.X mNabApi.addPeopleAccount(PEOPLE_USERNAME); account = s360PeopleAccount; threadWait(100); } long[] ids = getContactIdsForAllAccounts(); assertNull(ids); final int numRandomContacts = 10; long expectedContactId = ContactChange.INVALID_ID; for(int i = 0; i < numRandomContacts; i++) { long id = i; final ContactChange[] newContactCcList = ContactChangeHelper.randomContact(id, id, -1); final ContactChange[] newIds = mNabApi.addContact(account, newContactCcList); // expected num ids is + 1 for contact id verifyNewContactIds(expectedContactId, newContactCcList, newIds); expectedContactId = newIds[0].getNabContactId() + 1; // GET CONTACTS AND COMPARE ids = getContactIdsForAllAccounts(); assertNotNull(ids); assertEquals(i+1, ids.length); final ContactChange[] fetchedContactCcList = mNabApi.getContact(ids[i]); assertNotNull(fetchedContactCcList); if(!ContactChangeHelper.areChangeListsEqual(newContactCcList, fetchedContactCcList, false)) { Log.e(LOG_TAG, "ADD FAILED: Print of contact to be added follows:"); ContactChangeHelper.printContactChangeList(newContactCcList); Log.e(LOG_TAG, "ADD FAILED: Print of contact fetched follows:"); ContactChangeHelper.printContactChangeList(fetchedContactCcList); // fail test at this point assertFalse(true); } } // DELETE final int idCount = ids.length; for(int i = 0; i < idCount; i++) { mNabApi.removeContact(ids[i]); } ids = getContactIdsForAllAccounts(); assertNull(ids); } @MediumTest @Suppress public void testUpdateContacts() { Account account = null; if(mUsing2xApi) { // Add Account for the case where we are in 2.X mNabApi.addPeopleAccount(PEOPLE_USERNAME); account = s360PeopleAccount; threadWait(100); } long[] ids = getContactIdsForAllAccounts(); assertNull(ids); final int numRandomContacts = 10; for(int i = 0; i < numRandomContacts; i++) { long id = i; final ContactChange[] newContactCcList = ContactChangeHelper.randomContact(id, id, -1); mNabApi.addContact(account, newContactCcList); //expectedContactId = newIds[0].getNabContactId() + 1; // GET CONTACT ids = getContactIdsForAllAccounts(); assertNotNull(ids); assertEquals(i+1, ids.length); final ContactChange[] fetchedContactCcList = mNabApi.getContact(ids[i]); assertNotNull(fetchedContactCcList); // UPDATE final ContactChange[] updateCcList = ContactChangeHelper.randomContactUpdate(fetchedContactCcList); assertNotNull(updateCcList); assertTrue(updateCcList.length > 0); final ContactChange[] updatedIdsCcList = mNabApi.updateContact(updateCcList); verifyUpdateContactIds(fetchedContactCcList, updateCcList, updatedIdsCcList); final ContactChange[] updatedContactCcList = ContactChangeHelper.generatedUpdatedContact(newContactCcList, updateCcList); ids = getContactIdsForAllAccounts(); assertNotNull(ids); assertEquals(i+1, ids.length); final ContactChange[] fetchedUpdatedContactCcList = mNabApi.getContact(ids[i]); assertNotNull(fetchedUpdatedContactCcList); if(!ContactChangeHelper.areUnsortedChangeListsEqual(updatedContactCcList, fetchedUpdatedContactCcList, false)) { // Print update Log.e(LOG_TAG, "UPDATE FAILED: Print of initial contact follows"); ContactChangeHelper.printContactChangeList(fetchedContactCcList); Log.e(LOG_TAG, "UPDATE FAILED: Print of failed update follows:"); ContactChangeHelper.printContactChangeList(updateCcList); // fail test at this point assertFalse(true); } } // DELETE final int idCount = ids.length; for(int i = 0; i < idCount; i++) { mNabApi.removeContact(ids[i]); } ids = getContactIdsForAllAccounts(); assertNull(ids); } @SmallTest public void testIsKeySupported() { for(int i = ContactChange.KEY_UNKNOWN; i < ContactChange.KEY_EXTERNAL; i++) { switch(i) { case ContactChange.KEY_VCARD_NAME: case ContactChange.KEY_VCARD_PHONE: case ContactChange.KEY_VCARD_EMAIL: case ContactChange.KEY_VCARD_ADDRESS: case ContactChange.KEY_VCARD_ORG: case ContactChange.KEY_VCARD_TITLE: case ContactChange.KEY_VCARD_NOTE: assertEquals(true, mNabApi.isKeySupported(i)); break; case ContactChange.KEY_VCARD_NICKNAME: case ContactChange.KEY_VCARD_DATE: case ContactChange.KEY_VCARD_URL: if(VersionUtils.is2XPlatform()) { assertEquals(true, mNabApi.isKeySupported(i)); break; } default: assertEquals(false, mNabApi.isKeySupported(i)); } } } + + @SmallTest + public void testCompleteDateRegEx() { + + final String[] validDates = { + "1900-01-02", + "20-02-03", + "03-21-04", + "04-05-22", + "5-6-23", + "23-5-6", + "6-23-5", + "06-07-1900", + "1900-01-02T00:00.000", + "1900-01-02T00:00.000+0000Z", + "00:00.000T1900-01-02", + "xxxxxxxx2000-01-01xxxxxxxxxxx" + }; + + final int maximumValidDateLength = 10; + + Pattern pattern = Pattern.compile(NativeContactsApi2.COMPLETE_DATE_REGEX); + + for(String validDate : validDates) { + Matcher matcher = pattern.matcher(validDate); + assertEquals(1, matcher.groupCount()); + assertTrue(matcher.find()); + String group = matcher.group(); + assertNotNull(group); + assertTrue(group.length() > 0); + assertTrue(group.length() <= maximumValidDateLength); + } + + final String[] invalidDates = { + "", + "nodate", + "12345", + "1-2", + "11-222-33", + "11-22-##-20", + "05-06-a2013" + }; + + for(String invalidDate : invalidDates) { + Matcher matcher = pattern.matcher(invalidDate); + assertEquals(1, matcher.groupCount()); + assertFalse(matcher.find()); + } + } /** * Utility method to get contact ids for all existing accounts. */ private long[] getContactIdsForAllAccounts() { Account[] accounts = mNabApi.getAccounts(); List<Long> idsArray = new ArrayList<Long>(); if(accounts != null) { final int NUM_ACCOUNTS = accounts.length; for(int i = 0; i < NUM_ACCOUNTS; i++) { Account account = accounts[i]; if(account != null) { long ids[] = mNabApi.getContactIds(account); if(ids != null) { final int NUM_IDS = ids.length; for(int j=0; j < NUM_IDS; j++) { idsArray.add(Long.valueOf(ids[j])); } } } } } long nullAccountIds[] = mNabApi.getContactIds(null); if(nullAccountIds != null) { final int NUM_IDS = nullAccountIds.length; for(int i = 0; i < NUM_IDS; i++) { idsArray.add(Long.valueOf(nullAccountIds[i])); } } final int idsCount = idsArray.size(); if(idsCount > 0 ) { long[] ids = new long[idsCount]; for(int i = 0; i < idsCount; i++) { ids[i] = idsArray.get(i); } return ids; } return null; } /** * Utility method to put the thread waiting * @param time */ private void threadWait(int time) { try { synchronized(this) { wait(time); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Utility method to put the thread to sleep * @param time */ private void threadSleep(int time) { try { synchronized(this) { Thread.sleep(time); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Utility method to verify the presence of people accounts * @param numExpectedAccounts The number of expected Accounts */ private void verifyPeopleAccountPresence(final int numExpectedAccounts) { if(numExpectedAccounts > 0) { assertTrue(mNabApi.isPeopleAccountCreated()); } else { assertFalse(mNabApi.isPeopleAccountCreated()); } int peopleAccountsFound = 0; final Account[] accounts = mNabApi.getAccounts(); if(accounts != null) { final int numAccounts = accounts.length; for(int i = 0; i < numAccounts; i++) { if(accounts[i] != null && accounts[i].isPeopleAccount()) { peopleAccountsFound++; } } } assertEquals(numExpectedAccounts, peopleAccountsFound); } /** * Utility method to verify that received Ids for a new Contact are as expected */ private void verifyNewContactIds(long expectedNabId, ContactChange[] originalCcList, ContactChange[] ids) { assertNotNull(ids); final int idsCount = ids.length; final int originalCount = originalCcList.length; assertEquals(originalCount + 1, idsCount); final long expectedInternalContactId = originalCcList[0].getInternalContactId(); long previousDetailId = ContactChange.INVALID_ID; long orgAndTitleNabDetailId = ContactChange.INVALID_ID; for(int i= 0; i < idsCount; i++) { final ContactChange idCc = ids[i]; if(!VersionUtils.is2XPlatform() && i > 0) { final int originalKey = originalCcList[i-1].getKey(); if(originalKey == ContactChange.KEY_VCARD_NAME || originalKey == ContactChange.KEY_VCARD_NOTE || originalKey == ContactChange.KEY_VCARD_NICKNAME || originalKey == ContactChange.KEY_VCARD_URL) { // These fields don't get written to 1.X NAB and so correspond to a null idCc assertNull(idCc); continue; } } assertNotNull(idCc); // Internal Contact ID check assertEquals(expectedInternalContactId, idCc.getInternalContactId()); if(i > 0) { // Internal Detail ID check final ContactChange originalCc = originalCcList[i-1]; assertEquals(originalCcList[i-1].getInternalDetailId(), ids[i].getInternalDetailId()); // NAB Detail ID check assertEquals(ContactChange.TYPE_UPDATE_NAB_DETAIL_ID, ids[i].getType()); long currentDetailId = ids[i].getNabDetailId(); if(previousDetailId != ContactChange.INVALID_ID) { if(originalCc.getKey() != ContactChange.KEY_VCARD_ORG && originalCc.getKey() != ContactChange.KEY_VCARD_TITLE) { if(VersionUtils.is2XPlatform()) { // Only checking on 2.X because 1.X does not guarantee sequential ids // for the details (diff tables) assertEquals(previousDetailId+1, currentDetailId); } } else { // Org and title share nab detail id on both 1.X and 2.X! if(orgAndTitleNabDetailId == ContactChange.INVALID_ID) { orgAndTitleNabDetailId = currentDetailId; } else { assertEquals(orgAndTitleNabDetailId, currentDetailId); } } } previousDetailId = currentDetailId; } else { assertEquals(ContactChange.TYPE_UPDATE_NAB_CONTACT_ID, ids[i].getType()); // NAB Contact ID check if(expectedNabId != ContactChange.INVALID_ID) { assertEquals(expectedNabId, ids[0].getNabContactId()); } } } } /** * Utility method to verify that received Ids for a update Contact are as expected */ private void verifyUpdateContactIds(ContactChange[] contactCcList, ContactChange[] updateCcList, ContactChange[] ids) { if(updateCcList == null || updateCcList.length == 0) { return; } assertNotNull(ids); final int idsSize = ids.length; assertTrue(idsSize > 0); final int updatedCcListSize = updateCcList.length; assertEquals(updatedCcListSize, idsSize); final long nabContactId = updateCcList[0].getNabContactId(); for(int i = 0 ; i < updatedCcListSize; i++) { if(updateCcList[i].getType() == ContactChange.TYPE_ADD_DETAIL) { final int key = updateCcList[i].getKey(); if(VersionUtils.is2XPlatform() || (key != ContactChange.KEY_VCARD_NAME && key != ContactChange.KEY_VCARD_NOTE)) { assertNotNull(ids[i]); assertEquals(ContactChange.TYPE_UPDATE_NAB_DETAIL_ID, ids[i].getType()); assertTrue(ids[i].getNabDetailId() != ContactChange.INVALID_ID); assertEquals(nabContactId, ids[i].getNabContactId()); } } else { assertNull(ids[i]); } } } - - private void waitForAccountsChange(AccountsObserver observer, int expectedNumAccounts) { - final int maxTimeSleep = 1000000; - int timeslept = 0; - while(timeslept < maxTimeSleep) { - try { - Thread.sleep(100); - timeslept+=100; - } catch (InterruptedException e) { - assertEquals(expectedNumAccounts, observer.getCurrentNumAccounts()); - } - } - } } diff --git a/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeImporterTest.java b/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeImporterTest.java index fcd005e..aa03f4c 100644 --- a/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeImporterTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeImporterTest.java @@ -721,553 +721,552 @@ public class NativeImporterTest extends TestCase { if (mPeopleContacts.containsKey(nativeId)) { mPeopleContacts.remove(nativeId); } return false; } @Override public ContactChange[] getContact(long nativeId) { // return a copy, the NativeImporter may mess with it final ContactChange[] original = mPeopleContacts.get(nativeId); ContactChange[] copy = null; copy = new ContactChange[original.length]; for (int i = 0; i < original.length; i++) { copy[i] = copyContactChange(original[i]); } return copy; } @Override public void updateNativeContact(ContactChange[] contact) { // get the original contact final ContactChange[] originalContact = getContact(contact[0].getNabContactId()); final ArrayList<ContactChange> contactArrayList = new ArrayList<ContactChange>(); // put it in an ArrayList so we can easily manipulate it for (int i = 0; i < originalContact.length; i++) { contactArrayList.add(originalContact[i]); } // apply the updates for (int i = 0; i < contact.length; i++) { final ContactChange change = copyContactChange(contact[i]); final int type = change.getType(); switch(type) { case ContactChange.TYPE_ADD_DETAIL: change.setInternalDetailId(mLocalDetailId++); change.setType(ContactChange.TYPE_UNKNOWN); contactArrayList.add(change); break; case ContactChange.TYPE_DELETE_DETAIL: case ContactChange.TYPE_UPDATE_DETAIL: for (int j = 0; j < contactArrayList.size(); j++) { final ContactChange changeInList = contactArrayList.get(j); if (changeInList.getNabDetailId() == change.getNabDetailId()) { if (type == ContactChange.TYPE_DELETE_DETAIL) { contactArrayList.remove(j); } else { change.setType(ContactChange.TYPE_UNKNOWN); contactArrayList.set(j, change); } break; } } break; } } // set the updated contact back final ContactChange[] newContactChanges = new ContactChange[contactArrayList.size()]; contactArrayList.toArray(newContactChanges); mPeopleContacts.put(newContactChanges[0].getNabContactId(), newContactChanges); } } /** * Mocks up the NativeContactsApi. */ public static class NativeContactsApiMockup extends NativeContactsApi { /** * A Hashtable of contacts where the key is the contact id. */ private Hashtable<Long, ContactChange[]> mNativeContacts = new Hashtable<Long, ContactChange[]>(); /** * An Hashtable of accounts associated to an array of contact ids. */ private Hashtable<Account, ArrayList<Long>> mAccounts = new Hashtable<Account, ArrayList<Long>>(); /** * The counter used to generate new contact ids. */ private int mNabId = 1; /** * The counter used to generate new detail ids. */ private int mNabDetailId = 1; public int getAndIncNabDetailId() { return mNabDetailId++; } @Override public ContactChange[] getContact(long nabContactId) { // return a copy, the NativeImporter may mess with it final ContactChange[] original = mNativeContacts.get(nabContactId); ContactChange[] copy = null; if (original != null) { copy = new ContactChange[original.length]; for (int i = 0; i < original.length; i++) { copy[i] = copyContactChange(original[i]); } } return copy; } @Override public long[] getContactIds(Account account) { if (account == null) { // return all the ids if (mNativeContacts.size() > 0) { final Enumeration<ContactChange[]> e = mNativeContacts.elements(); final long[] ids = new long[mNativeContacts.size()]; int idIndex = 0; while (e.hasMoreElements()) { final ContactChange[] contact = e.nextElement(); ids[idIndex++] = contact[0].getNabContactId(); } Arrays.sort(ids); return ids; } else { return null; } } else { // return the ids depending on the account final ArrayList<Long> idsArray = mAccounts.get(account); if (idsArray != null) { final long[] ids = new long[idsArray.size()]; for (int i = 0; i < ids.length; i++) { ids[i] = idsArray.get(i); } Arrays.sort(ids); return ids; } } return null; } /** * */ public void feedAccount(Account account) { mAccounts.put(account, new ArrayList<Long>()); } /** * * @param nativeId * @param newContactChange */ public void setContact(long nativeId, ContactChange[] newContactChange) { mNativeContacts.put(nativeId, newContactChange); } @Override public ContactChange[] addContact(Account account, ContactChange[] ccList) { // set the native ids for (int i = 0; i < ccList.length; i++) { ccList[i].setNabContactId(mNabId); ccList[i].setNabDetailId(mNabDetailId++); } mNabId++; mNativeContacts.put(ccList[0].getNabContactId(), ccList); if (account != null) { // add the contact id in the account as well final ArrayList<Long> ids = mAccounts.get(account); ids.add(ccList[0].getNabContactId()); } // we have to return an array of native ids ContactChange[] copy = null; copy = new ContactChange[ccList.length + 1]; copy[0] = copyContactChange(ccList[0]); for (int i = 0; i < ccList.length; i++) { copy[i+1] = copyContactChange(ccList[i]); } return copy; } @Override public boolean addPeopleAccount(String username) { // TODO Auto-generated method stub return false; } @Override public Account[] getAccounts() { if (mAccounts.size() == 0) { return null; } else { int index = 0; Account[] accounts = new Account[mAccounts.size()]; Enumeration<Account> enumeration = mAccounts.keys(); while (enumeration.hasMoreElements()) { accounts[index++] = enumeration.nextElement(); } return accounts; } } @Override public Account[] getAccountsByType(int type) { switch (type){ case GOOGLE_ACCOUNT_TYPE: return filterAccountsByType(getAccounts(), GOOGLE_ACCOUNT_TYPE_STRING); case PEOPLE_ACCOUNT_TYPE: return filterAccountsByType(getAccounts(), PEOPLE_ACCOUNT_TYPE_STRING); default: return null; } } @Override protected void initialize() { // TODO Auto-generated method stub } @Override public boolean isPeopleAccountCreated() { // TODO Auto-generated method stub return false; } @Override public void registerObserver(ContactsObserver observer) { // TODO Auto-generated method stub } @Override public void removeContact(long nabContactId) { final Account[] accounts = getAccounts(); if (accounts != null) { for (int i = 0; i < accounts.length; i++) { final ArrayList<Long> ids = mAccounts.get(accounts[i]); ids.remove(nabContactId); } } mNativeContacts.remove(nabContactId); } @Override public void removePeopleAccount() { // TODO Auto-generated method stub } @Override public void unregisterObserver() { // TODO Auto-generated method stub } @Override public ContactChange[] updateContact(ContactChange[] ccList) { // get the original contact final ContactChange[] originalContact = getContact(ccList[0].getNabContactId()); final ArrayList<ContactChange> contactArrayList = new ArrayList<ContactChange>(); // put it in an ArrayList so we can easily manipulate it for (int i = 0; i < originalContact.length; i++) { contactArrayList.add(originalContact[i]); } final ContactChange[] returnedChanges = new ContactChange[ccList.length]; // apply the updates for (int i = 0; i < ccList.length; i++) { final ContactChange change = copyContactChange(ccList[i]); final int type = change.getType(); switch(type) { case ContactChange.TYPE_ADD_DETAIL: returnedChanges[i] = copyContactChange(ccList[i]); returnedChanges[i].setNabDetailId(mNabDetailId); returnedChanges[i].setType(ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); change.setInternalDetailId(mNabDetailId++); change.setType(ContactChange.TYPE_UNKNOWN); contactArrayList.add(change); break; case ContactChange.TYPE_DELETE_DETAIL: case ContactChange.TYPE_UPDATE_DETAIL: for (int j = 0; j < contactArrayList.size(); j++) { final ContactChange changeInList = contactArrayList.get(j); if (changeInList.getNabDetailId() == change.getNabDetailId()) { if (type == ContactChange.TYPE_DELETE_DETAIL) { contactArrayList.remove(j); } else { change.setType(ContactChange.TYPE_UNKNOWN); contactArrayList.set(j, change); } break; } } returnedChanges[i] = null; break; } } // set the updated contact back final ContactChange[] newContactChanges = new ContactChange[contactArrayList.size()]; contactArrayList.toArray(newContactChanges); mNativeContacts.put(newContactChanges[0].getNabContactId(), newContactChanges); return ccList; } @Override public boolean isKeySupported(int key) { return true; } @Override public boolean getMasterSyncAutomatically() { // TODO Auto-generated method stub return false; } @Override public void setSyncable(boolean syncable) { // TODO Auto-generated method stub } @Override public void setSyncAutomatically(boolean syncAutomatically) { // TODO Auto-generated method stub } } /** * A second version of PeopleContactsApiMockup only used for testing accounts. * * Note: it is a modified version of PeopleContactsApiMockup which adds a trick * on the id used to store the contact in order to easily test the account features * without writing a more sophisticated mockup of PeopleContactsApi. */ public class PeopleContactsApiMockup2 extends PeopleContactsApiMockup { public PeopleContactsApiMockup2(DatabaseHelper dbh) { super(null); } @Override public long[] getNativeContactsIds() { if (mPeopleContacts.size() > 0) { final Enumeration<ContactChange[]> e = mPeopleContacts.elements(); final long[] ids = new long[mPeopleContacts.size()]; int idIndex = 0; while (e.hasMoreElements()) { final ContactChange[] contact = e.nextElement(); ids[idIndex++] = contact[0].getInternalContactId(); } Arrays.sort(ids); return ids; } else { return null; } } @Override public boolean addNativeContact(ContactChange[] contact) { // set the local ids for (int i = 0; i < contact.length; i++) { contact[i].setInternalContactId(mLocalContactId); contact[i].setInternalDetailId(mLocalDetailId++); } mLocalContactId++; // add the contact via its local id because on first time import, the native ids are // removed on 2.X platform because the export will be done to the People account // so they will get different native ids. mPeopleContacts.put(contact[0].getInternalContactId(), contact); return true; } } /** * Gets the value of a field via reflection. * * @param fieldName the name of the field to retrieve * @param zClass the class where to look for the field * @return the field value */ private static Object getField(String fieldName, Class zClass) { try { Field fName = zClass.getDeclaredField(fieldName); fName.setAccessible(true); return fName.get(null); } catch (Exception e) { Log.e("NativeImporterTest", "getField(), error retrieving the field value... => " + e); } return null; } /** * Alter the given ContactChange value. * * @param change the change to modify * @param newValue the new value to set to the provided ContactChange * @return a new ContactChange with the modified value */ public static ContactChange alterContactChangeValue(ContactChange change, String newValue) { final ContactChange alteredContactChange = new ContactChange(change.getKey(), newValue, change.getFlags()); alteredContactChange.setBackendContactId(change.getBackendContactId()); alteredContactChange.setBackendDetailId(change.getBackendDetailId()); alteredContactChange.setInternalContactId(change.getInternalContactId()); alteredContactChange.setInternalDetailId(change.getInternalDetailId()); alteredContactChange.setNabContactId(change.getNabContactId()); alteredContactChange.setNabDetailId(change.getNabDetailId()); return alteredContactChange; } /** * Copies a ContactChange. * * @param change the change to copy * @return a deep copy of the ContactChange */ public static ContactChange copyContactChange(ContactChange change) { final ContactChange copy = new ContactChange(change.getKey(), change.getValue(), change.getFlags()); copy.setBackendContactId(change.getBackendContactId()); copy.setBackendDetailId(change.getBackendDetailId()); copy.setInternalContactId(change.getInternalContactId()); copy.setInternalDetailId(change.getInternalDetailId()); copy.setNabContactId(change.getNabContactId()); copy.setNabDetailId(change.getNabDetailId()); copy.setType(change.getType()); - copy.setDestinations(change.getDestinations()); return copy; } /** * Filters the given array of accounts by the given type. * * @param accounts the array of accounts to filter * @param type the type of accounts to filter * @return an array containing the filtered accounts or null if none */ private static Account[] filterAccountsByType(Account[] accounts, String type) { if (accounts != null) { final int length = accounts.length; final ArrayList<Account> matchingAccounts = new ArrayList<Account>(length); // find the corresponding accounts for (int i = 0; i < length; i++) { final Account account = accounts[i]; if (type.equals(account.getType())) { matchingAccounts.add(account); } } if (matchingAccounts.size() > 0) { accounts = new Account[matchingAccounts.size()]; matchingAccounts.toArray(accounts); return accounts; } } return null; } }
360/360-Engine-for-Android
7c8fae8c1d7d45757fa94fa0a9802aab7d41e145
fixed code review comments.
diff --git a/tests/src/com/vodafone360/people/tests/service/PeopleServiceTest.java b/tests/src/com/vodafone360/people/tests/service/PeopleServiceTest.java index 192f31e..0c6dedf 100644 --- a/tests/src/com/vodafone360/people/tests/service/PeopleServiceTest.java +++ b/tests/src/com/vodafone360/people/tests/service/PeopleServiceTest.java @@ -1,583 +1,582 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.tests.service; import java.util.ArrayList; import java.util.List; import android.R; import android.app.Instrumentation; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.test.ServiceTestCase; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import com.vodafone360.people.MainApplication; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.agent.NetworkAgentState; import com.vodafone360.people.service.agent.NetworkAgent.AgentState; import com.vodafone360.people.service.interfaces.IPeopleService; import com.vodafone360.people.service.io.ResponseQueue; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.IConnection; import com.vodafone360.people.tests.IPeopleTestFramework; import com.vodafone360.people.tests.PeopleTestConnectionThread; @Suppress public class PeopleServiceTest extends ServiceTestCase<RemoteService> implements IPeopleTestFramework { private final static String LOG_TAG = "PeopleServiceTest"; private final static boolean ENABLE_REGISTRATION_TEST = true; private final static int TEST_RESPONSE = 1; private final static int WAIT_EVENT_TIMEOUT_MS = 30000; private IPeopleService mPeopleService = null; private MainApplication mApplication = null; private Thread mEventWatcherThread = null; private Handler mHandler; private Object mUiRequestData = null; private ServiceStatus mStatus = null; private PeopleServiceTest mParent = null; private PeopleTestConnectionThread mTestConn = new PeopleTestConnectionThread(this); private boolean mActive = false; private boolean mEventThreadStarted = false; /* * TODO: Fix NullPointerException caused by EngineManager not yet created at this point. * Solution: call RemoteService.onCreate() first. */ private ConnectionManager mConnMgr; //private ConnectionManager mConnMgr = ConnectionManager.getInstance(); public PeopleServiceTest() { super(RemoteService.class); lazyLoadPeopleService(); mConnMgr = ConnectionManager.getInstance(); // Must be called after createService() Log.i(LOG_TAG, "PeopleServiceTest()"); mParent = this; } @Override protected void setUp() throws Exception { mConnMgr.setTestConnection(mTestConn); mTestConn.startThread(); } @Override protected void tearDown() throws Exception { if (mPeopleService != null && mHandler != null) { mPeopleService.removeEventCallback(mHandler); } - mConnMgr.free(); super.tearDown(); } protected void eventWatcherThreadMain() { Looper.prepare(); synchronized (this) { mHandler = new Handler() { @Override public void handleMessage(Message msg) { mActive = false; synchronized (mParent) { processMsg(msg); mParent.notify(); } } }; mEventThreadStarted = true; mParent.notify(); } Looper.loop(); } protected void processMsg(Message msg) { mStatus = ServiceStatus.fromInteger(msg.arg2); mUiRequestData = msg.obj; } private boolean matchResponse(int expectedType) { switch (expectedType) { case TEST_RESPONSE: return (mUiRequestData == null); default: return false; } } private synchronized ServiceStatus waitForEvent(long timeout, int respType) { long timeToFinish = System.nanoTime() + (timeout * 1000000); long remainingTime = timeout; mActive = true; while (mActive == true && remainingTime > 0) { try { wait(remainingTime); } catch (InterruptedException e) { // Do nothing. } remainingTime = (timeToFinish - System.nanoTime()) / 1000000; } if (!(matchResponse(respType))) { return ServiceStatus.ERROR_UNKNOWN; } return mStatus; } private boolean testContext(Context context) { try { context.getString(R.string.cancel); } catch (Exception e) { return false; } return true; } synchronized private boolean lazyLoadPeopleService() { if (mPeopleService != null) { return true; } try { mApplication = (MainApplication)Instrumentation.newApplication(MainApplication.class, getSystemContext() // Not good enough, must be Target Context?? ); Log.e(LOG_TAG, "Test 1 ["+testContext(getContext())+"]"); Log.e(LOG_TAG, "Test 2 ["+testContext(getSystemContext())+"]"); Log.e(LOG_TAG, "Test 3 ["+testContext(mApplication.getApplicationContext())+"]"); Log.e(LOG_TAG, "Test 4 ["+testContext(mApplication)+"]"); Instrumentation i = new Instrumentation(); i.getTargetContext(); Log.e(LOG_TAG, "Test 5 ["+testContext(i.getTargetContext())+"]"); //Tests: maybe have to get getInstrumentation().getTargetContext() ?? //Log.e(LOG_TAG, "Test 5 ["+testContext(getInstrumentation().getTargetContext())+"]"); mApplication.onCreate(); setApplication(mApplication); //Call before startService() } catch (ClassNotFoundException e){ Log.e(LOG_TAG, "ClassNotFoundException " + e.toString()); } catch (IllegalAccessException e){ Log.e(LOG_TAG, "IllegalAccessException " + e.toString()); } catch (InstantiationException e){ Log.e(LOG_TAG, "InstantiationException " + e.toString()); } // Explicitly start the service. Intent serviceIntent = new Intent(); serviceIntent.setClassName("com.vodafone360.people", "com.vodafone360.people.service.RemoteService"); startService(serviceIntent); mPeopleService = mApplication.getServiceInterface(); if (mPeopleService == null) { return false; } mEventWatcherThread = new Thread(new Runnable() { @Override public void run() { eventWatcherThreadMain(); } }); mEventWatcherThread.start(); while (!mEventThreadStarted) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // Add service handler. mPeopleService.addEventCallback(mHandler); // Restart thread. mTestConn.startThread(); return true; } /* * List of APIs that are called in tests within this class: * mPeopleService.fetchUsernameState(name); * mPeopleService.fetchTermsOfService(); * mPeopleService.fetchPrivacyStatement(); * mPeopleService.register(details); * mPeopleService.addEventCallback(mHandler); * mPeopleService.removeEventCallback(mHandler); * mPeopleService.getLoginRequired(); * mPeopleService.logon(loginDetails); * mPeopleService.fetchAvailableIdentities(filter); * mPeopleService.fetchMyIdentities(filter); * mPeopleService.validateIdentityCredentials(false, "facebook", "testUser", "testPass", null); * mPeopleService.setIdentityCapabilityStatus("facebook", "testUser", stat); * mPeopleService.getRoamingNotificationType(); * mPeopleService.setForceConnection(true); * mPeopleService.getForceConnection() * mPeopleService.getRoamingDeviceSetting(); * mPeopleService.notifyDataSettingChanged(InternetAvail.ALWAYS_CONNECT); * mPeopleService.setShowRoamingNotificationAgain(true); * mPeopleService.setNetworkAgentState(sas); * mPeopleService.getNetworkAgentState(); * mPeopleService.startActivitySync(); * mPeopleService.startBackgroundContactSync(); * mPeopleService.startContactSync(); * * void checkForUpdates(); * void setNewUpdateFrequency(); * PresenceList getPresenceList(); * */ public void testRegistration() { if (!ENABLE_REGISTRATION_TEST) { Log.i(LOG_TAG, "Skipping registration tests..."); return; } Log.i(LOG_TAG, "**** testRegistration ****\n"); assertTrue("Unable to create People service", lazyLoadPeopleService()); String name = "scottkennedy1111"; Log.i(LOG_TAG, "Fetching username state for a name (" + name + ") - checking correct state is returned"); mPeopleService.fetchUsernameState(name); ServiceStatus status = waitForEvent(WAIT_EVENT_TIMEOUT_MS, TEST_RESPONSE); assertEquals("fetchUsernameState() failed with status = " + status.name(), ServiceStatus.ERROR_INTERNAL_SERVER_ERROR, status); Log.i(LOG_TAG, "Fetching terms of service..."); mPeopleService.fetchTermsOfService(); status = waitForEvent(WAIT_EVENT_TIMEOUT_MS, TEST_RESPONSE); assertEquals("fetchTermsOfService() failed with status = " + status.name(), ServiceStatus.ERROR_INTERNAL_SERVER_ERROR, status); Log.i(LOG_TAG, "Fetching privacy statement..."); mPeopleService.fetchPrivacyStatement(); status = waitForEvent(WAIT_EVENT_TIMEOUT_MS, TEST_RESPONSE); assertEquals("fetchPrivacyStatement() failed with status = " + status.name(), ServiceStatus.ERROR_INTERNAL_SERVER_ERROR, status); Log.i(LOG_TAG, "Trying to register new account (username: " + name + ")"); RegistrationDetails details = new RegistrationDetails(); details.mFullname = "Gerry Rafferty"; details.mUsername = name; details.mPassword = "TestTestTest"; details.mAcceptedTAndC = true; details.mBirthdayDate = "1978-01-01"; details.mCountrycode = "En"; details.mEmail = "[email protected]"; details.mLanguage = "English"; details.mMobileModelId = 1L; details.mMobileOperatorId = 1L; details.mMsisdn = "447775128930"; details.mSendConfirmationMail = false; details.mSendConfirmationSms = true; details.mSubscribeToNewsLetter = false; details.mTimezone = "GMT"; mPeopleService.register(details); status = waitForEvent(WAIT_EVENT_TIMEOUT_MS, TEST_RESPONSE); assertEquals("register() failed with status = " + status.name(), ServiceStatus.ERROR_INTERNAL_SERVER_ERROR, status); Log.i(LOG_TAG, "**** testRegistration (SUCCESS) ****\n"); } public void testLogin(){ Log.i(LOG_TAG, "**** testLogin ****\n"); if (!lazyLoadPeopleService()) { throw(new RuntimeException("Unable to create People service")); } try { boolean ret = mPeopleService.getLoginRequired(); Log.i(LOG_TAG, "getLoginRequired returned = "+ret); } catch(Exception e) { Log.e(LOG_TAG, "getLoginRequired() failed with exception = "+e.getLocalizedMessage()); e.printStackTrace(); } Log.i(LOG_TAG, "logon with test credentials"); LoginDetails loginDetails = new LoginDetails(); loginDetails.mUsername = "testUser"; loginDetails.mPassword = "testPass"; loginDetails.mMobileNo = "+447502272981"; mPeopleService.logon(loginDetails); ServiceStatus status = waitForEvent(WAIT_EVENT_TIMEOUT_MS, TEST_RESPONSE); assertEquals("logon() failed with status = " + status.name(), ServiceStatus.ERROR_INTERNAL_SERVER_ERROR, status); Log.i(LOG_TAG, "**** testLogin (SUCCESS) ****\n"); } public void testIdentities(){ Log.i(LOG_TAG, "**** testIdentities ****\n"); assertTrue("Unable to create People service", lazyLoadPeopleService()); AuthSessionHolder ash = new AuthSessionHolder(); ash.sessionID = "adf32419086bc23"; ash.sessionSecret = "234789123678234"; ash.userID = 10; ash.userName = "testUser"; EngineManager em = EngineManager.getInstance(); if (em!=null) { Log.i(LOG_TAG, "Creating login Engine"); em.getLoginEngine().setActivatedSession(ash); } else { Log.e(LOG_TAG, "Failed to get EngineManager"); assertTrue("Failed to get EngineManager", false); } if (LoginEngine.getSession() == null) { Log.e(LOG_TAG, "Failed to set fake session"); assertTrue("Can't set fake session", false); } Bundle filter = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); l.add(IdentityCapability.CapabilityID.get_own_status.name()); filter.putStringArrayList("capability", l); mPeopleService.getAvailableThirdPartyIdentities(); ServiceStatus status = waitForEvent(WAIT_EVENT_TIMEOUT_MS, TEST_RESPONSE); assertEquals("fetchAvailableIdentities() failed with status = " + status.name(), ServiceStatus.ERROR_INTERNAL_SERVER_ERROR, status); mPeopleService.getMyThirdPartyIdentities(); status = waitForEvent(WAIT_EVENT_TIMEOUT_MS, TEST_RESPONSE); assertEquals("fetchMyIdentities() failed with status = " + status.name(), ServiceStatus.ERROR_INTERNAL_SERVER_ERROR, status); Log.i(LOG_TAG, "**** testIdentities (SUCCESS) ****\n"); } public void testSettingGettingRoaming(){ boolean testPass = true; Log.i(LOG_TAG, "**** testSettingGettingRoaming ****\n"); if (!lazyLoadPeopleService()) { throw(new RuntimeException("Unable to create People service")); } try { int type = mPeopleService.getRoamingNotificationType(); Log.i(LOG_TAG,"getRoamingNotificationType() = "+type); } catch(Exception e) { testPass = false; Log.e(LOG_TAG, "getRoamingNotificationType() failed = "+e.getMessage()); e.printStackTrace(); } try { boolean roamPermited = mPeopleService.getRoamingDeviceSetting(); Log.i(LOG_TAG,"getRoamingDeviceSetting() roaming permited = "+roamPermited); } catch(Exception e) { testPass = false; Log.e(LOG_TAG, "getRoamingDeviceSetting() failed = "+e.getMessage()); e.printStackTrace(); } try { mPeopleService.notifyDataSettingChanged(InternetAvail.ALWAYS_CONNECT); } catch(Exception e) { testPass = false; Log.e(LOG_TAG, "notifyDataSettingChanged() failed = "+e.getMessage()); e.printStackTrace(); } try { mPeopleService.setShowRoamingNotificationAgain(true); } catch(Exception e) { testPass = false; Log.e(LOG_TAG, "setShowRoamingNotificationAgain() failed = "+e.getMessage()); e.printStackTrace(); } if (!testPass) { Log.e(LOG_TAG, "**** testSettingGettingRoaming (FAILED) ****\n"); } assertTrue("testSettingGettingRoaming() failed", testPass); Log.i(LOG_TAG, "**** testSettingGettingRoaming (SUCCESS) ****\n"); } public void testNetworkAgent(){ boolean testPass = true; Log.i(LOG_TAG, "**** testNetworkAgent ****\n"); if (!lazyLoadPeopleService()) { throw(new RuntimeException("Unable to create People service")); } try { NetworkAgentState sas = new NetworkAgentState(); boolean[] changes = new boolean[NetworkAgent.StatesOfService.values().length]; for(int i=0; i<changes.length;i++){ changes[i] = true; } sas.setChanges(changes); sas.setInternetConnected(false); mPeopleService.setNetworkAgentState(sas); if (mPeopleService.getNetworkAgentState().getAgentState() != AgentState.DISCONNECTED ) { testPass = false; Log.e(LOG_TAG,"get/set NetworkAgentState() failed for setting DISCONNECTED"); } sas.setInternetConnected(true); sas.setNetworkWorking(true); mPeopleService.setNetworkAgentState(sas); if (mPeopleService.getNetworkAgentState().getAgentState() != AgentState.CONNECTED) { testPass = false; Log.e(LOG_TAG,"get/set NetworkAgentState() failed for setting CONNECTED"); } } catch(Exception e) { testPass = false; Log.e(LOG_TAG, "testNetworkAgent() failed = "+e.getMessage()); e.printStackTrace(); } if (!testPass) { Log.e(LOG_TAG, "**** testNetworkAgent (FAILED) ****\n"); } assertTrue("testNetworkAgent() failed", testPass); Log.i(LOG_TAG, "**** testNetworkAgent (SUCCESS) ****\n"); } public void testStartingVariousSyncs(){ boolean testPass = true; Log.i(LOG_TAG, "**** testStartingVariousSyncs ****\n"); if (!lazyLoadPeopleService()) { throw(new RuntimeException("Unable to create People service")); } try{ mPeopleService.startStatusesSync(); mPeopleService.startBackgroundContactSync(0); mPeopleService.startContactSync(); } catch(Exception e) { testPass = false; Log.e(LOG_TAG, "testStartingVariousSyncs() failed = "+e.getMessage()); e.printStackTrace(); } if (!testPass) { Log.e(LOG_TAG, "**** testStartingVariousSyncs (FAILED) ****\n"); } assertTrue("testStartingVariousSyncs() failed", testPass); Log.i(LOG_TAG, "**** testStartingVariousSyncs (SUCCESS) ****\n"); } public void testUpdates() { boolean testPass = true; Log.i(LOG_TAG, "**** testUpdates ****\n"); if (!lazyLoadPeopleService()) { throw(new RuntimeException("Unable to create People service")); } try { mPeopleService.checkForUpdates(); mPeopleService.setNewUpdateFrequency(); } catch(Exception e) { testPass = false; Log.e(LOG_TAG, "testUpdates() failed = "+e.getMessage()); e.printStackTrace(); } if (!testPass) { Log.e(LOG_TAG, "**** testUpdates (FAILED) ****\n"); } assertTrue("testUpdates() failed", testPass); Log.i(LOG_TAG, "**** testUpdates (SUCCESS) ****\n"); } //TODO: to be updated public void testPresence() { boolean testPass = true; Log.i(LOG_TAG, "**** testPresence ****\n"); if (!lazyLoadPeopleService()) { throw(new RuntimeException("Unable to create People service")); } try { mPeopleService.getPresenceList(-1L); } catch(Exception e) { testPass = false; Log.e(LOG_TAG, "testPresence() failed = "+e.getMessage()); e.printStackTrace(); } if (!testPass) { Log.e(LOG_TAG, "**** testPresence (FAILED) ****\n"); } assertTrue("testPresence() failed", testPass); Log.i(LOG_TAG, "**** testPresence (SUCCESS) ****\n"); } @Override public IConnection testConnectionThread() { return null; } @Override public void reportBackToFramework(int reqId, EngineId engine) { /* * We are not interested in testing specific engines in those tests then for all kind of * requests we will return error because it is handled by all engines, just to finish flow. */ ResponseQueue respQueue = ResponseQueue.getInstance(); List<BaseDataType> data = new ArrayList<BaseDataType>(); ServerError se1 = new ServerError(ServerError.ErrorType.INTERNALERROR); se1.errorDescription = "Test error produced by test framework, ignore it"; data.add(se1); respQueue.addToResponseQueue(new DecodedResponse(reqId, data, engine, DecodedResponse.ResponseType.SERVER_ERROR.ordinal())); } } \ No newline at end of file
360/360-Engine-for-Android
cb525ba7f0f8cfaf6646baea42a9ef366b9029bf
PAND-2451: removed local variable which stores the LoginEngine state, refer to the Engine directly
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 6dbfdff..56e25a0 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,894 +1,893 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.MePresenceCacheTable; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.ChatMessage; import com.vodafone360.people.datatypes.Conversation; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.PresenceList; import com.vodafone360.people.datatypes.PushAvailabilityEvent; import com.vodafone360.people.datatypes.PushChatMessageEvent; import com.vodafone360.people.datatypes.PushClosedConversationEvent; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.datatypes.SystemNotification.Tags; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Chat; import com.vodafone360.people.service.io.api.Presence; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, ITcpConnectionListener { /** Check every 24 hours **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; - /** Reconnecting before firing offline state to the handlers. **/ - private boolean mLoggedIn = false; - private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) - private final List<TimelineSummaryItem> mFailedMessagesList; // (to, network) + /** + * List of not delivered messages. + */ + private final List<TimelineSummaryItem> mFailedMessagesList; /** The list of Users still to be processed. **/ private List<User> mUsers = null; /** * This state indicates there are no more pending presence payload * information to be processed. **/ private static final int IDLE = 0; /** * This state indicates there are some pending presence payload information * to be processed. **/ private static final int UPDATE_PROCESSING_GOING_ON = 1; /** Timeout between each presence update processing. **/ private static final long UPDATE_PRESENCE_TIMEOUT_MILLS = 0; /** The page size i.e the number of presence updates processed at a time. **/ private static final int UPDATE_PRESENCE_PAGE_SIZE = 10; /** The number of pages after which the HandlerAgent is notified. **/ private static final int NOTIFY_AGENT_PAGE_INTERVAL = 5; /** The state of the presence Engine. **/ private int mState = IDLE; /** * Number of pages of presence Updates done. This is used to control when a * notification is sent to the UI. **/ private int mIterations = 0; /** * True if the engine runs for the 1st time. */ private boolean mFirstRun = true; /** * * @param eventCallback * @param databaseHelper */ public PresenceEngine(IEngineEventCallback eventCallback, DatabaseHelper databaseHelper) { super(eventCallback); mEngineId = EngineId.PRESENCE_ENGINE; mDbHelper = databaseHelper; mSendMessagesHash = new Hashtable<String, ChatMessage>(); mFailedMessagesList = new ArrayList<TimelineSummaryItem>(); } @Override public void onCreate() { } @Override public void onDestroy() { if (mDbHelper != null && SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper) != null) { PresenceDbUtils.resetPresenceStatesAcceptForMe(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), mDbHelper); } EngineManager.getInstance().getLoginEngine().removeListener(this); } /** * Checks if the SyncMe and ContactSync Engines have both completed first time sync. * * @return true if both engines have completed first time sync */ private boolean isFirstTimeSyncComplete() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !isLoggedIn()) { return -1; } if (!isFirstTimeSyncComplete()) { LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"); return -1; } /** * need isUiRequestOutstanding() because currently the worker thread is * running and finishing before PresenceEngine.setNextRuntime is called */ if (isCommsResponseOutstanding() || isUiRequestOutstanding()) { LogUtils.logV("PresenceEngine getNextRunTime() comms response outstanding"); return 0; } if (mFirstRun) { getPresenceList(); initSetMyAvailabilityRequestAfterLogin(); mFirstRun = false; } return getCurrentTimeout(); } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" - + isCommsResponseOutstanding() + "] mLoggedIn[" + isLoggedIn() + "] mNextRuntime[" + + isCommsResponseOutstanding() + "] mNextRuntime[" + getCurrentTimeout() + "]"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logV("PresenceEngine.run() handled processCommsInQueue()"); return; } if (processTimeout()) { LogUtils.logV("PresenceEngine.run() handled processTimeout()"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logV("PresenceEngine.run(): AgentState.DISCONNECTED"); setPresenceOffline(); } /** * and the getNextRunTime must check the uiRequestReady() function and * return 0 if it is true */ if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { return isUiRequestOutstanding(); } private User getMyAvailabilityStatusFromDatabase() { return PresenceDbUtils.getMeProfilePresenceStatus(mDbHelper); } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); - mLoggedIn = loggedIn; - if (!isLoggedIn()) { + if (loggedIn) { mFirstRun = true; mFailedMessagesList.clear(); mSendMessagesHash.clear(); setPresenceOffline(); } } /*** * Set the Global presence status to offline. */ private synchronized void setPresenceOffline() { PresenceDbUtils.setPresenceOfflineInDatabase(mDbHelper); // We clear the mUsers of any pending presence updates because this // Offline presence update request should take the highest priority. mUsers = null; mState = IDLE; mEventCallback.getUiAgent().updatePresence(UiAgent.ALL_USERS); } @Override protected void onRequestComplete() { LogUtils.logI("PresenceEngine.onRequestComplete()"); } @Override protected void onTimeoutEvent() { LogUtils.logI("PresenceEngine.onTimeoutEvent()"); switch (mState) { case UPDATE_PROCESSING_GOING_ON: updatePresenceDatabaseNextPage(); break; case IDLE: default: if (isLoggedIn()) { if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setTimeout(CHECK_FREQUENCY); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); setTimeout(CHECK_FREQUENCY / 20); } } break; } } @Override protected void processCommsResponse(DecodedResponse resp) { handleServerResponse(resp.mDataTypes); } private void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg) { UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribedWithChat()) { uiAgent.sendUnsolicitedUiEvent(errorEvent, null); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users List of users that require updating. */ private synchronized void updatePresenceDatabase(List<User> users) { if (users == null || users.size() == 0) { LogUtils.logW("PresenceEngine.updatePresenceDatabase() users is NULL or zero size"); } else { if (mUsers == null) { mUsers = users; } else { // Doing an add one by one is not an efficient way but then // there is an issue in the addAll API. It crashes sometimes. // And the java code for the AddAll API seems to be erroneous. // More investigation is needed on this. for (User user : users) { mUsers.add(user); } } } mState = UPDATE_PROCESSING_GOING_ON; updatePresenceDatabaseNextPage(); } /** * This API makes the presence updates in pages of 10 with a timeout * after each page. The HandlerAgent is notified after every 10 pages. */ private synchronized void updatePresenceDatabaseNextPage(){ UiAgent uiAgent = mEventCallback.getUiAgent(); if(mUsers == null){ mState = IDLE; return; } int listSize = mUsers.size(); int start = 0; int end = UPDATE_PRESENCE_PAGE_SIZE; if(listSize == 0){ mState = IDLE; mUsers = null; return; } else if(listSize < end) { end = listSize; } List<User> userSubset = mUsers.subList(start, end); if ((userSubset != null)) { long idListeningTo = UiAgent.ALL_USERS; if (uiAgent != null) { idListeningTo = uiAgent.getLocalContactId(); } boolean updateUI = PresenceDbUtils.updateDatabase(userSubset, idListeningTo, mDbHelper); userSubset.clear(); // Send the update notification to UI for every UPDATE_PRESENCE_PAGE_SIZE*NOTIFY_AGENT_PAGE_INTERVAL updates. if (updateUI) { if (mUsers.size() == 0 || NOTIFY_AGENT_PAGE_INTERVAL == mIterations) { if (uiAgent != null) { uiAgent.updatePresence(idListeningTo); } mIterations = 0; } else { mIterations++; } } this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true, message.getNetworkId()); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ synchronized public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Method used to set availability of me profile when user logs in. * This is primarily used for reacting to login/connection state changes. */ private void initSetMyAvailabilityRequestAfterLogin() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } String meProfileUserId = Long.toString(PresenceDbUtils.getMeProfileUserId(mDbHelper)); Hashtable<String, String> availability = new Hashtable<String, String>(); ArrayList<Identity> identityList = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if ((identityList.size() != 0)) { for (int i=0; i<identityList.size(); i++) { Identity myIdentity = identityList.get(i); availability.put(myIdentity.mNetwork, OnlineStatus.ONLINE.toString()); } } User meUser = new User(meProfileUserId, availability); meUser.setLocalContactId(Long.valueOf(meProfileUserId)); updateMyPresenceInDatabase(meUser); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } // Get presences Hashtable<String, String> presenceList = getPresencesForStatus(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** * Changes the user's availability. * * @param status - Hashtable<String, String> of pairs <communityName, statusName>. */ public void setMyAvailability(Hashtable<String, String> presenceHash) { if (presenceHash == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceHash); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } /** * Changes the user's availability. * * @param network - SocialNetwork to set presence on. * @param status - OnlineStatus presence status to set. */ public void setMyAvailability(SocialNetwork network, OnlineStatus status) { LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+ network + "=" + status); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); final NetworkPresence newPresence = new NetworkPresence(userId, network.ordinal(), status.ordinal()); presenceList.add(newPresence); User me = new User(userId, null); me.setPayload(presenceList); MePresenceCacheTable.updateCache(newPresence, mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now Hashtable<String, String> presenceHash = new Hashtable<String, String>(); presenceHash.put(network.toString(), status.toString()); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } @Override public void onConnectionStateChanged(int state) { if (isLoggedIn() && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initializeAvailabilityFromDb(); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * Initializes or re-initializes availability from the Database. * If there are cached presences then these will be used * instead of values from the presence table. */ private void initializeAvailabilityFromDb() { final User user = getMyAvailabilityStatusFromDatabase(); ArrayList<NetworkPresence> cachedPresences = MePresenceCacheTable.getCache(mDbHelper.getReadableDatabase()); if(cachedPresences != null) { user.setPayload(cachedPresences); } initSetMyAvailabilityRequest(user); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if (identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); for (Identity identity : identities) { presences.put(identity.mNetwork, statusString); } return presences; } @Override public void onReset() { // reset the engine as if it was just created super.onReset(); mFirstRun = true; - mLoggedIn = false; mIterations = 0; mState = IDLE; mUsers = null; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } + /** + * This method returns if the LoginEngine is in the LOGGED_ON state. + * @return - TRUE if the LoginEngine is in the LOGGED_ON state. + */ private boolean isLoggedIn(){ - if (!mLoggedIn) { - mLoggedIn = EngineManager.getInstance().getLoginEngine().isLoggedIn(); - } - return mLoggedIn; + return EngineManager.getInstance().getLoginEngine().isLoggedIn(); } }
360/360-Engine-for-Android
466c7c9f1fa2276edbf8947b6afaa56553b4c521
PAND-2451 Upgrade of the application leads to problems with setting presence and identities
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 15174dd..6dbfdff 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,888 +1,894 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.MePresenceCacheTable; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.ChatMessage; import com.vodafone360.people.datatypes.Conversation; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.PresenceList; import com.vodafone360.people.datatypes.PushAvailabilityEvent; import com.vodafone360.people.datatypes.PushChatMessageEvent; import com.vodafone360.people.datatypes.PushClosedConversationEvent; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.datatypes.SystemNotification.Tags; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Chat; import com.vodafone360.people.service.io.api.Presence; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, ITcpConnectionListener { /** Check every 24 hours **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private final List<TimelineSummaryItem> mFailedMessagesList; // (to, network) /** The list of Users still to be processed. **/ private List<User> mUsers = null; /** * This state indicates there are no more pending presence payload * information to be processed. **/ private static final int IDLE = 0; /** * This state indicates there are some pending presence payload information * to be processed. **/ private static final int UPDATE_PROCESSING_GOING_ON = 1; /** Timeout between each presence update processing. **/ private static final long UPDATE_PRESENCE_TIMEOUT_MILLS = 0; /** The page size i.e the number of presence updates processed at a time. **/ private static final int UPDATE_PRESENCE_PAGE_SIZE = 10; /** The number of pages after which the HandlerAgent is notified. **/ private static final int NOTIFY_AGENT_PAGE_INTERVAL = 5; /** The state of the presence Engine. **/ private int mState = IDLE; /** * Number of pages of presence Updates done. This is used to control when a * notification is sent to the UI. **/ private int mIterations = 0; /** * True if the engine runs for the 1st time. */ private boolean mFirstRun = true; /** * * @param eventCallback * @param databaseHelper */ public PresenceEngine(IEngineEventCallback eventCallback, DatabaseHelper databaseHelper) { super(eventCallback); mEngineId = EngineId.PRESENCE_ENGINE; mDbHelper = databaseHelper; mSendMessagesHash = new Hashtable<String, ChatMessage>(); mFailedMessagesList = new ArrayList<TimelineSummaryItem>(); } @Override public void onCreate() { } @Override public void onDestroy() { if (mDbHelper != null && SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper) != null) { PresenceDbUtils.resetPresenceStatesAcceptForMe(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), mDbHelper); } EngineManager.getInstance().getLoginEngine().removeListener(this); } /** * Checks if the SyncMe and ContactSync Engines have both completed first time sync. * * @return true if both engines have completed first time sync */ private boolean isFirstTimeSyncComplete() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { - if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { + if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !isLoggedIn()) { return -1; } - if (!isFirstTimeSyncComplete()) { LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"); return -1; } /** * need isUiRequestOutstanding() because currently the worker thread is * running and finishing before PresenceEngine.setNextRuntime is called */ if (isCommsResponseOutstanding() || isUiRequestOutstanding()) { LogUtils.logV("PresenceEngine getNextRunTime() comms response outstanding"); return 0; } if (mFirstRun) { getPresenceList(); initSetMyAvailabilityRequestAfterLogin(); mFirstRun = false; } return getCurrentTimeout(); } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" - + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + + isCommsResponseOutstanding() + "] mLoggedIn[" + isLoggedIn() + "] mNextRuntime[" + getCurrentTimeout() + "]"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logV("PresenceEngine.run() handled processCommsInQueue()"); return; } if (processTimeout()) { LogUtils.logV("PresenceEngine.run() handled processTimeout()"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logV("PresenceEngine.run(): AgentState.DISCONNECTED"); setPresenceOffline(); } /** * and the getNextRunTime must check the uiRequestReady() function and * return 0 if it is true */ if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { return isUiRequestOutstanding(); } private User getMyAvailabilityStatusFromDatabase() { return PresenceDbUtils.getMeProfilePresenceStatus(mDbHelper); } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; - if (!mLoggedIn) { + if (!isLoggedIn()) { mFirstRun = true; mFailedMessagesList.clear(); mSendMessagesHash.clear(); setPresenceOffline(); } } /*** * Set the Global presence status to offline. */ private synchronized void setPresenceOffline() { PresenceDbUtils.setPresenceOfflineInDatabase(mDbHelper); // We clear the mUsers of any pending presence updates because this // Offline presence update request should take the highest priority. mUsers = null; mState = IDLE; mEventCallback.getUiAgent().updatePresence(UiAgent.ALL_USERS); } @Override protected void onRequestComplete() { LogUtils.logI("PresenceEngine.onRequestComplete()"); } @Override protected void onTimeoutEvent() { LogUtils.logI("PresenceEngine.onTimeoutEvent()"); switch (mState) { case UPDATE_PROCESSING_GOING_ON: updatePresenceDatabaseNextPage(); break; case IDLE: default: - if (mLoggedIn) { + if (isLoggedIn()) { if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setTimeout(CHECK_FREQUENCY); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); setTimeout(CHECK_FREQUENCY / 20); } } break; } } @Override protected void processCommsResponse(DecodedResponse resp) { handleServerResponse(resp.mDataTypes); } private void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg) { UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribedWithChat()) { uiAgent.sendUnsolicitedUiEvent(errorEvent, null); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users List of users that require updating. */ private synchronized void updatePresenceDatabase(List<User> users) { if (users == null || users.size() == 0) { LogUtils.logW("PresenceEngine.updatePresenceDatabase() users is NULL or zero size"); } else { if (mUsers == null) { mUsers = users; } else { // Doing an add one by one is not an efficient way but then // there is an issue in the addAll API. It crashes sometimes. // And the java code for the AddAll API seems to be erroneous. // More investigation is needed on this. for (User user : users) { mUsers.add(user); } } } mState = UPDATE_PROCESSING_GOING_ON; updatePresenceDatabaseNextPage(); } /** * This API makes the presence updates in pages of 10 with a timeout * after each page. The HandlerAgent is notified after every 10 pages. */ private synchronized void updatePresenceDatabaseNextPage(){ UiAgent uiAgent = mEventCallback.getUiAgent(); if(mUsers == null){ mState = IDLE; return; } int listSize = mUsers.size(); int start = 0; int end = UPDATE_PRESENCE_PAGE_SIZE; if(listSize == 0){ mState = IDLE; mUsers = null; return; } else if(listSize < end) { end = listSize; } List<User> userSubset = mUsers.subList(start, end); if ((userSubset != null)) { long idListeningTo = UiAgent.ALL_USERS; if (uiAgent != null) { idListeningTo = uiAgent.getLocalContactId(); } boolean updateUI = PresenceDbUtils.updateDatabase(userSubset, idListeningTo, mDbHelper); userSubset.clear(); // Send the update notification to UI for every UPDATE_PRESENCE_PAGE_SIZE*NOTIFY_AGENT_PAGE_INTERVAL updates. if (updateUI) { if (mUsers.size() == 0 || NOTIFY_AGENT_PAGE_INTERVAL == mIterations) { if (uiAgent != null) { uiAgent.updatePresence(idListeningTo); } mIterations = 0; } else { mIterations++; } } this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true, message.getNetworkId()); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ synchronized public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Method used to set availability of me profile when user logs in. * This is primarily used for reacting to login/connection state changes. */ private void initSetMyAvailabilityRequestAfterLogin() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } String meProfileUserId = Long.toString(PresenceDbUtils.getMeProfileUserId(mDbHelper)); Hashtable<String, String> availability = new Hashtable<String, String>(); ArrayList<Identity> identityList = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if ((identityList.size() != 0)) { for (int i=0; i<identityList.size(); i++) { Identity myIdentity = identityList.get(i); availability.put(myIdentity.mNetwork, OnlineStatus.ONLINE.toString()); } } User meUser = new User(meProfileUserId, availability); meUser.setLocalContactId(Long.valueOf(meProfileUserId)); updateMyPresenceInDatabase(meUser); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } // Get presences Hashtable<String, String> presenceList = getPresencesForStatus(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** * Changes the user's availability. * * @param status - Hashtable<String, String> of pairs <communityName, statusName>. */ public void setMyAvailability(Hashtable<String, String> presenceHash) { if (presenceHash == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceHash); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } /** * Changes the user's availability. * * @param network - SocialNetwork to set presence on. * @param status - OnlineStatus presence status to set. */ public void setMyAvailability(SocialNetwork network, OnlineStatus status) { LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+ network + "=" + status); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); final NetworkPresence newPresence = new NetworkPresence(userId, network.ordinal(), status.ordinal()); presenceList.add(newPresence); User me = new User(userId, null); me.setPayload(presenceList); MePresenceCacheTable.updateCache(newPresence, mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now Hashtable<String, String> presenceHash = new Hashtable<String, String>(); presenceHash.put(network.toString(), status.toString()); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } @Override public void onConnectionStateChanged(int state) { - if (mLoggedIn && isFirstTimeSyncComplete()) { + if (isLoggedIn() && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initializeAvailabilityFromDb(); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * Initializes or re-initializes availability from the Database. * If there are cached presences then these will be used * instead of values from the presence table. */ private void initializeAvailabilityFromDb() { final User user = getMyAvailabilityStatusFromDatabase(); ArrayList<NetworkPresence> cachedPresences = MePresenceCacheTable.getCache(mDbHelper.getReadableDatabase()); if(cachedPresences != null) { user.setPayload(cachedPresences); } initSetMyAvailabilityRequest(user); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if (identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); for (Identity identity : identities) { presences.put(identity.mNetwork, statusString); } return presences; } @Override public void onReset() { // reset the engine as if it was just created super.onReset(); mFirstRun = true; mLoggedIn = false; mIterations = 0; mState = IDLE; mUsers = null; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } + + private boolean isLoggedIn(){ + if (!mLoggedIn) { + mLoggedIn = EngineManager.getInstance().getLoginEngine().isLoggedIn(); + } + return mLoggedIn; + } } diff --git a/src/com/vodafone360/people/service/RemoteService.java b/src/com/vodafone360/people/service/RemoteService.java index 845b545..c9eb0b1 100644 --- a/src/com/vodafone360/people/service/RemoteService.java +++ b/src/com/vodafone360/people/service/RemoteService.java @@ -1,339 +1,338 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import java.security.InvalidParameterException; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import com.vodafone360.people.MainApplication; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.interfaces.IConnectionManagerInterface; import com.vodafone360.people.service.interfaces.IPeopleServiceImpl; import com.vodafone360.people.service.interfaces.IWorkerThreadControl; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.IWakeupListener; import com.vodafone360.people.service.utils.UserDataProtection; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * Implementation of People client's Service class. Loads properties from * SettingsManager. Creates NetworkAgent. Connects to ConnectionManager enabling * transport layer. Activates service's worker thread when required. */ public class RemoteService extends Service implements IWorkerThreadControl, IConnectionManagerInterface { /** * Intent received when service is started is tested against the value * stored in this key to determine if the service has been started because * of an alarm. */ public static final String ALARM_KEY = "alarm_key"; /** * Action for an Authenticator. * Straight copy from AccountManager.ACTION_AUTHENTICATOR_INTENT in 2.X platform */ public static final String ACTION_AUTHENTICATOR_INTENT = "android.accounts.AccountAuthenticator"; /** * Sync Adapter System intent action received on Bind. */ public static final String ACTION_SYNC_ADAPTER_INTENT = "android.content.SyncAdapter"; /** * Main reference to network agent * * @see NetworkAgent */ private NetworkAgent mNetworkAgent; /** * Worker thread reference * * @see WorkerThread */ private WorkerThread mWorkerThread; /** * The following object contains the implementation of the * {@link com.vodafone360.people.service.interfaces.IPeopleService} * interface. */ private IPeopleServiceImpl mIPeopleServiceImpl; /** * Used by comms when waking up the CPI at regular intervals and sending a * heartbeat is necessary */ private IWakeupListener mWakeListener; /** * true when the service has been fully initialised */ private boolean mIsStarted = false; /** * Stores the previous network connection state (true = connected) */ private boolean mIsConnected = true; private NativeAccountObjectsHolder mAccountsObjectsHolder = null; /** * Creation of RemoteService. Loads properties (i.e. supported features, * server URLs etc) from SettingsManager. Creates IPeopleServiceImpl, * NetworkAgent. Connects ConnectionManager creating Connection thread(s) * and DecoderThread 'Kicks' worker thread. */ @Override public void onCreate() { LogUtils.logV("RemoteService.onCreate()"); SettingsManager.loadProperties(this); mIPeopleServiceImpl = new IPeopleServiceImpl(this, this); mNetworkAgent = new NetworkAgent(this, this, this); // Create NativeContactsApi here to access Application Context NativeContactsApi.createInstance(getApplicationContext()); EngineManager.createEngineManager(this, mIPeopleServiceImpl); mNetworkAgent.onCreate(); mIPeopleServiceImpl.setNetworkAgent(mNetworkAgent); - ConnectionManager.getInstance().connect(this); /** The service has now been fully initialised. **/ mIsStarted = true; kickWorkerThread(); final MainApplication mainApp = (MainApplication)getApplication(); mainApp.setServiceInterface(mIPeopleServiceImpl); if(VersionUtils.is2XPlatform()) { mAccountsObjectsHolder = new NativeAccountObjectsHolder(((MainApplication)getApplication())); } final UserDataProtection userDataProtection = new UserDataProtection(this, mainApp.getDatabase()); userDataProtection.performStartupChecks(); } /** * Called on start of RemoteService. Check if we need to kick the worker * thread or 'wake' the TCP connection thread. */ @Override public void onStart(Intent intent, int startId) { if(intent == null) { LogUtils.logV("RemoteService.onStart() intent is null. Returning."); return; } final Bundle bundle = intent.getExtras(); LogUtils.logI("RemoteService.onStart() Intent action[" + intent.getAction() + "] data[" + bundle + "]"); if ((null == bundle) || (null == bundle.getString(ALARM_KEY))) { LogUtils.logV("RemoteService.onStart() mBundle is null. Returning."); return; } if (bundle.getString(ALARM_KEY).equals(WorkerThread.ALARM_WORKER_THREAD)) { LogUtils.logV("RemoteService.onStart() ALARM_WORKER_THREAD Alarm thrown"); kickWorkerThread(); } else if (bundle.getString(ALARM_KEY).equals(IWakeupListener.ALARM_HB_THREAD)) { LogUtils.logV("RemoteService.onStart() ALARM_HB_THREAD Alarm thrown"); if (null != mWakeListener) { mWakeListener.notifyOfWakeupAlarm(); } } } /** * Destroy RemoteService Close WorkerThread, destroy EngineManger and * NetworkAgent. */ @Override public void onDestroy() { LogUtils.logV("RemoteService.onDestroy()"); ((MainApplication)getApplication()).setServiceInterface(null); mIsStarted = false; synchronized (this) { if (mWorkerThread != null) { mWorkerThread.close(); } } EngineManager.destroyEngineManager(); // No longer need NativeContactsApi NativeContactsApi.destroyInstance(); mNetworkAgent.onDestroy(); } /** * Service binding is not used internally by this Application, but called * externally by the system when it needs an Authenticator or Sync * Adapter. This method will throw an InvalidParameterException if it is * not called with the expected intent (or called on a 1.x platform). */ @Override public IBinder onBind(Intent intent) { final String action = intent.getAction(); if (VersionUtils.is2XPlatform() && action != null) { if (action.equals(ACTION_AUTHENTICATOR_INTENT)) { return mAccountsObjectsHolder.getAuthenticatorBinder(); } else if (action.equals(ACTION_SYNC_ADAPTER_INTENT)) { return mAccountsObjectsHolder.getSyncAdapterBinder(); } } throw new InvalidParameterException("RemoteService.action() " + "There are no Binders for the given Intent"); } /*** * Ensures that the WorkerThread runs at least once. */ @Override public void kickWorkerThread() { synchronized (this) { if (!mIsStarted) { // Thread will be kicked anyway once we have finished // initialisation. return; } if (mWorkerThread == null || !mWorkerThread.wakeUp()) { LogUtils.logV("RemoteService.kickWorkerThread() Start thread"); mWorkerThread = new WorkerThread(mHandler); mWorkerThread.start(); } } } /*** * Handler for remotely calling the kickWorkerThread() method. */ private final Handler mHandler = new Handler() { /** * Process kick worker thread message */ @Override public void handleMessage(Message msg) { kickWorkerThread(); } }; /** * Called by NetworkAgent to notify whether device has become connected or * disconnected. The ConnectionManager connects or disconnects * appropriately. We kick the worker thread if our internal connection state * is changed. * * @param connected true if device has become connected, false if device is * disconnected. */ @Override public void signalConnectionManager(boolean connected) { // if service agent becomes connected start conn mgr thread LogUtils.logI("RemoteService.signalConnectionManager()" + "Signalling Connection Manager to " + (connected ? "connect." : "disconnect.")); if (connected) { ConnectionManager.getInstance().connect(this); } else {// SA is disconnected stop conn thread (and close connections?) ConnectionManager.getInstance().disconnect(); } // kick EngineManager to run() and apply CONNECTED/DISCONNECTED changes if (connected != mIsConnected) { if (mIPeopleServiceImpl != null) { mIPeopleServiceImpl.kickWorkerThread(); } } mIsConnected = connected; } /** * <p> * Registers a listener (e.g. the HeartbeatSender for TCP) that will be * notified whenever an intent for a new alarm is received. * </p> * <p> * This is desperately needed as the CPU of Android devices will halt when * the user turns off the screen and all CPU related activity is suspended * for that time. The wake up alarm is one simple way of achieving the CPU * to wake up and send out data (e.g. the heartbeat sender). * </p> */ public void registerCpuWakeupListener(IWakeupListener wakeListener) { mWakeListener = wakeListener; } /** * Return handle to {@link NetworkAgent} * * @return handle to {@link NetworkAgent} */ public NetworkAgent getNetworkAgent() { return mNetworkAgent; } /** * Set an Alarm with the AlarmManager to trigger the next update check. * * @param set Set or cancel the Alarm * @param realTime Time when the Alarm should be triggered */ public void setAlarm(boolean set, long realTime) { Intent mRemoteServiceIntent = new Intent(this, this.getClass()); mRemoteServiceIntent.putExtra(RemoteService.ALARM_KEY, IWakeupListener.ALARM_HB_THREAD); PendingIntent mAlarmSender = PendingIntent.getService(this, 0, mRemoteServiceIntent, 0); AlarmManager mAlarmManager = (AlarmManager)getSystemService(RemoteService.ALARM_SERVICE); if (set) { if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logV("WorkerThread.setAlarm() Check for the next update at [" + realTime + "] or in [" + (realTime - System.currentTimeMillis()) + "ms]"); } mAlarmManager.set(AlarmManager.RTC_WAKEUP, realTime, mAlarmSender); /* * mAlarmManager.set(AlarmManager.RTC, realTime, mAlarmSender); * TODO: Optimisation suggestion - Consider only doing work when the * device is already awake */ } else { mAlarmManager.cancel(mAlarmSender); } } } diff --git a/src/com/vodafone360/people/service/transport/ConnectionManager.java b/src/com/vodafone360/people/service/transport/ConnectionManager.java index 3c68c30..f0d6875 100644 --- a/src/com/vodafone360/people/service/transport/ConnectionManager.java +++ b/src/com/vodafone360/people/service/transport/ConnectionManager.java @@ -1,280 +1,278 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.transport; import java.util.ArrayList; import android.content.Context; import android.os.AsyncTask; import android.widget.Toast; -import com.vodafone360.people.R; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.transport.http.authentication.AuthenticationManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.service.transport.tcp.TcpConnectionThread; -import com.vodafone360.people.utils.LogUtils; /** * ConnectionManager - responsible for controlling the current connection * Connects and disconnects based on network availability etc and start or stops * RPG polling. Currently handles HTTP connections - this will be extended to * support TCP sockets. */ public class ConnectionManager implements ILoginEventsListener, IQueueListener { private static ConnectionManager mInstance; private IConnection mConnection; private RemoteService mService; private DecoderThread mDecoder; /** * ApplicationContext */ private Context mContext; /** * the class member variable to keep the connection state. * * @see ITcpConnectionListener */ private int mConnectionState; /** * the list of connection state change listeners, e.g. PresenceEngine. */ private ArrayList<ITcpConnectionListener> mListeners = new ArrayList<ITcpConnectionListener>(); public static synchronized ConnectionManager getInstance() { if (mInstance == null) { mInstance = new ConnectionManager(); } return mInstance; } /** * Shows a Toast ruinning on a UI Thread. There can be a crash if the * connectionmanager is called outside of an UI Thread and then treis to * show a toast. Using this approach with the AsyncTask Toasts will allways * be shown inside an UI Thread. * * @param messageResId */ private void showToast(int messageResId) { new AsyncTask<Integer, Void, Boolean>() { protected Boolean doInBackground(Integer... messageResId) { try { Toast toast = Toast.makeText(mContext, messageResId[0], Toast.LENGTH_LONG); toast.show(); } catch (Exception exc) { return false; } return true; } }.execute(messageResId); } private ConnectionManager() { EngineManager.getInstance().getLoginEngine().addListener(this); } public void connect(RemoteService service) { HttpConnectionThread.logI("ConnectionManager.connect()", "CONNECT CALLED BY NETWORKAGENT"); mService = service; mContext = mService.getApplicationContext(); // start decoder if (mDecoder == null) { mDecoder = new DecoderThread(); } if (!mDecoder.getIsRunning()) { mDecoder.startThread(); } boolean isCurrentlyLoggedIn = EngineManager.getInstance().getLoginEngine().isLoggedIn(); onLoginStateChanged(isCurrentlyLoggedIn); HttpConnectionThread.logI("ConnectionManager.connect()", (isCurrentlyLoggedIn) ? "We are logged in!" : "We are not logged in!"); } /** * Returns an autodetected connection. Where available, TCP will be used. * HTTP is used as a fallback alternative. * * @return Returns the correct implmentation of the connection. If TCP is * available it will be used preferably. Otherwise, HTTP is used as * a fallback. */ private IConnection getAutodetectedConnection(RemoteService service) { return new TcpConnectionThread(mDecoder, service); } public void disconnect() { HttpConnectionThread.logI("ConnectionManager.disconnect()", "DISCONNECT CALLED BY NETWORKAGENT"); if (null != mDecoder) { mDecoder.stopThread(); } stopActiveConnection(); } @Override public synchronized void onLoginStateChanged(boolean loggedIn) { HttpConnectionThread.logI("ConnectionManager.onLoginStateChanged()", "Is logged in: " + loggedIn); stopActiveConnection(); if (loggedIn) { mConnection = getAutodetectedConnection(mService); } else { mConnection = new AuthenticationManager(mDecoder); } QueueManager.getInstance().addQueueListener(mConnection); mConnection.startThread(); } /** * * Stops the connection if it was currently running. * */ private void stopActiveConnection() { if (null != mConnection) { synchronized (mConnection) { mConnection.stopThread(); mConnection = null; unsubscribeFromQueueEvents(); } } } @Override public synchronized void notifyOfItemInRequestQueue() { mConnection.notifyOfItemInRequestQueue(); } public void notifyOfUiActivity() { if (null != mConnection) { mConnection.notifyOfUiActivity(); } } private void unsubscribeFromQueueEvents() { QueueManager queue = QueueManager.getInstance(); queue.removeQueueListener(mConnection); queue.clearRequestTimeouts(); } /** * Note: only called from tests. */ public void free() { EngineManager.getInstance().getLoginEngine().removeListener(this); disconnect(); mConnection = null; mInstance = null; } /** * Enable test connection (for Unit testing purposes) * * @param testConn handle to test connection */ public void setTestConnection(IConnection testConn) { mConnection = testConn; QueueManager.getInstance().addQueueListener(mConnection); } /** * This method is called by the protocol to signal the connection state change. * * @param state The new connection state, @see ITcpConnectionListener. */ public void onConnectionStateChanged(int state) { HttpConnectionThread.logI("ConnectionManager.onConnectionStateChanged()", "State is " + state); if (state == ITcpConnectionListener.STATE_DISCONNECTED) { // TODO show toast only if activity in foreground // showToast(R.string.ContactProfile_no_connection); } mConnectionState = state; for (ITcpConnectionListener listener : mListeners) { listener.onConnectionStateChanged(state); } } /** * This method adds a listener for the connection state changes to the list, * if it is not there yet. * * @param listener ITcpConnectionListener - listener. */ public void addConnectionListener(ITcpConnectionListener listener) { if (!mListeners.contains(listener)) { mListeners.add(listener); } } /** * This method removes a listener from the connection state changes * listeners list. * * @param listener ITcpConnectionListener - listener. */ public void removeConnectionListener(ITcpConnectionListener listener) { mListeners.remove(listener); } /** * This method returns the current connection state of the application. * * @see ITcpConnectionListener * @return int - the connection state @see ITcpConnectionListener. */ public int getConnectionState() { return mConnectionState; } } diff --git a/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java b/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java index edc21b8..04e0375 100644 --- a/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java +++ b/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java @@ -1,657 +1,658 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.transport.tcp; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.util.ArrayList; import java.util.List; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.DecoderThread; import com.vodafone360.people.service.transport.IConnection; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.TimeOutWatcher; import com.vodafone360.people.service.utils.hessian.HessianUtils; import com.vodafone360.people.utils.LogUtils; public class TcpConnectionThread implements Runnable, IConnection { private final Object errorLock = new Object(); private final Object requestLock = new Object(); private static final String RPG_FALLBACK_TCP_URL = "rpg.vodafone360.com"; private static final int RPG_DEFAULT_TCP_PORT = 9900; private static final int TCP_DEFAULT_TIMEOUT = 120000; private static final int ERROR_RETRY_INTERVAL = 10000; /** * If we have a connection error we try to restart after 60 seconds earliest */ private static final int CONNECTION_RESTART_INTERVAL = 60000; /** * The maximum number of retries to reestablish a connection until we sleep * until the user uses the UI or * Settings.TCP_RETRY_BROKEN_CONNECTION_INTERVAL calls another retry. */ private static final int MAX_NUMBER_RETRIES = 3; private static final int FIRST_ATTEMPT = 1; private static final int BYTE_ARRAY_OUTPUT_STREAM_SIZE = 2048; // bytes private Thread mThread; private RemoteService mService; private DecoderThread mDecoder; private boolean mConnectionShouldBeRunning; private Boolean mFailedRetrying; private Boolean mIsRetrying; private BufferedInputStream mBufferedInputStream; private OutputStream mOs; private String mRpgTcpUrl; private int mRpgTcpPort; private Socket mSocket; private HeartbeatSenderThread mHeartbeatSender; private ResponseReaderThread mResponseReader; private long mLastErrorRetryTime; private ByteArrayOutputStream mBaos; public TcpConnectionThread(DecoderThread decoder, RemoteService service) { mSocket = new Socket(); mBaos = new ByteArrayOutputStream(BYTE_ARRAY_OUTPUT_STREAM_SIZE); - + mIsRetrying = new Boolean(false); mFailedRetrying = new Boolean(false); mConnectionShouldBeRunning = true; mDecoder = decoder; mService = service; mLastErrorRetryTime = System.currentTimeMillis(); try { mRpgTcpUrl = SettingsManager.getProperty(Settings.TCP_RPG_URL_KEY); mRpgTcpPort = Integer.parseInt(SettingsManager.getProperty(Settings.TCP_RPG_PORT_KEY)); } catch (Exception e) { HttpConnectionThread.logE("TcpConnectionThread()", "Could not parse URL or Port!", e); mRpgTcpUrl = RPG_FALLBACK_TCP_URL; mRpgTcpPort = RPG_DEFAULT_TCP_PORT; } } public void run() { + QueueManager queueManager = QueueManager.getInstance(); setFailedRetrying(false); setIsRetrying(false); try { // start the initial connection reconnectSocket(); HeartbeatSenderThread hbSender = new HeartbeatSenderThread(this, mService, mSocket); hbSender.setOutputStream(mOs); hbSender.sendHeartbeat(); hbSender = null; // TODO run this when BE supports it but keep HB in front! /* * ConnectionTester connTester = new ConnectionTester(mIs, mOs); if * (connTester.runTest()) { } else {} */ startHelperThreads(); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTED); } catch (IOException e) { haltAndRetryConnection(FIRST_ATTEMPT); } catch (Exception e) { haltAndRetryConnection(FIRST_ATTEMPT); } while (mConnectionShouldBeRunning) { try { if ((null != mOs) && (!getFailedRetrying())) { List<Request> reqs = QueueManager.getInstance().getRpgRequests(); int reqNum = reqs.size(); List<Integer> reqIdList = null; if (Settings.sEnableProtocolTrace || Settings.sEnableSuperExpensiveResponseFileLogging) { reqIdList = new ArrayList<Integer>(); } if (reqNum > 0) { mBaos.reset(); // batch payloads for (int i = 0; i < reqNum; i++) { Request req = reqs.get(i); if ((null == req) || (req.getAuthenticationType() == Request.USE_API)) { HttpConnectionThread.logV("TcpConnectionThread.run()", "Ignoring non-RPG method"); continue; } HttpConnectionThread.logD("TcpConnectionThread.run()", "Preparing [" + req.getRequestId() + "] for sending via RPG..."); req.setActive(true); req.writeToOutputStream(mBaos, true); if (req.isFireAndForget()) { // f-a-f, no response, // remove from queue HttpConnectionThread.logD("TcpConnectionThread.run()", "Removed F&F-Request: " + req.getRequestId()); queueManager.removeRequest(req.getRequestId()); } if (Settings.sEnableProtocolTrace) { reqIdList.add(req.getRequestId()); HttpConnectionThread.logD("HttpConnectionThread.run()", "Req ID: " + req.getRequestId() + " <-> Auth: " + req.getAuth()); } } mBaos.flush(); byte[] payload = mBaos.toByteArray(); if (null != payload) { // log file containing response to SD card if (Settings.sEnableSuperExpensiveResponseFileLogging) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < reqIdList.size(); i++) { sb.append(reqIdList.get(i)); sb.append("_"); } LogUtils.logE("XXXXXXYYYXXXXXX Do not Remove this!"); LogUtils.logToFile(payload, "people_" +( reqIdList.size()>0?reqIdList.get(0):0)+ "_" + System.currentTimeMillis() + "_req_" + ((int)payload[2]) // message // type + ".txt"); } // end log file containing response to SD card if (Settings.sEnableProtocolTrace) { Long userID = null; AuthSessionHolder auth = LoginEngine.getSession(); if (auth != null) { userID = auth.userID; } HttpConnectionThread.logI("TcpConnectionThread.run()", "\n > Sending request(s) " + reqIdList.toString() + ", for user ID " + userID + " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + HessianUtils.getInHessian( new ByteArrayInputStream(payload), true) + "\n "); } try { synchronized (mOs) { mOs.write(payload); mOs.flush(); } } catch (IOException ioe) { HttpConnectionThread.logE("TcpConnectionThread.run()", "Could not send request", ioe); notifyOfNetworkProblems(); } payload = null; } } } if (!getFailedRetrying()) { synchronized(requestLock) { requestLock.wait(); } } else { while (getFailedRetrying()) { // loop until a retry // succeeds HttpConnectionThread.logI("TcpConnectionThread.run()", "Wait() for next connection retry has started."); synchronized(errorLock) { errorLock.wait(Settings.TCP_RETRY_BROKEN_CONNECTION_INTERVAL); } if (mConnectionShouldBeRunning) { haltAndRetryConnection(FIRST_ATTEMPT); } } } } catch (Throwable t) { HttpConnectionThread.logE("TcpConnectionThread.run()", "Unknown Error: ", t); } } stopConnection(); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_DISCONNECTED); } /** * Attempts to reconnect the socket if it has been closed for some reason. * * @throws IOException Thrown if something goes wrong while reconnecting the * socket. */ private void reconnectSocket() throws IOException { HttpConnectionThread.logI("TcpConnectionThread.reconnectSocket()", "Reconnecting Socket on " + mRpgTcpUrl + ":" + mRpgTcpPort); mSocket = null; mSocket = new Socket(); mSocket.connect(new InetSocketAddress(mRpgTcpUrl, mRpgTcpPort), TCP_DEFAULT_TIMEOUT); mBufferedInputStream = new BufferedInputStream(mSocket.getInputStream()); mOs = mSocket.getOutputStream(); HttpConnectionThread.logI("TcpConnectionThread.reconnectSocket()", "Socket started: " + mRpgTcpUrl + ":" + mRpgTcpPort); } /** * * <p> * Retries to establish a network connection after a network error has * occurred or the coverage of the network was lost. The amount of retries * depends on MAX_NUMBER_RETRIES. This method is recursive! * * </p> * <p> * A new retry is carried out each time an exception is thrown until the * limit of retries has been reached. * </p> * * @param retryIteration Shows the number of iterations we have gone through thus far. * */ private void haltAndRetryConnection(int retryIteration) { if (retryIteration < MAX_NUMBER_RETRIES) { HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "\n \n \nRETRYING CONNECTION: " + retryIteration + " retries"); } ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTING); if (!mConnectionShouldBeRunning) { // connection was killed by network agent HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "Connection " + "was disconnected by Service Agent. Stopping retries!"); return; } stopConnection(); // stop to kill anything that might cause further IOEs // if we retried enough, we just return and end further retries if (retryIteration > MAX_NUMBER_RETRIES) { setFailedRetrying(true); invalidateRequests(); synchronized (requestLock) { // notify as we might be currently blocked on a request's wait() // this will cause us to go into the error lock requestLock.notify(); } synchronized (errorLock) { errorLock.notify(); } ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_DISCONNECTED); return; } try { // sleep a while to let the connection recover int sleepVal = (ERROR_RETRY_INTERVAL / 2) * retryIteration; Thread.sleep(sleepVal); } catch (InterruptedException ie) { } if (!mConnectionShouldBeRunning) { return; } try { reconnectSocket(); // TODO switch this block with the test connection block below // once the RPG implements this correctly. HeartbeatSenderThread hbSender = new HeartbeatSenderThread(this, mService, mSocket); hbSender.setOutputStream(mOs); hbSender.sendHeartbeat(); hbSender = null; setFailedRetrying(false); setIsRetrying(false); if (!mConnectionShouldBeRunning) { return; } startHelperThreads(); // restart our connections // TODO add this once the BE supports it! /* * ConnectionTester connTester = new ConnectionTester(mIs, mOs); * if (connTester.runTest()) { * mDidCriticalErrorOccur = false; * startHelperThreads(); // restart our connections Map<String, * } else { * haltAndRetryConnection(++numberOfRetries); } */ ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTED); } catch (IOException ioe) { HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "Failed sending heartbeat. Need to retry..."); haltAndRetryConnection(++retryIteration); } catch (Exception e) { HttpConnectionThread.logE("TcpConnectionThread.haltAndRetryConnection()", "An unknown error occured: ", e); haltAndRetryConnection(++retryIteration); } } /** * Invalidates all the requests so that the engines can either resend or * post an error message for the user. */ private void invalidateRequests() { QueueManager reqQueue = QueueManager.getInstance(); if (null != reqQueue) { TimeOutWatcher timeoutWatcher = reqQueue.getRequestTimeoutWatcher(); if (null != timeoutWatcher) { timeoutWatcher.invalidateAllRequests(); } } } @Override public void startThread() { if ((null != mThread) && (mThread.isAlive()) && (mConnectionShouldBeRunning)) { HttpConnectionThread.logI("TcpConnectionThread.startThread()", "No need to start Thread. " + "Already there. Returning"); return; } mConnectionShouldBeRunning = true; - mThread = new Thread(this); + mThread = new Thread(this, "TcpConnectionThread"); mThread.start(); } @Override public void stopThread() { HttpConnectionThread.logI("TcpConnectionThread.stopThread()", "Stop Thread was called!"); mConnectionShouldBeRunning = false; synchronized (requestLock) { requestLock.notify(); } synchronized (errorLock) { errorLock.notify(); } } /** * Starts the helper threads in order to be able to read responses and send * heartbeats and passes them the needed input and output streams. */ private void startHelperThreads() { HttpConnectionThread.logI("TcpConnectionThread.startHelperThreads()", "STARTING HELPER THREADS."); if (null == mHeartbeatSender) { mHeartbeatSender = new HeartbeatSenderThread(this, mService, mSocket); HeartbeatSenderThread.mCurrentThread = mHeartbeatSender; } else { HttpConnectionThread.logE("TcpConnectionThread.startHelperThreads()", "HeartbeatSenderThread was not null!", null); } if (null == mResponseReader) { mResponseReader = new ResponseReaderThread(this, mDecoder, mSocket); ResponseReaderThread.mCurrentThread = mResponseReader; } else { HttpConnectionThread.logE("TcpConnectionThread.startHelperThreads()", "ResponseReaderThread was not null!", null); } mHeartbeatSender.setOutputStream(mOs); mResponseReader.setInputStream(mBufferedInputStream); if (!mHeartbeatSender.getIsActive()) { mHeartbeatSender.startConnection(); mResponseReader.startConnection(); } } /** * Stops the helper threads and closes the input and output streams. As the * response reader is at this point in time probably in a blocking * read()-state an IOException will need to be caught. */ private void stopHelperThreads() { HttpConnectionThread.logI("TcpConnectionThread.stopHelperThreads()", "STOPPING HELPER THREADS: " + ((null != mHeartbeatSender) ? mHeartbeatSender.getIsActive() : false)); if (null != mResponseReader) { synchronized (mResponseReader) { mResponseReader.stopConnection(); mResponseReader = null; } } if (null != mHeartbeatSender) { synchronized (mHeartbeatSender) { mHeartbeatSender.stopConnection(); mHeartbeatSender = null; } } mOs = null; mBufferedInputStream = null; } /** * Stops the connection and its underlying socket implementation. Keeps the * thread running to allow further logins from the user. */ private synchronized void stopConnection() { HttpConnectionThread.logI("TcpConnectionThread.stopConnection()", "Closing socket..."); stopHelperThreads(); if (null != mSocket) { synchronized (mSocket) { try { mSocket.close(); } catch (IOException ioe) { HttpConnectionThread.logE("TcpConnectionThread.stopConnection()", "Could not close Socket!!!!!!!!!!! This should not happen. If this fails" + "the connection might get stuck as the read() in ResponseReader might never" + "get freed!", ioe); } finally { mSocket = null; } } } QueueManager.getInstance().clearAllRequests(); } @Override public void notifyOfItemInRequestQueue() { HttpConnectionThread.logV("TcpConnectionThread.notifyOfItemInRequestQueue()", "NEW REQUEST AVAILABLE!"); synchronized (requestLock) { requestLock.notify(); } synchronized (errorLock) { errorLock.notify(); } } /** * Gets notified whenever the user is using the UI. In this special case * whenever an error occured with the connection and this method was not * called a short time before */ @Override public void notifyOfUiActivity() { if (getFailedRetrying()) { if ((System.currentTimeMillis() - mLastErrorRetryTime) >= CONNECTION_RESTART_INTERVAL) { synchronized (errorLock) { // if we are in an error state let's try to fix it errorLock.notify(); } mLastErrorRetryTime = System.currentTimeMillis(); } } } @Override public void notifyOfRegainedNetworkCoverage() { synchronized (errorLock) { errorLock.notify(); } } /** * Called back by the response reader, which should notice network problems * first */ protected void notifyOfNetworkProblems() { if(getIsRetrying()) { return; } setIsRetrying(true); HttpConnectionThread.logE("TcpConnectionThread.notifyOfNetworkProblems()", "Houston, we have a network problem!", null); haltAndRetryConnection(FIRST_ATTEMPT); } @Override public boolean getIsConnected() { return mConnectionShouldBeRunning; } @Override public boolean getIsRpgConnectionActive() { if ((null != mHeartbeatSender) && (mHeartbeatSender.getIsActive())) { return true; } return false; } /** * * If the connection was lost this flag indicates that we are trying to regain it. * * @param isRetrying True if the connection is currently trying to be regained, false otherwise. * */ private void setIsRetrying(final boolean isRetrying) { synchronized(mIsRetrying) { mIsRetrying = isRetrying; } } /** * * Sets a flag which indicates whether the connection has failed retrying to connect to the server * for 3 consecutive times or not. * * @param failedRetrying True if the connection failed to connect 3 times, otherwise false. */ private void setFailedRetrying(final boolean failedRetrying) { synchronized(mFailedRetrying) { mFailedRetrying = failedRetrying; } } /** * * Returns whether we are currently trying to regain a connection. * * @return True if we are trying to regain the connection, false otherwise. * */ private boolean getIsRetrying() { synchronized(mIsRetrying) { return mIsRetrying; } } /** * * Returns whether we have failed trying to regain the connection (happens after 3 retries). * * @return True if we have failed reconnecting, false if we are connected. */ private boolean getFailedRetrying() { synchronized(mFailedRetrying) { return mFailedRetrying; } } @Override public void onLoginStateChanged(boolean isLoggedIn) { } }
360/360-Engine-for-Android
f6386d4040a5443c1c2f9ee136d69d04c4f36ed4
removed (unused) free() method from ConnectionManager, which contained questionable code according to findbugs
diff --git a/src/com/vodafone360/people/service/transport/ConnectionManager.java b/src/com/vodafone360/people/service/transport/ConnectionManager.java index 3c68c30..60b1bf5 100644 --- a/src/com/vodafone360/people/service/transport/ConnectionManager.java +++ b/src/com/vodafone360/people/service/transport/ConnectionManager.java @@ -1,280 +1,269 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.transport; import java.util.ArrayList; import android.content.Context; import android.os.AsyncTask; import android.widget.Toast; import com.vodafone360.people.R; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.transport.http.authentication.AuthenticationManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.service.transport.tcp.TcpConnectionThread; import com.vodafone360.people.utils.LogUtils; /** * ConnectionManager - responsible for controlling the current connection * Connects and disconnects based on network availability etc and start or stops * RPG polling. Currently handles HTTP connections - this will be extended to * support TCP sockets. */ public class ConnectionManager implements ILoginEventsListener, IQueueListener { private static ConnectionManager mInstance; private IConnection mConnection; private RemoteService mService; private DecoderThread mDecoder; /** * ApplicationContext */ private Context mContext; /** * the class member variable to keep the connection state. * * @see ITcpConnectionListener */ private int mConnectionState; /** * the list of connection state change listeners, e.g. PresenceEngine. */ private ArrayList<ITcpConnectionListener> mListeners = new ArrayList<ITcpConnectionListener>(); public static synchronized ConnectionManager getInstance() { if (mInstance == null) { mInstance = new ConnectionManager(); } return mInstance; } /** * Shows a Toast ruinning on a UI Thread. There can be a crash if the * connectionmanager is called outside of an UI Thread and then treis to * show a toast. Using this approach with the AsyncTask Toasts will allways * be shown inside an UI Thread. * * @param messageResId */ private void showToast(int messageResId) { new AsyncTask<Integer, Void, Boolean>() { protected Boolean doInBackground(Integer... messageResId) { try { Toast toast = Toast.makeText(mContext, messageResId[0], Toast.LENGTH_LONG); toast.show(); } catch (Exception exc) { return false; } return true; } }.execute(messageResId); } private ConnectionManager() { EngineManager.getInstance().getLoginEngine().addListener(this); } public void connect(RemoteService service) { HttpConnectionThread.logI("ConnectionManager.connect()", "CONNECT CALLED BY NETWORKAGENT"); mService = service; mContext = mService.getApplicationContext(); // start decoder if (mDecoder == null) { mDecoder = new DecoderThread(); } if (!mDecoder.getIsRunning()) { mDecoder.startThread(); } boolean isCurrentlyLoggedIn = EngineManager.getInstance().getLoginEngine().isLoggedIn(); onLoginStateChanged(isCurrentlyLoggedIn); HttpConnectionThread.logI("ConnectionManager.connect()", (isCurrentlyLoggedIn) ? "We are logged in!" : "We are not logged in!"); } /** * Returns an autodetected connection. Where available, TCP will be used. * HTTP is used as a fallback alternative. * * @return Returns the correct implmentation of the connection. If TCP is * available it will be used preferably. Otherwise, HTTP is used as * a fallback. */ private IConnection getAutodetectedConnection(RemoteService service) { return new TcpConnectionThread(mDecoder, service); } public void disconnect() { HttpConnectionThread.logI("ConnectionManager.disconnect()", "DISCONNECT CALLED BY NETWORKAGENT"); if (null != mDecoder) { mDecoder.stopThread(); } stopActiveConnection(); } @Override public synchronized void onLoginStateChanged(boolean loggedIn) { HttpConnectionThread.logI("ConnectionManager.onLoginStateChanged()", "Is logged in: " + loggedIn); stopActiveConnection(); if (loggedIn) { mConnection = getAutodetectedConnection(mService); } else { mConnection = new AuthenticationManager(mDecoder); } QueueManager.getInstance().addQueueListener(mConnection); mConnection.startThread(); } /** * * Stops the connection if it was currently running. * */ private void stopActiveConnection() { if (null != mConnection) { synchronized (mConnection) { mConnection.stopThread(); mConnection = null; unsubscribeFromQueueEvents(); } } } @Override public synchronized void notifyOfItemInRequestQueue() { mConnection.notifyOfItemInRequestQueue(); } public void notifyOfUiActivity() { if (null != mConnection) { mConnection.notifyOfUiActivity(); } } private void unsubscribeFromQueueEvents() { QueueManager queue = QueueManager.getInstance(); queue.removeQueueListener(mConnection); queue.clearRequestTimeouts(); } - /** - * Note: only called from tests. - */ - public void free() { - EngineManager.getInstance().getLoginEngine().removeListener(this); - - disconnect(); - mConnection = null; - mInstance = null; - } - /** * Enable test connection (for Unit testing purposes) * * @param testConn handle to test connection */ public void setTestConnection(IConnection testConn) { mConnection = testConn; QueueManager.getInstance().addQueueListener(mConnection); } /** * This method is called by the protocol to signal the connection state change. * * @param state The new connection state, @see ITcpConnectionListener. */ public void onConnectionStateChanged(int state) { HttpConnectionThread.logI("ConnectionManager.onConnectionStateChanged()", "State is " + state); if (state == ITcpConnectionListener.STATE_DISCONNECTED) { // TODO show toast only if activity in foreground // showToast(R.string.ContactProfile_no_connection); } mConnectionState = state; for (ITcpConnectionListener listener : mListeners) { listener.onConnectionStateChanged(state); } } /** * This method adds a listener for the connection state changes to the list, * if it is not there yet. * * @param listener ITcpConnectionListener - listener. */ public void addConnectionListener(ITcpConnectionListener listener) { if (!mListeners.contains(listener)) { mListeners.add(listener); } } /** * This method removes a listener from the connection state changes * listeners list. * * @param listener ITcpConnectionListener - listener. */ public void removeConnectionListener(ITcpConnectionListener listener) { mListeners.remove(listener); } /** * This method returns the current connection state of the application. * * @see ITcpConnectionListener * @return int - the connection state @see ITcpConnectionListener. */ public int getConnectionState() { return mConnectionState; } }
360/360-Engine-for-Android
d4f3d6433fa220d24f5fa5eb241ad4d168dca863
small change in presence info logging
diff --git a/src/com/vodafone360/people/ApplicationCache.java b/src/com/vodafone360/people/ApplicationCache.java index 43122a6..9abe7fd 100644 --- a/src/com/vodafone360/people/ApplicationCache.java +++ b/src/com/vodafone360/people/ApplicationCache.java @@ -1,775 +1,774 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import java.lang.ref.SoftReference; import java.security.InvalidParameterException; import java.util.ArrayList; import android.content.Context; import android.content.SharedPreferences; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.contactsync.SyncStatus; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.io.api.Auth; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.LoginPreferences; import com.vodafone360.people.utils.ThirdPartyAccount; /** * Caches information about the current state of the application. Stores most * recent activity and caches other information such as login details, so that * the application is returned to its most recent state when brought back to the * foreground or re-entered. The cached details can be cleared if required (as * part of 'Remove user data' for example). */ public class ApplicationCache { /** Text key for Terms of Service content. **/ private final static String TERMS_OF_SERVICE = "TERMS_OF_SERVICE"; /** Text key for Terms of Service last updated time. **/ private final static String TERMS_OF_SERVICE_TIME = "TERMS_OF_SERVICE_TIME"; /** Text key for Privacy content. **/ private final static String PRIVACY = "PRIVACY"; /** Text key for Privacy last updated time. **/ private final static String PRIVACY_TIME = "PRIVACY_TIME"; /** * Refresh any cached terms of service or privacy content after 10 minutes. */ private final static long REFRESH_TIME = 10 * 60 * 1000; private static final String TRUE = "true"; private static final String FALSE = "false"; /** * Login details are stored in the preferences file so that they can be used * to pre-populate the edit fields if the user is interrupted in the middle * of login/signup */ public static final String PREFS_FILE = "NOW_PLUS"; public static final String CONTACT_DATA = "ContactData"; public static final String CONTACT_SUMMARY = "ContactSummary"; public static final String CONTACT_ID = "CONTACTID"; public static final String CONTACT_NAME = "CONTACTNAME"; public static final String CONTACT_NUMBER = "CONTACTNUMBER"; public static final String CONTACT_NETWORK = "CONTACTNETWORK"; public static final String CONTACT_MODIFIED = "ContactModified"; public static final String STARTUP_LAUNCH_PATH_KEY = "LAUNCHED_FROM"; public static final String ADD_ACCOUNT_CLICKED = "ADD_ACCOUNT_CLICKED"; /*** * New String ID for Opening a chat from contextual menu, always opens the first connected (first in list) chat account. */ public static final String PREFERRED_ONLINE_SNS = "PREFERRED_ONLINE_SNS"; public static final int RESULT_DELETE = -100; public static final int CONTACT_PROFILE_VIEW = 0; public static final int CONTACT_PROFILE_EDIT = 1; public static final int CONTACT_PROFILE_ADD = 2; public static final int CONTACT_PROFILE_VIEW_ME = 3; public static final String THIRD_PARTY_ACCOUNT_NAME_KEY = "ThirdPartyAccountName"; public static final String THIRD_PARTY_ACCOUNT_NETWORK_KEY = "ThirdPartyNetworkName"; public static final String THIRD_PARTY_ACCOUNT_USERNAME_KEY = "ThirdPartyAccountUsername"; public static final String THIRD_PARTY_ACCOUNT_PASSWORD_KEY = "ThirdPartyAccountPassword"; public static final String THIRD_PARTY_ACCOUNT_CAPABILITIES = "ThirdPartyAccountCapabilities"; public static final String THIRD_PARTY_ACCOUNT_ERROR_CODE = "ThirdPartyAccountErrorCode"; private final static String FACEBOOK_SUBSCRIBED = "FacebookSubscribed"; private final static String HYVES_SUBSCRIBED = "HyvesSubscribed"; public final static String PREFS_NAME = "NowPlus_Prefs"; // Check settings public final static String PREFS_CHECK_FREQUENCY = "checkFrequency"; // Upgrade version - these values are deleted when the latest version is not // new public final static String PREFS_LAST_DIALOG_DATE = "lastDialogDate"; public final static String PREFS_LAST_CHECKED_DATE = "lastCheckedDate"; public final static String PREFS_UPGRADE_LATEST_VERSION = "upgradeLatestVersion"; public final static String PREFS_UPGRADE_URL = "upgradeUrl"; public final static String PREFS_UPGRADE_TEXT = "upgradeText"; /** * Text key to indicate if the intent from StartTabsActivity needs to be * retained. */ public final static String RETAIN_INTENT = "RetainIntent"; /** * Current state of the Activities engine fetching older time line logic. */ private static boolean sFetchingOlderTimeline = false; /** * Current state of the Activities engine updating statuses logic. */ private static boolean sUpdatingStatuses = false; /** * Current state of the Activities engine fetching newer time line logic. */ private static boolean sFetchingOlderStatuses = false; public static String sIsNewMessage = "isNewMessage"; private static String mPrivacyLanguage; private static String mTermsLanguage; // Frequency setting descriptions and defaults public final static long[] FREQUENCY_SETTING_LONG = { -1, // Off 7 * 24 * 60 * 60 * 1000, // Weekly 24 * 60 * 60 * 1000, // Daily 6 * 60 * 60 * 1000, // Every 6 hours 1 * 60 * 60 * 1000, // Hourly 10 * 60 * 1000 // Every 10 minutes }; /** In memory cache of the current contacts sync status. **/ private SyncStatus mSyncStatus = null; private boolean mScanThirdPartyAccounts = true; private boolean mAcceptedTermsAndConditions = false; private int mIdentityBeingProcessed = -1; private ArrayList<ThirdPartyAccount> mThirdPartyAccountsCache; private ContactSummary mMeProfileSummary; private Contact mCurrentContact; private ContactSummary mCurrentContactSummary; private ServiceStatus mServiceStatus = ServiceStatus.ERROR_UNKNOWN; /** * The constant for storing the "Add Account" button state (hidden or shown). */ public static final String JUST_LOGGED_IN = "first_time"; private TimelineSummaryItem mCurrentTimelineSummary; private long mCurrentContactFilter; /** Cached whether ThirdPartyAccountsActivity is opened. */ private boolean mIsAddAccountActivityOpened; /** * For storing the filter type in timeline status. */ private int mSelectedFilterType = 0; /** * For storing the filter type in timeline status of history details. */ private int mSelectedHistoryFilterType; /** * True if the menu "Sync Now" request is being processed. */ private static boolean sIsContactSyncBusy = false; /** * Setter for the selected filter */ public void setSelectedTimelineFilter(int filter) { mSelectedFilterType = filter; } /** * Getter for the selected filter */ public int getSelectedTimelineFilter() { return mSelectedFilterType; } /** * Setter for the selected filter */ public void setSelectedHistoryTimelineFilter(int filter) { mSelectedHistoryFilterType = filter; } /** * Getter for the selected filter */ public int getSelectedHistoryTimelineFilter() { return mSelectedHistoryFilterType; } /*** * GETTER Whether "add Account" activity is opened * * @return True if "add Account" activity is opened */ public boolean addAccountActivityOpened() { return mIsAddAccountActivityOpened; } /*** * SETTER Whether "add Account" activity is opened. * * @param flag if "add Account" activity is opened */ public void setAddAccountActivityOpened(final boolean flag) { mIsAddAccountActivityOpened = flag; } /** * Set whether application should re-scan 3rd party accounts. * * @param state true if application should re-scan 3rd party accounts. */ public void setScanThirdPartyAccounts(boolean state) { mScanThirdPartyAccounts = state; } /** * Return whether application should re-scan 3rd party accounts. * * @return true if application should re-scan 3rd party accounts. */ public boolean getScanThirdPartyAccounts() { return mScanThirdPartyAccounts; } /** * Set index of Identity currently being processed. * * @param index Index of Identity currently being processed. */ public void setIdentityBeingProcessed(int index) { mIdentityBeingProcessed = index; } /** * Return index of the Identity currently being processed. * * @return index of the Identity currently being processed. */ public int getIdentityBeingProcessed() { return mIdentityBeingProcessed; } /** * Set whether user has accepted the Terms and Conditions on sign-up. * * @param state true if user has accepted terms and conditions. */ public void setAcceptedTermsAndConditions(boolean state) { mAcceptedTermsAndConditions = state; } /** * Return whether user has accepted the Terms and Conditions on sign-up. * * @return true if user has accepted terms and conditions. */ public boolean getAcceptedTermsAndConditions() { return mAcceptedTermsAndConditions; } /** * Sets the language for the cached terms string. If the language of the * device changes, the cache becomes invalid * * @param privacyLanguage language of last fetched terms string */ public static void setTermsLanguage(String termsLanguage) { mTermsLanguage = termsLanguage; } /** * Sets the language for the cached privacy string. If the language of the * device changes, the cache becomes invalid * * @param privacyLanguage language of last fetched privacy string */ public static void setPrivacyLanguage(String privacyLanguage) { mPrivacyLanguage = privacyLanguage; } /** * Clear all cached data currently stored in People application. */ protected void clearCachedData(Context context) { LoginPreferences.clearPreferencesFile(context); LoginPreferences.clearCachedLoginDetails(); setBooleanValue(context, JUST_LOGGED_IN, true); setBooleanValue(context, ADD_ACCOUNT_CLICKED, false); mScanThirdPartyAccounts = true; mIdentityBeingProcessed = -1; mAcceptedTermsAndConditions = false; mMeProfileSummary = null; mCurrentContact = null; mCurrentContactSummary = null; mServiceStatus = ServiceStatus.ERROR_UNKNOWN; mThirdPartyAccountsCache = null; mSyncStatus = null; mIsAddAccountActivityOpened = false; sFetchingOlderTimeline = false; sUpdatingStatuses = false; sFetchingOlderStatuses = false; - Settings.LOG_PRESENCE_PUSH_ON_LOGCAT = false; } /** * Gets the ME profile object. * * @return The ME profile object. */ public ContactSummary getMeProfile() { return mMeProfileSummary; } /** * Sets the ME profile object. * * @param summary ContyactSummary for Me profile. */ public void setMeProfile(ContactSummary summary) { mMeProfileSummary = summary; } /** * Gets the contact currently being viewed in the UI. * * @return The currently view contact. */ public Contact getCurrentContact() { return mCurrentContact; } /** * Sets the contact currently being viewed in the UI. * * @param contact The currently viewed contact. */ public void setCurrentContact(Contact contact) { mCurrentContact = contact; } /** * Gets the summary information of the contact currently being viewed in the * UI. * * @return Contact summary information. */ public ContactSummary getCurrentContactSummary() { return mCurrentContactSummary; } /** * Sets the summary information of the contact currently being viewed in the * UI. * * @param contactSummary Contact summary information. */ public void setCurrentContactSummary(ContactSummary contactSummary) { mCurrentContactSummary = contactSummary; } /** * Return status of request issued to People service. * * @return status of request issued to People service. */ public ServiceStatus getServiceStatus() { return mServiceStatus; } /** * Set status of request issued to People service. * * @param status of request issued to People service. */ public void setServiceStatus(ServiceStatus status) { mServiceStatus = status; } /** * Cache list of 3rd party accounts (Identities) associated with current * login. * * @param list List of ThirdPartyAccount items retrieved from current login. */ public void storeThirdPartyAccounts(Context context, ArrayList<ThirdPartyAccount> list) { setValue(context, FACEBOOK_SUBSCRIBED, EngineManager.getInstance().getIdentityEngine().isFacebookInThirdPartyAccountList() + ""); setValue(context, HYVES_SUBSCRIBED, EngineManager.getInstance().getIdentityEngine().isHyvesInThirdPartyAccountList() + ""); mThirdPartyAccountsCache = list; } /** * Return cached list of 3rd party accounts (Identities) associated with * current login. * * @return List of ThirdPartyAccount items retrieved from current login. */ public ArrayList<ThirdPartyAccount> getThirdPartyAccounts() { return mThirdPartyAccountsCache; } /*** * Set a value in the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param value Preference value. */ private static void setValue(Context context, String key, String value) { SharedPreferences.Editor editor = context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(key, value); if (!editor.commit()) { throw new NullPointerException("MainApplication.setValue() Failed to set key[" + key + "] with value[" + value + "]"); } LogUtils.logV("ApplicationCache.setValue() key [" + key + "] value [" + value + "] saved to properties file"); } /*** * Gets the current sync state, or NULL if the state has not been set in * this JVM instance. * * Note: The sync state is an in memory condition. If this is not NULL * then the UI should be redirected to the SyncingYourAddressBookActivity. * * @return SyncStatus or NULL. */ public SyncStatus getSyncStatus() { return mSyncStatus; } /*** * Sets the current sync status. * * @param syncStatus New sync status. */ public void setSyncStatus(SyncStatus syncStatus) { mSyncStatus = syncStatus; } /*** * Get a value from the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param defaultValue Preference value. * @return */ private static String getValue(Context context, String key, String defaultValue) { return context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).getString(key, defaultValue); } /*** * Return the resource ID for the SNS Subscribed warning (e.g. * facebook/hyves/etc posting), or -1 if no warning is necessary. * * @param context Android context. * @return Resource ID for textView or -1 is warning is not required. * @throws InvalidParameterException when context is NULL. */ public static int getSnsSubscribedWarningId(Context context) { if (context == null) { throw new InvalidParameterException("ApplicationCache.getSnsSubscribedWarningId() " + "context cannot be NULL"); } boolean facebook = EngineManager.getInstance().getIdentityEngine().isFacebookInThirdPartyAccountList(); boolean hyves =EngineManager.getInstance().getIdentityEngine().isHyvesInThirdPartyAccountList(); if (facebook && hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves_and_facebook; } else if (facebook) { return R.string.ContactStatusListActivity_update_status_on_facebook; } else if (hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves; } else { return -1; } } public static boolean isBooleanValue(Context context, String key) { return TRUE.equals(getValue(context, key, FALSE)); } public static void setBooleanValue(Context context, String key, boolean value) { setValue(context, key, value ? TRUE : FALSE); } /** * Gets the summary information of the Timeline currently being viewed in the * UI. * * @return Timeline summary information. */ public TimelineSummaryItem getCurrentTimelineSummary() { return mCurrentTimelineSummary; } /** * Sets the summary information of the Timeline Item currently being viewed in the * UI. * * @param timelineSummary Timeline summary information. */ public void setCurrentTimelineSummary(TimelineSummaryItem timelineSummary) { mCurrentTimelineSummary = timelineSummary; } /*** * Set the Terms of Service content into the cache. * * @param value Terms of Service content. * @param context Android context. */ public static void setTermsOfService(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(TERMS_OF_SERVICE, value); editor.putLong(TERMS_OF_SERVICE_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setTermsOfService() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Set the Privacy content into the cache. * * @param value Privacy content. * @param context Android context. */ public static void setPrivacyStatemet(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(PRIVACY, value); editor.putLong(PRIVACY_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setPrivacyStatemet() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Get the Terms of Service content from the cache. Will return NULL if * there is no content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Terms of Service content */ public static String getTermsOfService(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(TERMS_OF_SERVICE_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME || !Auth.getLocalString().equals(mTermsLanguage)) { return null; } else { return sharedPreferences.getString(TERMS_OF_SERVICE, null); } } /*** * Get the Privacy content from the cache. Will return NULL if there is no * content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Privacy content */ public static String getPrivacyStatement(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(PRIVACY_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME || !Auth.getLocalString().equals(mPrivacyLanguage) ) { return null; } else { return sharedPreferences.getString(PRIVACY, null); } } private static ServiceStatus sStatus = ServiceStatus.SUCCESS; public static void setTermsStatus(final ServiceStatus status) { sStatus = status; } public static ServiceStatus getTermsStatus() { return sStatus; } /** * @param currentContactFilter the mCurrentContactFilter to set */ public final void setCurrentContactFilter(final long currentContactFilter) { mCurrentContactFilter = currentContactFilter; } /** * @return the mCurrentContactFilter */ public final long getCurrentContactFilter() { return mCurrentContactFilter; } /** Background thread for caching Thumbnails in memory. **/ private SoftReference<ThumbnailCache> mThumbnailCache; /*** * Get or create a background thread for caching Thumbnails in memory. * Note: This object can be used by multiple activities. */ public synchronized ThumbnailCache getThumbnailCache() { ThumbnailCache local = null; if (mThumbnailCache == null || mThumbnailCache.get() == null) { local = new ThumbnailCache(); mThumbnailCache =new SoftReference<ThumbnailCache>(local); } return mThumbnailCache.get(); } /*** * TRUE if the Activities engine is currently fetching older time line * data. * * @return TRUE if the Activities engine is currently fetching older time * line data. */ public static boolean isFetchingOlderTimeline() { return sFetchingOlderTimeline; } /*** * Set if the Activities engine is currently fetching older time line * data. * * @param fetchingOlderTimeline Specific current state. */ public static void setFetchingOlderTimeline( final boolean fetchingOlderTimeline) { sFetchingOlderTimeline = fetchingOlderTimeline; } /*** * TRUE if the Activities engine is currently updating status data. * * @return TRUE if the Activities engine is currently updating status data. */ public static boolean isUpdatingStatuses() { return sUpdatingStatuses; } /*** * Set if the Activities engine is currently updating status data. * * @param updatingStatuses Specific current state. */ public static void setUpdatingStatuses(final boolean updatingStatuses) { sUpdatingStatuses = updatingStatuses; } /*** * TRUE if the Activities engine is currently fetching older time line * statuses. * * @return TRUE if the Activities engine is currently fetching older time * line data. */ public static boolean isFetchingOlderStatuses() { return sFetchingOlderStatuses; } /*** * Set if the Activities engine is currently fetching older time line * statuses. * * @param fetchingOlderStatuses Specific current state. */ public static void setFetchingOlderStatuses( final boolean fetchingOlderStatuses) { sFetchingOlderStatuses = fetchingOlderStatuses; } /** * This method is used by menu "Sync Now" to check if the current BG sync * has finished to place a new BG sync request. * @return TRUE if the background sync is still on-going */ synchronized public static boolean isSyncBusy() { return sIsContactSyncBusy; } /** * This flag is set by ContactSyncEngine to indicate his state synchronizing the account. * @param isSyncBusy must be TRUE if state of ContactSync is State.IDLE, false otherwise. */ synchronized public static void setSyncBusy(boolean isSyncBusy) { ApplicationCache.sIsContactSyncBusy = isSyncBusy; } } diff --git a/src/com/vodafone360/people/service/io/api/Presence.java b/src/com/vodafone360/people/service/io/api/Presence.java index 57ad562..fdf1bd9 100644 --- a/src/com/vodafone360/people/service/io/api/Presence.java +++ b/src/com/vodafone360/people/service/io/api/Presence.java @@ -1,114 +1,87 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io.api; -import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import com.vodafone360.people.Settings; -import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine; -import com.vodafone360.people.engine.presence.NetworkPresence; -import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.utils.LogUtils; /** * Implementation of People server Presence APIs. */ public class Presence { private final static String EMPTY = ""; // TODO: What is the name of this // function? /** * Retrieve current presence list * * @param engineId ID for Presence engine. * @param recipientUserIdList List of user IDs. */ public static void getPresenceList(EngineId engineId, Map<String, List<String>> recipientUserIdList) { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.getPresenceList() No session, return"); return; } Request request = new Request(EMPTY, Request.Type.PRESENCE_LIST, engineId, false, Settings.API_REQUESTS_TIMEOUT_PRESENCE_LIST); if (recipientUserIdList != null) { // If not specified, then all presence information will be returned request.addData("tos", ApiUtils.createHashTable(recipientUserIdList)); } QueueManager.getInstance().addRequest(request); QueueManager.getInstance().fireQueueStateChanged(); } public static void setMyAvailability(Hashtable<String, String> status) { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.setAvailability() No session, so return"); return; } if (Settings.LOG_PRESENCE_PUSH_ON_LOGCAT) { LogUtils.logWithName(LogUtils.PRESENCE_INFO_TAG,"SET MY AVAILABILITY: " + status); } Request request = new Request(EMPTY, Request.Type.AVAILABILITY, EngineId.UNDEFINED, true, Settings.API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY); request.addData("availability", status); QueueManager.getInstance().addRequest(request); QueueManager.getInstance().fireQueueStateChanged(); } - - /** - * API to set my availability - * - * @param engineId ID of presence engine. - * @param onlinestatus Availability to set - */ - public static void setMyAvailability(String availability) { - if (LoginEngine.getSession() == null) { - LogUtils.logE("Presence.setMyAvailability() No session, so return"); - return; - } - Request request = new Request(EMPTY, Request.Type.AVAILABILITY, EngineId.UNDEFINED, true, - Settings.API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY); - - // Construct identities hash map with the appropriate availability - Hashtable<String, String> availabilityMap = new Hashtable<String, String>(); - //availabilityMap.put("mobile", availability); - // TODO: Get identities and add to map with availability set - request.addData("availability", availabilityMap); - - QueueManager.getInstance().addRequest(request); - QueueManager.getInstance().fireQueueStateChanged(); - } + }
360/360-Engine-for-Android
5fb57bc95eea05e139297bdd1e29a60d009462ba
change tag for logcat
diff --git a/src/com/vodafone360/people/utils/LogUtils.java b/src/com/vodafone360/people/utils/LogUtils.java index 2e03ce5..8a5ce63 100644 --- a/src/com/vodafone360/people/utils/LogUtils.java +++ b/src/com/vodafone360/people/utils/LogUtils.java @@ -1,306 +1,301 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import android.os.Environment; import android.util.Log; import com.vodafone360.people.Settings; /** * Logging utility functions: Allows logging to be enabled, Logs application * name and current thread name prepended to logged data. */ public final class LogUtils { /** Special tag postfix for LogCat to print presence infos. **/ public static final String PRESENCE_INFO_TAG = "PRESENCE_INFO"; /** Application tag prefix for LogCat. **/ private static final String APP_NAME_PREFIX = "People_"; /** Simple date format for Logging. **/ private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); /** SD Card filename. **/ private static final String APP_FILE_NAME = "/sdcard/people.log"; /** SD Card log file size limit (in bytes). **/ private static final int LOG_FILE_LIMIT = 100000; /** Maximum number of SD Card log files. **/ private static final int LOG_FILE_COUNT = 50; /** Stores the enabled state of the LogUtils function. **/ private static Boolean mEnabled = false; /** SD Card data logger. **/ private static Logger sLogger; /** SD Card data profile logger. **/ private static Logger sProfileLogger; /*** * Private constructor makes it impossible to create an instance of this * utility class. */ private LogUtils() { // Do nothing. } /** * Enable logging. */ public static void enableLogcat() { mEnabled = true; /** Enable the SD Card logger **/ sLogger = Logger.getLogger(APP_NAME_PREFIX); try { FileHandler fileHandler = new FileHandler(APP_FILE_NAME, LOG_FILE_LIMIT, LOG_FILE_COUNT); fileHandler.setFormatter(new Formatter() { @Override public String format(final LogRecord logRecord) { StringBuilder sb = new StringBuilder(); sb.append(DATE_FORMAT.format( new Date(logRecord.getMillis()))); sb.append(" "); sb.append(logRecord.getMessage()); sb.append("\n"); return sb.toString(); } }); sLogger.addHandler(fileHandler); } catch (IOException e) { logE("LogUtils.logToFile() IOException, data will not be logged " + "to file", e); sLogger = null; } if (Settings.ENABLED_PROFILE_ENGINES) { /** Enable the SD Card profiler **/ sProfileLogger = Logger.getLogger("profiler"); try { FileHandler fileHandler = new FileHandler("/sdcard/engineprofiler.log", LOG_FILE_LIMIT, LOG_FILE_COUNT); fileHandler.setFormatter(new Formatter() { @Override public String format(final LogRecord logRecord) { StringBuilder sb = new StringBuilder(); sb.append(DATE_FORMAT.format( new Date(logRecord.getMillis()))); sb.append("|"); sb.append(logRecord.getMessage()); sb.append("\n"); return sb.toString(); } }); sProfileLogger.addHandler(fileHandler); } catch (IOException e) { logE("LogUtils.logToFile() IOException, data will not be logged " + "to file", e); sProfileLogger = null; } } } /** * Write info log string. * * @param data String containing data to be logged. */ public static void logI(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.i(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write debug log string. * * @param data String containing data to be logged. */ public static void logD(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.d(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write warning log string. * * @param data String containing data to be logged. */ public static void logW(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.w(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write error log string. * * @param data String containing data to be logged. */ public static void logE(final String data) { // FlurryAgent.onError("Generic", data, "Unknown"); if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.e(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write verbose log string. * * @param data String containing data to be logged. */ public static void logV(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.v(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write info log string with specific component name. * This method should be only used from the code, that is run after being enabled * with a special TwelveKeyDialer cheat code combination. * * @param name String name string to prepend to log data. * @param data String containing data to be logged. */ public static void logWithName(final String name, final String data) { - Log.v(APP_NAME_PREFIX + name, data); + Log.v(name, data); } /** * Write error log string with Exception thrown. * * @param data String containing data to be logged. * @param exception Exception associated with error. */ public static void logE(final String data, final Throwable exception) { - // FlurryAgent.onError("Generic", data, + // FlurryAgent.onError("Generic", data,it // exception.getClass().toString()); if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.e(APP_NAME_PREFIX + currentThread.getName(), data, exception); } } /*** * Write a line to the SD Card log file (e.g. "Deleted contact name from * NAB because...."). * * @param data String containing data to be logged. */ public static void logToFile(final String data) { if (mEnabled && sLogger != null) { sLogger.log(new LogRecord(Level.INFO, data)); } } /*** * Write a line to the SD Card log file (e.g. "Deleted contact name from * NAB because...."). * * @param data String containing data to be logged. */ public static void profileToFile(final String data) { if (mEnabled && sProfileLogger != null) { sProfileLogger.log(new LogRecord(Level.INFO, data)); } } /** * * Writes a given byte-array to the SD card under the given file name. * * @param data The data to write to the SD card. * @param fileName The file name to write the data under. * */ public static void logToFile(final byte[] data, final String fileName) { if (Settings.sEnableSuperExpensiveResponseFileLogging) { FileOutputStream fos = null; try { File root = Environment.getExternalStorageDirectory(); - if (root.canWrite()) { + if (root.canWrite()){ File binaryFile = new File(root, fileName); fos = new FileOutputStream(binaryFile); fos.write(data); fos.flush(); - } else { - logE("LogUtils.logToFile() Could not write to SD card. Missing a permission? " + - "SC Card is currently "+ - Environment.getExternalStorageState()); } } catch (IOException e) { - logE("LogUtils.logToFile() Could not write " + fileName + - " to SD card! Exception: "+e); + logE("LogUtils.logToFile() Could not write " + fileName + " to SD card!"); } finally { if (null != fos) { try { fos.close(); } catch (IOException ioe) { logE("LogUtils.logToFile() Could not close file output stream!"); } } } } } /*** * Returns if the logging feature is currently enabled. * * @return TRUE if logging is enabled, FALSE otherwise. */ public static Boolean isEnabled() { return mEnabled; } } \ No newline at end of file
360/360-Engine-for-Android
2df3e05f0358870e628bd14c7521bcc7cdf77e39
LogCat presence
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 4935008..df23641 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -15,942 +15,942 @@ * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.identities; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import android.os.Bundle; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Identities; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.ThirdPartyAccount; /** * Engine responsible for handling retrieval and validation of Identities (e.g. * 3rd party/web accounts). The Identities engine can fetch a list of available * accounts, and set required capabilities and validate credentials for * specified accounts. */ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { /** * States for IdentitiesEngine. States are based on the requests that the * engine needs to handle. */ private enum State { IDLE, FETCHING_IDENTITIES, VALIDATING_IDENTITY_CREDENTIALS, SETTING_IDENTITY_STATUS, GETTING_MY_IDENTITIES, GETTING_MY_CHATABLE_IDENTITIES, DELETE_IDENTITY } /** * Mutex for thread synchronisation */ private final Object mMutex = new Object(); /** * Container class for Identity Capability Status request. Consists of a * network, identity id and a filter containing the required capabilities. */ private static class IdentityStatusRequest { private String mNetwork; private String mIdentityId; private String mIdentityStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setIdentityStatus(String status) { mIdentityStatus = status; } } /** * Container class encapsulating an Identity validation request containing: * dry-run flag, network, user-name, password, set of required capabilities. */ private static class IdentityValidateCredentialsRequest { /** Performs a dry run if true. */ private boolean mDryRun; /** Network to sign into. */ private String mNetwork; /** Username to sign into identity with. */ private String mUserName; /** Password to sign into identity with. */ private String mPassword; private Map<String, Boolean> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } /** * * Container class for Delete Identity request. Consist network and identity id. * */ private static class DeleteIdentityRequest { /** Network to delete.*/ private String mNetwork; /** IdentityID which needs to be Deleted.*/ private String mIdentityId; } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mMyIdentityList; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; /** * Maintaining DeleteIdentityRequest so that it can be later removed from * maintained cache. **/ private DeleteIdentityRequest identityToBeDeleted; /** * The hard coded list of capabilities we use to getAvailable~/MyIdentities(): chat and status. */ private final Map<String, List<String>> mCapabilitiesFilter; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; mMyIdentityList = new ArrayList<Identity>(); mAvailableIdentityList = new ArrayList<Identity>(); mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; // initialize identity capabilities filter mCapabilitiesFilter = new Hashtable<String, List<String>>(); final List<String> capabilities = new ArrayList<String>(); capabilities.add(IdentityCapability.CapabilityID.chat.name()); capabilities.add(IdentityCapability.CapabilityID.get_own_status.name()); mCapabilitiesFilter.put(Identities.CAPABILITY, capabilities); } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { final ArrayList<Identity> availableIdentityList; synchronized(mAvailableIdentityList) { // make a shallow copy availableIdentityList = new ArrayList<Identity>(mAvailableIdentityList); } if ((availableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return availableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { final ArrayList<Identity> myIdentityList; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } if ((myIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return myIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = getMyThirdPartyChattableIdentities(); // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chattableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chattableIdentities; } /** * * Takes all third party identities that have a chat capability set to true. * * @return A list of chattable 3rd party identities the user is signed in to. If the retrieval identities failed the returned list will be empty. * */ public ArrayList<Identity> getMyThirdPartyChattableIdentities() { final ArrayList<Identity> chattableIdentities = new ArrayList<Identity>(); final ArrayList<Identity> myIdentityList; final int identityListSize; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } identityListSize = myIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = myIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue)) { chattableIdentities.add(identity); break; } } } return chattableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, mCapabilitiesFilter); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, mCapabilitiesFilter); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * TODO: re-factor the method in the way that the UI doesn't pass the Bundle with capabilities * list to the Engine, but the Engine makes the list itself (UI/Engine separation). * * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Delete the given social network. * * @param network Name of the identity, * @param identityId Id of identity. */ public final void addUiDeleteIdentityRequest(final String network, final String identityId) { LogUtils.logD("IdentityEngine.addUiRemoveIdentity()"); DeleteIdentityRequest data = new DeleteIdentityRequest(); data.mNetwork = network; data.mIdentityId = identityId; /**maintaining the sent object*/ setIdentityToBeDeleted(data); addUiRequestToQueue(ServiceUiRequest.DELETE_IDENTITY, data); } /** * Setting the DeleteIdentityRequest object. * * @param data */ private void setIdentityToBeDeleted(final DeleteIdentityRequest data) { identityToBeDeleted = data; } /** * Return the DeleteIdentityRequest object. * */ private DeleteIdentityRequest getIdentityToBeDeleted() { return identityToBeDeleted; } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case GET_MY_IDENTITIES: sendGetMyIdentitiesRequest(); completeUiRequest(ServiceStatus.SUCCESS); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; case DELETE_IDENTITY: executeDeleteIdentityRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to delete the identity as specified . (Request is not issued if there * is currently no connectivity). * * @param data bundled request data containing network and identityId. */ private void executeDeleteIdentityRequest(final Object data) { if (!isConnected()) { completeUiRequest(ServiceStatus.ERROR_NO_INTERNET); } newState(State.DELETE_IDENTITY); DeleteIdentityRequest reqData = (DeleteIdentityRequest) data; if (!setReqId(Identities.deleteIdentity(this, reqData.mNetwork, reqData.mIdentityId))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(DecodedResponse resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if ((null == resp) || (null == resp.mDataTypes)) { - LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); + LogUtils.logE("Response objects or its contents were null. Aborting..."); return; } // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; case BaseDataType.IDENTITY_DELETION_DATA_TYPE: handleDeleteIdentity(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); } } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { Identity identity = (Identity)item; mMyIdentityList.add(identity); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); if (errorStatus == ServiceStatus.SUCCESS) { addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, null); } } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response of request to delete the identity. The response * should be a status that whether the operation is succeeded or not. The * response will be a status result otherwise ERROR_UNEXPECTED_RESPONSE if * the response is not as expected. * * @param data * List of BaseDataTypes generated from Server response. */ private void handleDeleteIdentity(final List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus( BaseDataType.IDENTITY_DELETION_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { for (BaseDataType item : data) { if (item.getType() == BaseDataType.IDENTITY_DELETION_DATA_TYPE) { synchronized(mMyIdentityList) { // iterating through the subscribed identities for (Identity identity : mMyIdentityList) { if (identity.mIdentityId .equals(getIdentityToBeDeleted().mIdentityId)) { mMyIdentityList.remove(identity); break; } } } completeUiRequest(ServiceStatus.SUCCESS); return; } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } } completeUiRequest(errorStatus, bu); } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; synchronized (mAvailableIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mAvailableIdentityList); } } else { requestKey = KEY_MY_IDS; synchronized (mMyIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mMyIdentityList); } } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ /** {@inheritDoc} */ @Override public final void onReset() { super.onReset(); mMyIdentityList.clear(); mAvailableIdentityList.clear(); mStatusList.clear(); mState = State.IDLE; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of Identity objects, can be NULL. * @return TRUE if the given Identity contains a Facebook account. */ public boolean isFacebookInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_FACEBOOK)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given Identity contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given Identity contains a Hyves account. */ public boolean isHyvesInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_HYVES)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Hyves not found in list"); return false; } } diff --git a/src/com/vodafone360/people/engine/presence/User.java b/src/com/vodafone360/people/engine/presence/User.java index 4f6bb71..393027e 100644 --- a/src/com/vodafone360/people/engine/presence/User.java +++ b/src/com/vodafone360/people/engine/presence/User.java @@ -1,364 +1,363 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; -import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import android.os.Parcel; import android.os.Parcelable; import com.vodafone360.people.Settings; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.utils.LogUtils; /** * User is a class encapsulating the information about a user's presence state. */ public class User implements Parcelable { private static final String COLUMNS = "::"; /** Database ID of the contact (e.g. "[email protected]"). **/ private long mLocalContactId; /** Overall presence state displayed in the common contact list. **/ private int mOverallOnline; /** * Communities presence status: * {google:online, pc:online, mobile:online}. */ private ArrayList<NetworkPresence> mPayload; /** * Default Constructor. */ public User() { } /** * Constructor. * * @param userId - user id in the contact list, e.g. * "google::[email protected]" or "882339" * @param payload - communities presence status {google:online, pc:online, * mobile:online} */ public User(String userId, Hashtable<String, String> payload) { if (payload != null) { if (Settings.LOG_PRESENCE_PUSH_ON_LOGCAT) { - LogUtils.logE("user id:"+ userId + ", " + payload); + LogUtils.logWithName(LogUtils.PRESENCE_INFO_TAG, "user id:"+ userId + ", " + payload); } mOverallOnline = isOverallOnline(payload); mPayload = createPayload(userId, payload); } } /** * This method returns the localContactId for this contact in DB across the * application . * * @return the localContactId for this contact in DB */ public long getLocalContactId() { return mLocalContactId; } public void setLocalContactId(long mLocalContactId) { this.mLocalContactId = mLocalContactId; } /** * Returns communities presence status * * @return communities presence status, e.g. {google:online, pc:online, * mobile:online} */ public ArrayList<NetworkPresence> getPayload() { return mPayload; } public OnlineStatus getStatusForNetwork(SocialNetwork network) { if (network == null) { return null; } OnlineStatus os = OnlineStatus.OFFLINE; if (mPayload != null) { if (network == SocialNetwork.VODAFONE) { int aggregated = 0; // aggregated state for "mobile" and "pc" for (NetworkPresence np : mPayload) { if (np.getNetworkId() == SocialNetwork.MOBILE.ordinal() || (np.getNetworkId() == SocialNetwork.PC.ordinal())) { if (aggregated < np.getOnlineStatusId()) { aggregated += np.getOnlineStatusId(); } } } os = OnlineStatus.getValue(aggregated); } else { for (NetworkPresence np : mPayload) { if (np.getNetworkId() == network.ordinal()) { os = OnlineStatus.getValue(np.getOnlineStatusId()); break; } } } } return os; } /** * Returns communities presence status * * @return communities presence status, e.g. {google:online, pc:online, * mobile:online} */ public void setPayload(ArrayList<NetworkPresence> payload) { mPayload = payload; } /** * Returns the overall user presence status * * @return true if user is online at least at one community, e.g. true if * {google:offline, pc:offline, mobile:online} */ private int isOverallOnline(Hashtable<String, String> payload) { if (payload != null) { if (payload.values().contains(ContactSummary.OnlineStatus.ONLINE.toString())) return ContactSummary.OnlineStatus.ONLINE.ordinal(); if (payload.values().contains(ContactSummary.OnlineStatus.INVISIBLE.toString())) return ContactSummary.OnlineStatus.INVISIBLE.ordinal(); if (payload.values().contains(ContactSummary.OnlineStatus.IDLE.toString())) return ContactSummary.OnlineStatus.IDLE.ordinal(); } return ContactSummary.OnlineStatus.OFFLINE.ordinal(); } /** * Returns the overall user presence status: in fact the one from the below * status states first encountered for all known user accounts next: * INVISIBLE, ONLINE, IDLE, OFFLINE * * @return presence state */ public int isOnline() { return mOverallOnline; } /** * @param payload * @return */ private ArrayList<NetworkPresence> createPayload(String userId, Hashtable<String, String> payload) { ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(payload.size()); String parsedUserId = parseUserName(userId); String key = null; SocialNetwork network = null; String value = null; OnlineStatus status = null; for (Enumeration<String> en = payload.keys(); en.hasMoreElements();) { key = en.nextElement(); network = SocialNetwork.getValue(key); if (network != null) { int keyIdx = network.ordinal(); value = payload.get(key); if (value != null) { status = OnlineStatus.getValue(value); if (status != null) { int valueIdx = status.ordinal(); presenceList.add(new NetworkPresence(parsedUserId, keyIdx, valueIdx)); } } } } return presenceList; } /** * @param user * @return */ private static String parseUserName(String userId) { if (userId != null) { int columnsIndex = userId.indexOf(COLUMNS); if (columnsIndex > -1) { return userId.substring(columnsIndex + COLUMNS.length()); } else { return userId; } } return null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mOverallOnline; result = prime * result + ((mPayload == null) ? 0 : mPayload.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User)obj; if (mOverallOnline != other.mOverallOnline) return false; if (mPayload == null) { if (other.mPayload != null) return false; } else if (!mPayload.equals(other.mPayload)) return false; return true; } @Override public String toString() { final StringBuffer sb = new StringBuffer("User [mLocalContactId="); sb.append(mLocalContactId); sb.append(", mOverallOnline="); sb.append(mOverallOnline); sb.append(", mPayload="); sb.append(mPayload); sb.append("]"); return sb.toString(); } /** * This method sets the overall user presence status, * @parameter the online status id - the ordinal, see @OnlineStatus */ public void setOverallOnline(int overallOnline) { this.mOverallOnline = overallOnline; } /** * This method removes the network presence information with the given presence id from the User. * @param ordinal - the network id, ordinal in @see SocialNetworks */ public void removeNetwork(int ordinal) { Iterator<NetworkPresence> itr = mPayload.iterator(); NetworkPresence presence = null; while (itr.hasNext()) { presence = itr.next(); if (presence.getNetworkId() == ordinal) { itr.remove(); break; } } } @Override public final int describeContents() { return 0; } @Override public final void writeToParcel(final Parcel dest, final int flags) { dest.writeLong(mLocalContactId); dest.writeInt(mOverallOnline); writePayloadToParcel(dest, flags); } /*** * Parcelable constructor for User. * * @param source User Parcel. */ private void readFromParcel(final Parcel source) { mLocalContactId = source.readLong(); mOverallOnline = source.readInt(); readPayloadFromParcel(source); } /** * Helper function to get the payload into & out of a parcel. * Keeping this code in a helper function should help maintenance. * Doing it this way seems to be the only way to avoid constant * ClassNotFoundExceptions even with proper classloaders in place. * * @param dest User Parcel. * @param flags Flags. */ public final void writePayloadToParcel(final Parcel dest, final int flags) { // Locals more efficient than members on Dalvik VM ArrayList<NetworkPresence> payload = mPayload; dest.writeInt(payload.size()); for (NetworkPresence netPres : payload) { netPres.writeToParcel(dest, flags); } } /** * Helper function to get the payload into & out of a parcel. * Keeping this code in a helper function should help maintenance. * Doing it this way seems to be the only way to avoid constant * ClassNotFoundExceptions even with proper classloaders in place. * * @param source User Parcel. */ private void readPayloadFromParcel(final Parcel source) { // Could do this directly into mPayload but locals are more efficient ArrayList<NetworkPresence> payload = new ArrayList<NetworkPresence>(); for (int i = 0; i < source.readInt(); i++) { payload.add(new NetworkPresence(source)); } mPayload = payload; } /*** * Parcelable.Creator for User. */ public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { @Override public User createFromParcel(final Parcel source) { User newUser = new User(); newUser.readFromParcel(source); return newUser; } @Override public User[] newArray(final int size) { return new User[size]; } }; } diff --git a/src/com/vodafone360/people/service/io/api/Presence.java b/src/com/vodafone360/people/service/io/api/Presence.java index 29dcd3e..57ad562 100644 --- a/src/com/vodafone360/people/service/io/api/Presence.java +++ b/src/com/vodafone360/people/service/io/api/Presence.java @@ -1,114 +1,114 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io.api; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import com.vodafone360.people.Settings; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.engine.presence.NetworkPresence; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.utils.LogUtils; /** * Implementation of People server Presence APIs. */ public class Presence { private final static String EMPTY = ""; // TODO: What is the name of this // function? /** * Retrieve current presence list * * @param engineId ID for Presence engine. * @param recipientUserIdList List of user IDs. */ public static void getPresenceList(EngineId engineId, Map<String, List<String>> recipientUserIdList) { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.getPresenceList() No session, return"); return; } Request request = new Request(EMPTY, Request.Type.PRESENCE_LIST, engineId, false, Settings.API_REQUESTS_TIMEOUT_PRESENCE_LIST); if (recipientUserIdList != null) { // If not specified, then all presence information will be returned request.addData("tos", ApiUtils.createHashTable(recipientUserIdList)); } QueueManager.getInstance().addRequest(request); QueueManager.getInstance().fireQueueStateChanged(); } public static void setMyAvailability(Hashtable<String, String> status) { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.setAvailability() No session, so return"); return; } if (Settings.LOG_PRESENCE_PUSH_ON_LOGCAT) { - LogUtils.logE("SET MY AVAILABILITY: " + status); + LogUtils.logWithName(LogUtils.PRESENCE_INFO_TAG,"SET MY AVAILABILITY: " + status); } Request request = new Request(EMPTY, Request.Type.AVAILABILITY, EngineId.UNDEFINED, true, Settings.API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY); request.addData("availability", status); QueueManager.getInstance().addRequest(request); QueueManager.getInstance().fireQueueStateChanged(); } /** * API to set my availability * * @param engineId ID of presence engine. * @param onlinestatus Availability to set */ public static void setMyAvailability(String availability) { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.setMyAvailability() No session, so return"); return; } Request request = new Request(EMPTY, Request.Type.AVAILABILITY, EngineId.UNDEFINED, true, Settings.API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY); // Construct identities hash map with the appropriate availability Hashtable<String, String> availabilityMap = new Hashtable<String, String>(); //availabilityMap.put("mobile", availability); // TODO: Get identities and add to map with availability set request.addData("availability", availabilityMap); QueueManager.getInstance().addRequest(request); QueueManager.getInstance().fireQueueStateChanged(); } } diff --git a/src/com/vodafone360/people/utils/LogUtils.java b/src/com/vodafone360/people/utils/LogUtils.java index ee9e34e..2e03ce5 100644 --- a/src/com/vodafone360/people/utils/LogUtils.java +++ b/src/com/vodafone360/people/utils/LogUtils.java @@ -1,302 +1,306 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import android.os.Environment; import android.util.Log; import com.vodafone360.people.Settings; /** * Logging utility functions: Allows logging to be enabled, Logs application * name and current thread name prepended to logged data. */ public final class LogUtils { + + /** Special tag postfix for LogCat to print presence infos. **/ + public static final String PRESENCE_INFO_TAG = "PRESENCE_INFO"; + /** Application tag prefix for LogCat. **/ private static final String APP_NAME_PREFIX = "People_"; /** Simple date format for Logging. **/ private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); /** SD Card filename. **/ private static final String APP_FILE_NAME = "/sdcard/people.log"; /** SD Card log file size limit (in bytes). **/ private static final int LOG_FILE_LIMIT = 100000; /** Maximum number of SD Card log files. **/ private static final int LOG_FILE_COUNT = 50; /** Stores the enabled state of the LogUtils function. **/ private static Boolean mEnabled = false; /** SD Card data logger. **/ private static Logger sLogger; /** SD Card data profile logger. **/ private static Logger sProfileLogger; /*** * Private constructor makes it impossible to create an instance of this * utility class. */ private LogUtils() { // Do nothing. } /** * Enable logging. */ public static void enableLogcat() { mEnabled = true; /** Enable the SD Card logger **/ sLogger = Logger.getLogger(APP_NAME_PREFIX); try { FileHandler fileHandler = new FileHandler(APP_FILE_NAME, LOG_FILE_LIMIT, LOG_FILE_COUNT); fileHandler.setFormatter(new Formatter() { @Override public String format(final LogRecord logRecord) { StringBuilder sb = new StringBuilder(); sb.append(DATE_FORMAT.format( new Date(logRecord.getMillis()))); sb.append(" "); sb.append(logRecord.getMessage()); sb.append("\n"); return sb.toString(); } }); sLogger.addHandler(fileHandler); } catch (IOException e) { logE("LogUtils.logToFile() IOException, data will not be logged " + "to file", e); sLogger = null; } if (Settings.ENABLED_PROFILE_ENGINES) { /** Enable the SD Card profiler **/ sProfileLogger = Logger.getLogger("profiler"); try { FileHandler fileHandler = new FileHandler("/sdcard/engineprofiler.log", LOG_FILE_LIMIT, LOG_FILE_COUNT); fileHandler.setFormatter(new Formatter() { @Override public String format(final LogRecord logRecord) { StringBuilder sb = new StringBuilder(); sb.append(DATE_FORMAT.format( new Date(logRecord.getMillis()))); sb.append("|"); sb.append(logRecord.getMessage()); sb.append("\n"); return sb.toString(); } }); sProfileLogger.addHandler(fileHandler); } catch (IOException e) { logE("LogUtils.logToFile() IOException, data will not be logged " + "to file", e); sProfileLogger = null; } } } /** * Write info log string. * * @param data String containing data to be logged. */ public static void logI(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.i(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write debug log string. * * @param data String containing data to be logged. */ public static void logD(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.d(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write warning log string. * * @param data String containing data to be logged. */ public static void logW(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.w(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write error log string. * * @param data String containing data to be logged. */ public static void logE(final String data) { // FlurryAgent.onError("Generic", data, "Unknown"); if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.e(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write verbose log string. * * @param data String containing data to be logged. */ public static void logV(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.v(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write info log string with specific component name. - * + * This method should be only used from the code, that is run after being enabled + * with a special TwelveKeyDialer cheat code combination. + * * @param name String name string to prepend to log data. * @param data String containing data to be logged. */ public static void logWithName(final String name, final String data) { - if (mEnabled) { - Log.v(APP_NAME_PREFIX + name, data); - } + Log.v(APP_NAME_PREFIX + name, data); } /** * Write error log string with Exception thrown. * * @param data String containing data to be logged. * @param exception Exception associated with error. */ public static void logE(final String data, final Throwable exception) { // FlurryAgent.onError("Generic", data, // exception.getClass().toString()); if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.e(APP_NAME_PREFIX + currentThread.getName(), data, exception); } } /*** * Write a line to the SD Card log file (e.g. "Deleted contact name from * NAB because...."). * * @param data String containing data to be logged. */ public static void logToFile(final String data) { if (mEnabled && sLogger != null) { sLogger.log(new LogRecord(Level.INFO, data)); } } /*** * Write a line to the SD Card log file (e.g. "Deleted contact name from * NAB because...."). * * @param data String containing data to be logged. */ public static void profileToFile(final String data) { if (mEnabled && sProfileLogger != null) { sProfileLogger.log(new LogRecord(Level.INFO, data)); } } /** * * Writes a given byte-array to the SD card under the given file name. * * @param data The data to write to the SD card. * @param fileName The file name to write the data under. * */ public static void logToFile(final byte[] data, final String fileName) { if (Settings.sEnableSuperExpensiveResponseFileLogging) { FileOutputStream fos = null; try { File root = Environment.getExternalStorageDirectory(); if (root.canWrite()) { File binaryFile = new File(root, fileName); fos = new FileOutputStream(binaryFile); fos.write(data); fos.flush(); } else { logE("LogUtils.logToFile() Could not write to SD card. Missing a permission? " + "SC Card is currently "+ Environment.getExternalStorageState()); } } catch (IOException e) { logE("LogUtils.logToFile() Could not write " + fileName + " to SD card! Exception: "+e); } finally { if (null != fos) { try { fos.close(); } catch (IOException ioe) { logE("LogUtils.logToFile() Could not close file output stream!"); } } } } } /*** * Returns if the logging feature is currently enabled. * * @return TRUE if logging is enabled, FALSE otherwise. */ public static Boolean isEnabled() { return mEnabled; } } \ No newline at end of file
360/360-Engine-for-Android
8536dd41854cc51ad9adc1c0a01312c7f97922be
PAND-2375: Fixed user session depending on Simcard presence.
diff --git a/src/com/vodafone360/people/engine/login/LoginEngine.java b/src/com/vodafone360/people/engine/login/LoginEngine.java index 0009b01..744d9be 100644 --- a/src/com/vodafone360/people/engine/login/LoginEngine.java +++ b/src/com/vodafone360/people/engine/login/LoginEngine.java @@ -1,1427 +1,1412 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.login; import java.util.ArrayList; import java.util.List; import org.bouncycastle.crypto.InvalidCipherTextException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; -import android.telephony.TelephonyManager; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.Intents; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.StateTable; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.PublicKeyDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.datatypes.SimpleText; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.agent.NetworkAgent.AgentState; import com.vodafone360.people.service.io.ResponseQueue; import com.vodafone360.people.service.io.api.Auth; import com.vodafone360.people.service.receivers.SmsBroadcastReceiver; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.LoginPreferences; +import com.vodafone360.people.utils.SimCard; /** * Engine handling sign in to existing accounts and sign up to new accounts. */ public class LoginEngine extends BaseEngine { /** * List of states for LoginEngine. */ private enum State { NOT_INITIALISED, NOT_REGISTERED, LOGGED_ON, LOGGED_OFF, LOGGED_OFF_WAITING_FOR_RETRY, LOGGED_OFF_WAITING_FOR_NETWORK, LOGIN_FAILED, LOGIN_FAILED_WRONG_CREDENTIALS, SIGNING_UP, FETCHING_TERMS_OF_SERVICE, FETCHING_PRIVACY_STATEMENT, FETCHING_USERNAME_STATE, REQUESTING_ACTIVATION_CODE, CREATING_SESSION_MANUAL, ACTIVATING_ACCOUNT, CREATING_SESSION_AUTO, RETRIEVING_PUBLIC_KEY } /** * Text coming from the server contains these carriage return characters, * which need to be exchanged with space characters to improve layout. */ private static final char CARRIAGE_RETURN_CHARACTER = (char) 13; /** * Text coming from the server contains carriage return characters, which * need to be exchanged with these space characters to improve layout. */ private static final char SPACE_CHARACTER = (char) 32; /** * used for sending unsolicited ui events */ private final UiAgent mUiAgent = mEventCallback.getUiAgent(); /** * mutex for thread synchronization */ private final Object mMutex = new Object(); /** * To convert between seconds and milliseconds */ private static final int MS_IN_SECONDS = 1000; /** * Current state of the engine */ private State mState = State.NOT_INITIALISED; /** * Context used for listening to SMS events */ private Context mContext; /** * Database used for fetching/storing state information */ private DatabaseHelper mDb; - /** - * Subscriber ID fetched from SIM card - */ - private String mCurrentSubscriberId; - - /** - * Android telephony manager used for fetching subscriber ID - */ - private TelephonyManager mTelephonyManager; - /** * Contains the authenticated session information while the user is logged * in */ private static AuthSessionHolder sActivatedSession = null; /** * Contains user login details such as user name and password */ private final LoginDetails mLoginDetails = new LoginDetails(); /** * Contains a public key for encrypting login details to be sent to the * server */ private PublicKeyDetails mPublicKey = new PublicKeyDetails(); /** * Contains user registration details such as name, username, password, etc. */ private RegistrationDetails mRegistrationDetails = new RegistrationDetails(); /** * Determines if current login information from database can be used to * establish a session. Set to false if login fails repeatedly. */ private boolean mAreLoginDetailsValid = true; /** * Timeout used when waiting for the server to sent an activation SMS. If * this time in milliseconds is exceeded, the login will fail with SMS not * received error. */ private static final long ACTIVATE_LOGIN_TIMEOUT = 72000; /** * Holds the activation code once an activation SMS has been received. */ private String mActivationCode = null; /** * Set to true when sign in or sign up has been completed by the user. When * this is false the landing page will be displayed when the application is * launched. */ private boolean mIsRegistrationComplete = false; /** * Contains a list of login engine observers which will be notified when the * login engine changes state. */ private final ArrayList<ILoginEventsListener> mEventsListener = new ArrayList<ILoginEventsListener>(); /** * Determines if the user is currently logged in with a valid session */ private boolean mCurrentLoginState = false; /** * Listener interface that can be used by clients to receive login state * events from the engine. */ public static interface ILoginEventsListener { void onLoginStateChanged(boolean loggedIn); } /** * Public constructor. * * @param context The service Context * @param eventCallback Provides access to useful engine manager * functionality * @param db The Now+ database used for fetching/storing login state * information */ public LoginEngine(Context context, IEngineEventCallback eventCallback, DatabaseHelper db) { super(eventCallback); LogUtils.logD("LoginEngine.LoginEngine()"); mContext = context; - mTelephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); mDb = db; mEngineId = EngineId.LOGIN_ENGINE; } /** * This will be called immediately after creation to perform extra * initialisation. */ @Override public void onCreate() { LogUtils.logD("LoginEngine.OnCreate()"); mState = State.NOT_INITIALISED; - mCurrentSubscriberId = mTelephonyManager.getSubscriberId(); IntentFilter filter = new IntentFilter(SmsBroadcastReceiver.ACTION_ACTIVATION_CODE); mContext.registerReceiver(mEventReceiver, filter); mIsRegistrationComplete = StateTable.isRegistrationComplete(mDb.getReadableDatabase()); + initializeEngine(); } /** * This will be called just before the engine is shutdown. Cleans up any * resources used. */ @Override public void onDestroy() { LogUtils.logD("LoginEngine.onDestroy()"); // Intent intent = new Intent(); // intent.setAction(Intents.HIDE_LOGIN_NOTIFICATION); // mContext.sendBroadcast(intent); removeAllListeners(); mContext.unregisterReceiver(mEventReceiver); } /** * Called by the INowPlusService implementation to start a manual login. * Adds a manual login UI request to the queue and kicks the worker thread. * * @param loginDetails The login information entered by the user */ public void addUiLoginRequest(LoginDetails loginDetails) { LogUtils.logD("LoginEngine.addUiLoginRequest()"); addUiRequestToQueue(ServiceUiRequest.LOGIN, loginDetails); } /** * Called by the INowPlusService implementation to remove user data Issues a * UI request to effectively log out. */ public void addUiRemoveUserDataRequest() { LogUtils.logD("LoginEngine.addUiRemoveUserDataRequest()"); addUiRequestToQueue(ServiceUiRequest.REMOVE_USER_DATA, null); } /** * Called by the INowPlusService implementation to start the sign-up * process. Adds a registration UI request to the queue and kicks the worker * thread. * * @param details The registration details entered by the user */ public void addUiRegistrationRequest(RegistrationDetails details) { LogUtils.logD("LoginEngine.addUiRegistrationRequest()"); addUiRequestToQueue(ServiceUiRequest.REGISTRATION, details); } /** * Called by the INowPlusService implementation to fetch terms of service * text for the UI. Adds a fetch terms of service UI request to the queue * and kicks the worker thread. */ public void addUiFetchTermsOfServiceRequest() { LogUtils.logD("LoginEngine.addUiFetchTermsOfServiceRequest()"); addUiRequestToQueue(ServiceUiRequest.FETCH_TERMS_OF_SERVICE, null); } /** * Called by the INowPlusService implementation to privacy statement for the * UI. Adds a fetch privacy statement UI request to the queue and kicks the * worker thread. */ public void addUiFetchPrivacyStatementRequest() { LogUtils.logD("LoginEngine.addUiFetchPrivacyStatementRequest()"); addUiRequestToQueue(ServiceUiRequest.FETCH_PRIVACY_STATEMENT, null); } /** * Called by the INowPlusService implementation to check if a username is * available for registration. Adds a get username state UI request to the * queue and kicks the worker thread. * * @param username Username to fetch the state of * TODO: Not currently used by UI. */ public void addUiGetUsernameStateRequest(String username) { LogUtils.logD("LoginEngine.addUiGetUsernameStateRequest()"); addUiRequestToQueue(ServiceUiRequest.USERNAME_AVAILABILITY, username); } /** * Return the absolute time in milliseconds when the engine needs to run * (based on System.currentTimeMillis). * * @return -1 never needs to run, 0 needs to run as soon as possible, * CurrentTime + 60000 to run in 1 minute, etc. */ @Override public long getNextRunTime() { if (isCommsResponseOutstanding()) { return 0; } if (uiRequestReady()) { return 0; } switch (mState) { case NOT_INITIALISED: return 0; case NOT_REGISTERED: case LOGGED_ON: case LOGIN_FAILED: case LOGIN_FAILED_WRONG_CREDENTIALS: return -1; case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: if (mActivationCode != null) { return 0; } break; case LOGGED_OFF: return 0; case LOGGED_OFF_WAITING_FOR_NETWORK: if (NetworkAgent.getAgentState() == AgentState.CONNECTED) { return 0; } break; case RETRIEVING_PUBLIC_KEY: return 0; default: // Do nothing. break; } return getCurrentTimeout(); } /** * Do some work but anything that takes longer than 1 second must be broken * up. The type of work done includes: * <ul> * <li>If a comms response from server is outstanding, process it</li> * <li>If a timeout is pending, process it</li> * <li>If an SMS activation code has been received, process it</li> * <li>Retry auto login if necessary</li> * </ul> */ @Override public void run() { LogUtils.logD("LoginEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { return; } if (processTimeout()) { return; } switch (mState) { case NOT_INITIALISED: - initialiseEngine(); + initializeEngine(); return; case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: if (mActivationCode != null) { handleSmsResponse(); return; } break; case RETRIEVING_PUBLIC_KEY: break; case LOGGED_OFF: case LOGGED_OFF_WAITING_FOR_NETWORK: AuthSessionHolder session = StateTable.fetchSession(mDb.getReadableDatabase()); // if session is null we try to login automatically again if (null == session) { if (retryAutoLogin()) { return; } } else { // otherwise we try to reuse the session sActivatedSession = session; newState(State.LOGGED_ON); } default: // do nothing. break; } if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { if (!isUiRequestOutstanding()) { return false; } switch (mState) { case NOT_REGISTERED: case LOGGED_OFF: case LOGGED_ON: case LOGIN_FAILED: case CREATING_SESSION_AUTO: case LOGIN_FAILED_WRONG_CREDENTIALS: case LOGGED_OFF_WAITING_FOR_RETRY: return true; default: return false; } } /** * Determines if the user is currently logged in with a valid session. * * @return true if logged in, false otherwise */ public boolean isLoggedIn() { return mState == State.LOGGED_ON; } /** * Add a listener which will receive events whenever the login state * changes. * * @param listener The callback interface */ public synchronized void addListener(ILoginEventsListener listener) { LogUtils.logD("LoginEngine.addListener()"); if (!mEventsListener.contains(listener)) { mEventsListener.add(listener); } } /** * Remove a listener added by the addListener function. * * @param listener The same callback interface passed in to the add function */ public synchronized void removeListener(ILoginEventsListener listener) { LogUtils.logD("LoginEngine.removeListener()"); mEventsListener.remove(listener); } /** * Remove all ILoginStateChangeListener (done as part of cleanup). */ private synchronized void removeAllListeners() { LogUtils.logD("LoginEngine.removeAllListeners()"); if (mEventsListener != null) { mEventsListener.clear(); } } /** * Once the engine has finished processing a user request, this function is * called to restore the state back to an appropriate value (based on the * user login state). */ private synchronized void restoreLoginState() { LogUtils.logD("LoginEngine.restoreLoginState"); if (mIsRegistrationComplete) { if (sActivatedSession != null) { newState(State.LOGGED_ON); } else { if (mAreLoginDetailsValid) { newState(State.LOGGED_OFF); } else { newState(State.LOGIN_FAILED); } } } else { newState(State.NOT_REGISTERED); } } /** * Called when a server response is received, processes the response based * on the engine state. * * @param resp Response data from server */ @Override protected void processCommsResponse(ResponseQueue.DecodedResponse resp) { LogUtils.logD("LoginEngine.processCommsResponse() - resp = " + resp); switch (mState) { case SIGNING_UP: handleSignUpResponse(resp.mDataTypes); break; case RETRIEVING_PUBLIC_KEY: handleNewPublicKeyResponse(resp.mDataTypes); break; case CREATING_SESSION_MANUAL: handleCreateSessionManualResponse(resp.mDataTypes); break; case CREATING_SESSION_AUTO: handleCreateSessionAutoResponse(resp.mDataTypes); break; case REQUESTING_ACTIVATION_CODE: handleRequestingActivationResponse(resp.mDataTypes); break; case ACTIVATING_ACCOUNT: handleActivateAccountResponse(resp.mDataTypes); break; case FETCHING_TERMS_OF_SERVICE: case FETCHING_PRIVACY_STATEMENT: case FETCHING_USERNAME_STATE: handleServerSimpleTextResponse(resp.mDataTypes, mState); break; default: // do nothing. break; } } /** * Called when a UI request is ready to be processed. Handlers the UI * request based on the type. * * @param requestId UI request type * @param data Interpretation of this data depends on the request type */ @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { LogUtils.logD("LoginEngine.processUiRequest() - reqID = " + requestId); switch (requestId) { case LOGIN: startManualLoginProcess((LoginDetails)data); break; case REGISTRATION: startRegistrationProcessCrypted((RegistrationDetails)data); break; case REMOVE_USER_DATA: startLogout(); // Remove NAB Account at this point (does nothing on 1.X) NativeContactsApi.getInstance().removePeopleAccount(); super.onReset(); // Sets the reset flag as done break; case LOGOUT: startLogout(); break; case FETCH_TERMS_OF_SERVICE: startFetchTermsOfService(); break; case FETCH_PRIVACY_STATEMENT: startFetchPrivacyStatement(); break; case USERNAME_AVAILABILITY: startFetchUsernameState((String)data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); } } /** * Called by the run() function the first time it is executed to perform * non-trivial initialisation such as auto login. */ - private void initialiseEngine() { + private void initializeEngine() { LogUtils.logD("LoginEngine.initialiseEngine()"); if (ServiceStatus.SUCCESS == mDb.fetchLogonCredentialsAndPublicKey(mLoginDetails, mPublicKey)) { - if (mLoginDetails.mSubscriberId != null - && !mLoginDetails.mSubscriberId.equals(mCurrentSubscriberId)) { - LogUtils.logW("SIM card has changed. Login session invalid"); - } else { - sActivatedSession = StateTable.fetchSession(mDb.getReadableDatabase()); - } + sActivatedSession = StateTable.fetchSession(mDb.getReadableDatabase()); } mAreLoginDetailsValid = true; restoreLoginState(); clearTimeout(); } /** * Starts the sign-up process where the password is RSA encrypted. A setting * determines if this function is used in preference to * {@link #startRegistrationProcess(RegistrationDetails)} function. * * @param details Registration details received from the UI request */ private void startRegistrationProcessCrypted(RegistrationDetails details) { LogUtils.logD("startRegistrationCrypted"); if (details == null || details.mUsername == null || details.mPassword == null) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } setRegistrationComplete(false); setActivatedSession(null); mRegistrationDetails.copy(details); mLoginDetails.mUsername = mRegistrationDetails.mUsername; mLoginDetails.mPassword = mRegistrationDetails.mPassword; try { final long timestampInSeconds = System.currentTimeMillis() / MS_IN_SECONDS; final byte[] theBytes = prepareBytesForSignup(timestampInSeconds); mLoginDetails.mAutoConnect = true; mLoginDetails.mRememberMe = true; mLoginDetails.mMobileNo = mRegistrationDetails.mMsisdn; - mLoginDetails.mSubscriberId = mCurrentSubscriberId; + mLoginDetails.mSubscriberId = SimCard.getSubscriberId(mContext); mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); startSignUpCrypted(theBytes, timestampInSeconds); } catch (InvalidCipherTextException e) { e.printStackTrace(); } } /** * Encrypts the sign-up data ready for sending to the server * * @param timeStampInSeconds Current time in milliseconds * @return Raw data that can be sent to the server */ private byte[] prepareBytesForSignup(long timeStampInSeconds) throws InvalidCipherTextException { byte[] theBytes = null; if (mPublicKey != null) { if (mPublicKey.mExponential != null && (mPublicKey.mModulus != null)) { theBytes = RSAEncryptionUtils.encryptRSA(RSAEncryptionUtils.getRSAPubKey( mPublicKey.mModulus, mPublicKey.mExponential), makeSecurePassword( mLoginDetails.mUsername, mLoginDetails.mPassword, timeStampInSeconds)); } } if (theBytes == null) { RSAEncryptionUtils.copyDefaultPublicKey(mPublicKey);// we'll store // the default // public key // into the db theBytes = RSAEncryptionUtils.encryptRSA(RSAEncryptionUtils.getDefaultPublicKey(), makeSecurePassword(mLoginDetails.mUsername, mLoginDetails.mPassword, timeStampInSeconds)); } return theBytes; } /** * Concatenates the username, password, current time and some other data * into a string which can be encrypted and sent to the server. * * @param userName User name for sign-in or sign-up * @param password Password as entered by user * @param ts Current time in milliseconds * @return Concatenated data */ private static String makeSecurePassword(String userName, String password, long ts) { String appSecret = SettingsManager.getProperty(Settings.APP_SECRET_KEY);// RSAEncrypter.testAppSecretThrottled; final char amp = '&'; if (ts <= 0 || // userName == null || userName.trim().length() == 0 || // password == null || password.trim().length() == 0 || // // set application key somewhere appSecret == null || appSecret.trim().length() == 0) return null; final String passwordT = password.trim(); final String userNameT = userName.trim(); final StringBuffer sb = new StringBuffer(); sb.append(appSecret).append(amp).append(Long.toString(ts)).append(amp).append(userNameT) .append(amp).append(passwordT); return sb.toString(); } /** * Puts the engine into the signing up state and sends an encrypted sign-up * request to the server. * * @param theBytes byte-array containing encrypted password data. * @param timestamp Current timestamp. */ private void startSignUpCrypted(byte[] theBytes, long timestamp) { LogUtils.logD("startSignUpCrypted()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mActivationCode = null; newState(State.SIGNING_UP); if (!validateRegistrationDetails()) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } int reqId = Auth.signupUserCrypted( this, mRegistrationDetails.mFullname, mRegistrationDetails.mUsername, theBytes, // what is encrypted timestamp, mRegistrationDetails.mEmail, mRegistrationDetails.mBirthdayDate, mRegistrationDetails.mMsisdn, mRegistrationDetails.mAcceptedTAndC, mRegistrationDetails.mCountrycode, mRegistrationDetails.mTimezone, mRegistrationDetails.mLanguage, mRegistrationDetails.mMobileOperatorId, mRegistrationDetails.mMobileModelId, mRegistrationDetails.mSendConfirmationMail, mRegistrationDetails.mSendConfirmationSms, mRegistrationDetails.mSubscribeToNewsLetter); if (!setReqId(reqId)) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Basic check to determine if the registration details given by the user * are valid * * @return true if the details are valid, false otherwise. */ private boolean validateRegistrationDetails() { if (mRegistrationDetails.mFullname == null || mRegistrationDetails.mEmail == null || mRegistrationDetails.mBirthdayDate == null || mRegistrationDetails.mMsisdn == null || mRegistrationDetails.mAcceptedTAndC == null || mRegistrationDetails.mCountrycode == null || mRegistrationDetails.mTimezone == null || mRegistrationDetails.mLanguage == null || mRegistrationDetails.mMobileOperatorId == null || mRegistrationDetails.mMobileModelId == null || mRegistrationDetails.mSendConfirmationMail == null || mRegistrationDetails.mSendConfirmationSms == null || mRegistrationDetails.mSubscribeToNewsLetter == null) { return false; } return true; } /** * Requests a new Public Key from the server. */ public void getNewPublicKey() { LogUtils.logD("LoginEngine.getNewPublicKey"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mActivationCode = null; newState(State.RETRIEVING_PUBLIC_KEY); if (!setReqId(Auth.getPublicKey(this))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch terms of service request to the server. */ private void startFetchTermsOfService() { LogUtils.logD("LoginEngine.startFetchTermsOfService()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } newState(State.FETCHING_TERMS_OF_SERVICE); if (!setReqId(Auth.getTermsAndConditions(this))) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch privacy statement request to the server. */ private void startFetchPrivacyStatement() { LogUtils.logD("LoginEngine.startFetchPrivacyStatement()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } newState(State.FETCHING_PRIVACY_STATEMENT); if (!setReqId(Auth.getPrivacyStatement(this))) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch user-name state request to the server. * * @param username, the user-name to retrieve information for. */ private void startFetchUsernameState(String username) { LogUtils.logD("LoginEngine.startFetchUsernameState()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mLoginDetails.mUsername = username; newState(State.FETCHING_USERNAME_STATE); if (!setReqId(Auth.getUsernameState(this, username))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sets registration complete flag to false then starts a new sign-in * request. * * @param details Login details received from the UI request */ private void startManualLoginProcess(LoginDetails details) { LogUtils.logD("LoginEngine.startManualLoginProcess()"); setRegistrationComplete(false); setActivatedSession(null); if (details == null) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } mLoginDetails.copy(details); - mLoginDetails.mSubscriberId = mCurrentSubscriberId; + mLoginDetails.mSubscriberId = SimCard.getSubscriberId(mContext); mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); if (Settings.ENABLE_ACTIVATION) { startRequestActivationCode(); } else { startGetSessionManual(); } } /** * Sends a request activation code request to the server. */ private void startRequestActivationCode() { LogUtils.logD("LoginEngine.startRequestActivationCode()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mActivationCode = null; newState(State.REQUESTING_ACTIVATION_CODE); if (!setReqId(Auth.requestActivationCode(this, mLoginDetails.mUsername, mLoginDetails.mMobileNo))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a get session by credentials request to the server. */ private void startGetSessionManual() { LogUtils.logD("LoginEngine.startGetSessionManual()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } newState(State.CREATING_SESSION_MANUAL); if (!setReqId(Auth.getSessionByCredentials(this, mLoginDetails.mUsername, mLoginDetails.mPassword, null))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a activate account request to the server. */ private void startActivateAccount() { LogUtils.logD("LoginEngine.startActivateAccount()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } if (Settings.ENABLE_ACTIVATION) { newState(State.ACTIVATING_ACCOUNT); if (!setReqId(Auth.activate(this, mActivationCode))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } else { setRegistrationComplete(true); completeUiRequest(ServiceStatus.SUCCESS, null); } } /** * Clears the session and registration complete information so that the user * will need to manually login again to use the now+ services. Does not * currently send a request to the server to log out. */ private void startLogout() { LogUtils.logD("LoginEngine.startLogout()"); setRegistrationComplete(false); setActivatedSession(null); completeUiRequest(ServiceStatus.SUCCESS, null); } /** * Clears the session and registration complete information so that the user * will need to manually login again to use the now+ services. Does not * currently send a request to the server to log out. */ public final void logoutAndRemoveUser() { LogUtils.logD("LoginEngine.startLogout()"); addUiRemoveUserDataRequest(); LoginPreferences.clearPreferencesFile(mContext); mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UNSOLICITED_GO_TO_LANDING_PAGE, null); } /** * Retries to log the user in based on credential information stored in the * database. * * @return true if the login process was able to start */ public boolean retryAutoLogin() { LogUtils.logD("LoginEngine.retryAutoLogin()"); setActivatedSession(null); if (ServiceStatus.SUCCESS != mDb.fetchLogonCredentialsAndPublicKey(mLoginDetails, mPublicKey)) { LogUtils .logE("LoginEngine.retryAutoLogin() - Unable to fetch credentials from database"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } // AA: commented the condition out if (Settings.ENABLE_ACTIVATION) { // AA: the old version if (mCurrentSubscriberId == null || // !mCurrentSubscriberId.equals(mLoginDetails.mSubscriberId)) { // // logging off/fail will be done in another way according to bug 8288 - if (mCurrentSubscriberId != null - && !mCurrentSubscriberId.equals(mLoginDetails.mSubscriberId)) { + final String currentSubscriberId = SimCard.getSubscriberId(mContext); + if (currentSubscriberId != null + && !currentSubscriberId.equals(mLoginDetails.mSubscriberId)) { LogUtils.logV("LoginEngine.retryAutoLogin() -" + " SIM card has changed or is missing (old subId = " - + mLoginDetails.mSubscriberId + ", new subId = " + mCurrentSubscriberId + ")"); + + mLoginDetails.mSubscriberId + ", new subId = " + currentSubscriberId + ")"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } // } if (mLoginDetails.mUsername == null || mLoginDetails.mPassword == null || mLoginDetails.mMobileNo == null) { LogUtils.logV("LoginEngine.retryAutoLogin() - Username, password " + "or mobile number are missing (old username = " + mLoginDetails.mUsername + ", mobile no = " + mLoginDetails.mMobileNo + ")"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } mAreLoginDetailsValid = true; if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { newState(State.LOGGED_OFF_WAITING_FOR_NETWORK); LogUtils.logV("LoginEngine.retryAutoLogin() - Internet connection down. " + "Will try again when connection is available"); return false; } newState(State.CREATING_SESSION_AUTO); if (!setReqId(Auth.getSessionByCredentials(this, mLoginDetails.mUsername, mLoginDetails.mPassword, null))) { return false; } return true; } /** * Helper function to set the registration complete flag and update the * database with the new state. * * @param value true if registration is completed */ private void setRegistrationComplete(boolean value) { LogUtils.logD("LoginEngine.setRegistrationComplete(" + value + ")"); if (value != mIsRegistrationComplete) { StateTable.setRegistrationComplete(value, mDb.getWritableDatabase()); mIsRegistrationComplete = value; if (mIsRegistrationComplete) { // Create NAB Account at this point (does nothing on 1.X // devices) final NativeContactsApi nabApi = NativeContactsApi.getInstance(); if (!nabApi.isPeopleAccountCreated()) { // TODO: React upon failure to create account nabApi.addPeopleAccount(LoginPreferences.getUsername()); } } } } /** * Changes the state of the engine. Also displays the login notification if * necessary. * * @param newState The new state */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("LoginEngine.newState: " + oldState + " -> " + mState); Intent intent = null; // Update notification switch (mState) { case LOGIN_FAILED_WRONG_CREDENTIALS: intent = new Intent(); intent.setAction(Intents.START_LOGIN_ACTIVITY); mContext.sendBroadcast(intent); setRegistrationComplete(false); break; // here should be no break case NOT_REGISTERED: case LOGIN_FAILED: // intent = new Intent(); // intent.setAction(Intents.LOGIN_FAILED); // mContext.sendBroadcast(intent); setRegistrationComplete(false); // startLogout(); // mDb.removeUserData(); // sending user to login screen again // should be done by UI itself because // when it's done from here it cause problems when user tries to // login // giving wrong credentials, ui flow will be broken break; case LOGGED_OFF: case LOGGED_OFF_WAITING_FOR_NETWORK: case LOGGED_OFF_WAITING_FOR_RETRY: case LOGGED_ON: // intent = new Intent(); // intent.setAction(Intents.HIDE_LOGIN_NOTIFICATION); // mContext.sendBroadcast(intent); break; default:// do nothing break; } // Update listeners with any state changes switch (mState) { case NOT_REGISTERED: case LOGIN_FAILED: case LOGIN_FAILED_WRONG_CREDENTIALS: case LOGGED_OFF: onLoginStateChanged(false); break; case LOGGED_ON: onLoginStateChanged(true); break; default: // do nothing. break; } } /** * Called when the engine transitions between the logged in and logged out * states. Notifies listeners. * * @param loggedIn true if the user is now logged in, false otherwise. */ private synchronized void onLoginStateChanged(boolean loggedIn) { LogUtils.logD("LoginEngine.onLoginStateChanged() Login state changed to " + (loggedIn ? "logged in." : "logged out.")); if (loggedIn == mCurrentLoginState) { return; } mCurrentLoginState = loggedIn; for (ILoginEventsListener listener : mEventsListener) { listener.onLoginStateChanged(loggedIn); } } /** * A helper function which determines which activity should be displayed * when the UI is loaded. * * @return true if landing page should be displayed, false otherwise */ public synchronized boolean getLoginRequired() { LogUtils.logD("LoginEngine.getLoginRequired() - " + !mIsRegistrationComplete); return !mIsRegistrationComplete; } /** * Retrieves the active comms session. * * @return The session or NULL if the user is logged out. */ public static AuthSessionHolder getSession() { return sActivatedSession; } /** * Helper function to store the new session in the database and inform * clients that the session has changed. * * @param session The new session or NULL if the user has logged off. */ public synchronized void setActivatedSession(AuthSessionHolder session) { LogUtils.logD("LoginEngine.setActivatedSession() session[" + session + "]"); sActivatedSession = session; if (session != null) { LogUtils.logD("LoginEngine.setActivatedSession() Login successful"); } else { LogUtils.logW("LoginEngine.setActivatedSession() " + "Login unsuccessful, the session is NULL"); } StateTable.setSession(session, mDb.getWritableDatabase()); } /** * Called when a response to the sign-up API is received. In case of success * sets a timeout value waiting for the activation SMS to arrive. * * @param data The received data */ private void handleSignUpResponse(List<BaseDataType> data) { ServiceStatus errorStatus = getResponseStatus(BaseDataType.CONTACT_DATA_TYPE, data); LogUtils.logD("LoginEngine.handleSignUpResponse() errorStatus[" + errorStatus.name() + "]"); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils.logD("LoginEngine.handleSignUpResponse() - Registration successful"); if (!Settings.ENABLE_ACTIVATION) { startGetSessionManual(); } else { // Now waiting for SMS... setTimeout(ACTIVATE_LOGIN_TIMEOUT); } // AA } else if (errorStatus == ServiceStatus.ERROR_INVALID_PUBLIC_KEY) { // start new key retrieval and make the new cycle getNewPublicKey(); } else { completeUiRequest(errorStatus, null); } } /** * Called when a response to the server fetch public key request is * received. Validates the response and stores the new public key details. * * @param mDataTypes Response data from server. */ private void handleNewPublicKeyResponse(List<BaseDataType> mDataTypes) { LogUtils.logD("LoginEngine.handleNewPublicKeyResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.PUBLIC_KEY_DETAILS_DATA_TYPE, mDataTypes); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils.logD("LoginEngine.handleNewPublicKeyResponse() - Succesfully retrieved"); // AA // 1. save to DB; save the flag that we aren't using default and // have to use one from DB // 2. start registration again mPublicKey = (PublicKeyDetails)mDataTypes.get(0); // done in startRegistrationProcessCrypted already // mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); startRegistrationProcessCrypted(mRegistrationDetails); } else { completeUiRequest(errorStatus, null); } } /** * Called when a response to the GetSessionByCredentials API is received * (manual login). In case of success, tries to activate the account using * the activation code received by SMS. * * @param data The received data */ private void handleCreateSessionManualResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleCreateSessionManualResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AUTH_SESSION_HOLDER_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS && (data.size() > 0)) { setActivatedSession((AuthSessionHolder)data.get(0)); startActivateAccount(); return; } completeUiRequest(errorStatus, null); } /** * Called when a response to the GetSessionByCredentials API is received * (auto login). In case of success, moves to the logged in state * * @param data The received data */ private void handleCreateSessionAutoResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleCreateSessionResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AUTH_SESSION_HOLDER_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { clearTimeout(); setActivatedSession((AuthSessionHolder)data.get(0)); newState(State.LOGGED_ON); } else { LogUtils.logE("LoginEngine.handleCreateSessionResponse() - Auto Login Failed Error " + errorStatus); // AA:the 1st retry failed, just go to the start page, // if (loginAttemptsRemaining() // && errorStatus!=ServiceStatus.ERROR_INVALID_PASSWORD) { // newState(State.LOGGED_OFF_WAITING_FOR_RETRY); // setTimeout(LOGIN_RETRY_TIME); // } else { // mAreLoginDetailsValid = false; if (errorStatus == ServiceStatus.ERROR_INVALID_PASSWORD) { mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED_WRONG_CREDENTIALS); } else { newState(State.LOGIN_FAILED); } // } } } /** * Called when a response to the RequestActivationCode API is received * (manual login). In case of success, tries to fetch a login session from * the server. * * @param data The received data */ private void handleRequestingActivationResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleRequestingActivationResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { // Now waiting for SMS... setTimeout(ACTIVATE_LOGIN_TIMEOUT); return; } completeUiRequest(errorStatus, null); } /** * Called when a response to the Activate API is received (manual login or * sign-up). In case of success, moves to the logged in state and completes * the manual login or sign-up request. * * @param data The received data */ private void handleActivateAccountResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleActivateAccountResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils .logD("LoginEngine.handleActivateAccountResponse: ** Mobile number activated **"); setRegistrationComplete(true); completeUiRequest(ServiceStatus.SUCCESS, null); return; } setActivatedSession(null); completeUiRequest(ServiceStatus.ERROR_ACCOUNT_ACTIVATION_FAILED, null); } /** * Called when a response to the GetTermsAndConditions, GetPrivacyStatement * and GetUsernameState APIs are received. In case of success, completes the * request and passes the response data to the UI. * * @param data The received data */ private void handleServerSimpleTextResponse(List<BaseDataType> data, State type) { LogUtils.logV("LoginEngine.handleServerSimpleTextResponse()"); ServiceStatus serviceStatus = getResponseStatus(BaseDataType.SIMPLE_TEXT_DATA_TYPE, data); String result = null; if (serviceStatus == ServiceStatus.SUCCESS) { result = ((SimpleText) data.get(0)).mValue.toString().replace( CARRIAGE_RETURN_CHARACTER, SPACE_CHARACTER); switch (type) { case FETCHING_TERMS_OF_SERVICE: LogUtils.logD("LoginEngine.handleServerSimpleTextResponse() Terms of Service"); ApplicationCache.setTermsOfService(result, mContext); break; case FETCHING_PRIVACY_STATEMENT: LogUtils.logD("LoginEngine.handleServerSimpleTextResponse() Privacy Statemet"); ApplicationCache.setPrivacyStatemet(result, mContext); break; case FETCHING_USERNAME_STATE: // TODO: Unused by UI. break; } } updateTermsState(serviceStatus, result); } /*** * Informs the UI to update any terms which are being shown on screen. * * @param serviceStatus Current ServiceStatus. * @param messageText Legacy call for old UI (TODO: remove after UI-Refresh * merge). NULL when combined with a ServiceStatus of * ERROR_COMMS, or contains the Privacy or Terms and Conditions * text to be displayed in the UI. */ private void updateTermsState(ServiceStatus serviceStatus, String messageText) { ApplicationCache.setTermsStatus(serviceStatus); /** Trigger UiAgent. **/ mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.TERMS_CHANGED_EVENT, null); /** Clear this request from the UI queue. **/ completeUiRequest(serviceStatus, messageText); } /** * A broadcast receiver which is used to receive notifications when a data * SMS arrives. */ private final BroadcastReceiver mEventReceiver = new BroadcastReceiver() { /** * Called when an SMS arrives. The activation code is extracted from the * given intent and the worker thread kicked. * * @param context Context from which the intent was broadcast * @param intent Will only process the SMS which the action is * {@link SmsBroadcastReceiver#ACTION_ACTIVATION_CODE}. */ @Override public void onReceive(Context context, Intent intent) { LogUtils.logD("LoginEngine.BroadcastReceiver.onReceive - Processing data sms"); if (intent.getAction().equals(SmsBroadcastReceiver.ACTION_ACTIVATION_CODE)) { String activationCode = intent.getStringExtra("code"); LogUtils .logD("LoginEngine.BroadcastReceiver.onReceive - Activation code Received: " + activationCode); synchronized (LoginEngine.this) { mActivationCode = activationCode; } mEventCallback.kickWorkerThread(); } } }; /** * Called when an SMS is received during sign-up or manual login. Starts * requesting a session from the server. */ private void handleSmsResponse() { LogUtils.logD("LoginEngine.handleSmsResponse(" + mActivationCode + ")"); clearTimeout(); startGetSessionManual(); } /** * Called by the base engine implementation whenever a UI request is * completed to do any necessary cleanup. We use it to restore our state to * a suitable value. */ @Override protected void onRequestComplete() { LogUtils.logD("LoginEngine.onRequestComplete()"); restoreLoginState(); } /** * Handles timeouts for SMS activation and auto login retries. */ protected synchronized void onTimeoutEvent() { LogUtils.logD("LoginEngine.onTimeoutEvent()"); switch (mState) { case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: completeUiRequest(ServiceStatus.ERROR_SMS_CODE_NOT_RECEIVED, null); break; case LOGGED_OFF_WAITING_FOR_RETRY: retryAutoLogin(); break; default: // do nothing. break; } } /** * Called by the framework before a remove user data operation takes place. * Initiates a suitable UI request which will kick the worker thread. */ @Override public void onReset() { // reset the engine as if it was just created super.onReset(); setRegistrationComplete(false); setActivatedSession(null); mState = State.NOT_INITIALISED; mRegistrationDetails = new RegistrationDetails(); mActivationCode = null; onLoginStateChanged(false); } /** * Set 'dummy' auth session for test purposes only. * * @param session 'dummy' session supplied to LoginEngine */ public static void setTestSession(AuthSessionHolder session) { sActivatedSession = session; } } diff --git a/src/com/vodafone360/people/service/RemoteService.java b/src/com/vodafone360/people/service/RemoteService.java index e2a4a6a..845b545 100644 --- a/src/com/vodafone360/people/service/RemoteService.java +++ b/src/com/vodafone360/people/service/RemoteService.java @@ -1,334 +1,339 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import java.security.InvalidParameterException; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import com.vodafone360.people.MainApplication; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.interfaces.IConnectionManagerInterface; import com.vodafone360.people.service.interfaces.IPeopleServiceImpl; import com.vodafone360.people.service.interfaces.IWorkerThreadControl; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.IWakeupListener; +import com.vodafone360.people.service.utils.UserDataProtection; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * Implementation of People client's Service class. Loads properties from * SettingsManager. Creates NetworkAgent. Connects to ConnectionManager enabling * transport layer. Activates service's worker thread when required. */ public class RemoteService extends Service implements IWorkerThreadControl, IConnectionManagerInterface { /** * Intent received when service is started is tested against the value * stored in this key to determine if the service has been started because * of an alarm. */ public static final String ALARM_KEY = "alarm_key"; /** * Action for an Authenticator. * Straight copy from AccountManager.ACTION_AUTHENTICATOR_INTENT in 2.X platform */ public static final String ACTION_AUTHENTICATOR_INTENT = "android.accounts.AccountAuthenticator"; /** * Sync Adapter System intent action received on Bind. */ public static final String ACTION_SYNC_ADAPTER_INTENT = "android.content.SyncAdapter"; /** * Main reference to network agent * * @see NetworkAgent */ private NetworkAgent mNetworkAgent; /** * Worker thread reference * * @see WorkerThread */ private WorkerThread mWorkerThread; /** * The following object contains the implementation of the * {@link com.vodafone360.people.service.interfaces.IPeopleService} * interface. */ private IPeopleServiceImpl mIPeopleServiceImpl; /** * Used by comms when waking up the CPI at regular intervals and sending a * heartbeat is necessary */ private IWakeupListener mWakeListener; /** * true when the service has been fully initialised */ private boolean mIsStarted = false; /** * Stores the previous network connection state (true = connected) */ private boolean mIsConnected = true; private NativeAccountObjectsHolder mAccountsObjectsHolder = null; /** * Creation of RemoteService. Loads properties (i.e. supported features, * server URLs etc) from SettingsManager. Creates IPeopleServiceImpl, * NetworkAgent. Connects ConnectionManager creating Connection thread(s) * and DecoderThread 'Kicks' worker thread. */ @Override public void onCreate() { LogUtils.logV("RemoteService.onCreate()"); SettingsManager.loadProperties(this); mIPeopleServiceImpl = new IPeopleServiceImpl(this, this); mNetworkAgent = new NetworkAgent(this, this, this); // Create NativeContactsApi here to access Application Context NativeContactsApi.createInstance(getApplicationContext()); EngineManager.createEngineManager(this, mIPeopleServiceImpl); mNetworkAgent.onCreate(); mIPeopleServiceImpl.setNetworkAgent(mNetworkAgent); ConnectionManager.getInstance().connect(this); /** The service has now been fully initialised. **/ mIsStarted = true; kickWorkerThread(); - ((MainApplication)getApplication()).setServiceInterface(mIPeopleServiceImpl); + final MainApplication mainApp = (MainApplication)getApplication(); + mainApp.setServiceInterface(mIPeopleServiceImpl); if(VersionUtils.is2XPlatform()) { mAccountsObjectsHolder = new NativeAccountObjectsHolder(((MainApplication)getApplication())); } + + final UserDataProtection userDataProtection = new UserDataProtection(this, mainApp.getDatabase()); + userDataProtection.performStartupChecks(); } /** * Called on start of RemoteService. Check if we need to kick the worker * thread or 'wake' the TCP connection thread. */ @Override public void onStart(Intent intent, int startId) { if(intent == null) { LogUtils.logV("RemoteService.onStart() intent is null. Returning."); return; } - Bundle mBundle = intent.getExtras(); + final Bundle bundle = intent.getExtras(); LogUtils.logI("RemoteService.onStart() Intent action[" - + intent.getAction() + "] data[" + mBundle + "]"); + + intent.getAction() + "] data[" + bundle + "]"); - if ((null == mBundle) || (null == mBundle.getString(ALARM_KEY))) { + if ((null == bundle) || (null == bundle.getString(ALARM_KEY))) { LogUtils.logV("RemoteService.onStart() mBundle is null. Returning."); return; } - if (mBundle.getString(ALARM_KEY).equals(WorkerThread.ALARM_WORKER_THREAD)) { + if (bundle.getString(ALARM_KEY).equals(WorkerThread.ALARM_WORKER_THREAD)) { LogUtils.logV("RemoteService.onStart() ALARM_WORKER_THREAD Alarm thrown"); kickWorkerThread(); - } else if (mBundle.getString(ALARM_KEY).equals(IWakeupListener.ALARM_HB_THREAD)) { + } else if (bundle.getString(ALARM_KEY).equals(IWakeupListener.ALARM_HB_THREAD)) { LogUtils.logV("RemoteService.onStart() ALARM_HB_THREAD Alarm thrown"); if (null != mWakeListener) { mWakeListener.notifyOfWakeupAlarm(); } } } /** * Destroy RemoteService Close WorkerThread, destroy EngineManger and * NetworkAgent. */ @Override public void onDestroy() { LogUtils.logV("RemoteService.onDestroy()"); ((MainApplication)getApplication()).setServiceInterface(null); mIsStarted = false; synchronized (this) { if (mWorkerThread != null) { mWorkerThread.close(); } } EngineManager.destroyEngineManager(); // No longer need NativeContactsApi NativeContactsApi.destroyInstance(); mNetworkAgent.onDestroy(); } /** * Service binding is not used internally by this Application, but called * externally by the system when it needs an Authenticator or Sync * Adapter. This method will throw an InvalidParameterException if it is * not called with the expected intent (or called on a 1.x platform). */ @Override public IBinder onBind(Intent intent) { final String action = intent.getAction(); if (VersionUtils.is2XPlatform() && action != null) { if (action.equals(ACTION_AUTHENTICATOR_INTENT)) { return mAccountsObjectsHolder.getAuthenticatorBinder(); } else if (action.equals(ACTION_SYNC_ADAPTER_INTENT)) { return mAccountsObjectsHolder.getSyncAdapterBinder(); } } throw new InvalidParameterException("RemoteService.action() " + "There are no Binders for the given Intent"); } /*** * Ensures that the WorkerThread runs at least once. */ @Override public void kickWorkerThread() { synchronized (this) { if (!mIsStarted) { // Thread will be kicked anyway once we have finished // initialisation. return; } if (mWorkerThread == null || !mWorkerThread.wakeUp()) { LogUtils.logV("RemoteService.kickWorkerThread() Start thread"); mWorkerThread = new WorkerThread(mHandler); mWorkerThread.start(); } } } /*** * Handler for remotely calling the kickWorkerThread() method. */ private final Handler mHandler = new Handler() { /** * Process kick worker thread message */ @Override public void handleMessage(Message msg) { kickWorkerThread(); } }; /** * Called by NetworkAgent to notify whether device has become connected or * disconnected. The ConnectionManager connects or disconnects * appropriately. We kick the worker thread if our internal connection state * is changed. * * @param connected true if device has become connected, false if device is * disconnected. */ @Override public void signalConnectionManager(boolean connected) { // if service agent becomes connected start conn mgr thread LogUtils.logI("RemoteService.signalConnectionManager()" + "Signalling Connection Manager to " + (connected ? "connect." : "disconnect.")); if (connected) { ConnectionManager.getInstance().connect(this); } else {// SA is disconnected stop conn thread (and close connections?) ConnectionManager.getInstance().disconnect(); } // kick EngineManager to run() and apply CONNECTED/DISCONNECTED changes if (connected != mIsConnected) { if (mIPeopleServiceImpl != null) { mIPeopleServiceImpl.kickWorkerThread(); } } mIsConnected = connected; } /** * <p> * Registers a listener (e.g. the HeartbeatSender for TCP) that will be * notified whenever an intent for a new alarm is received. * </p> * <p> * This is desperately needed as the CPU of Android devices will halt when * the user turns off the screen and all CPU related activity is suspended * for that time. The wake up alarm is one simple way of achieving the CPU * to wake up and send out data (e.g. the heartbeat sender). * </p> */ public void registerCpuWakeupListener(IWakeupListener wakeListener) { mWakeListener = wakeListener; } /** * Return handle to {@link NetworkAgent} * * @return handle to {@link NetworkAgent} */ public NetworkAgent getNetworkAgent() { return mNetworkAgent; } /** * Set an Alarm with the AlarmManager to trigger the next update check. * * @param set Set or cancel the Alarm * @param realTime Time when the Alarm should be triggered */ public void setAlarm(boolean set, long realTime) { Intent mRemoteServiceIntent = new Intent(this, this.getClass()); mRemoteServiceIntent.putExtra(RemoteService.ALARM_KEY, IWakeupListener.ALARM_HB_THREAD); PendingIntent mAlarmSender = PendingIntent.getService(this, 0, mRemoteServiceIntent, 0); AlarmManager mAlarmManager = (AlarmManager)getSystemService(RemoteService.ALARM_SERVICE); if (set) { if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logV("WorkerThread.setAlarm() Check for the next update at [" + realTime + "] or in [" + (realTime - System.currentTimeMillis()) + "ms]"); } mAlarmManager.set(AlarmManager.RTC_WAKEUP, realTime, mAlarmSender); /* * mAlarmManager.set(AlarmManager.RTC, realTime, mAlarmSender); * TODO: Optimisation suggestion - Consider only doing work when the * device is already awake */ } else { mAlarmManager.cancel(mAlarmSender); } } } diff --git a/src/com/vodafone360/people/service/receivers/SimStateReceiver.java b/src/com/vodafone360/people/service/receivers/SimStateReceiver.java new file mode 100755 index 0000000..7dc2463 --- /dev/null +++ b/src/com/vodafone360/people/service/receivers/SimStateReceiver.java @@ -0,0 +1,65 @@ +package com.vodafone360.people.service.receivers; + +import com.vodafone360.people.utils.LogUtils; +import com.vodafone360.people.utils.SimCard; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.telephony.TelephonyManager; + +/** + * The SimStateReceiver is a BroadcastReceiver used to listen for SIM state changes. + * + * @see INTENT_SIM_STATE_CHANGED + */ +public class SimStateReceiver extends BroadcastReceiver { + + /** + * The Listener interface. + */ + public interface Listener { + + /** + * Callback method when SIM is ready. + */ + void onSimReadyState(); + } + + /** + * The Intent broadcasted by the Android platform when the SIM card state changes. + */ + public final static String INTENT_SIM_STATE_CHANGED = "android.intent.action.SIM_STATE_CHANGED"; + + /** + * The registered Listener. + */ + private final Listener mListener; + + /** + * The SimStateReceiver constructor. + * + * @param listener the registered listener + */ + public SimStateReceiver(Listener listener) { + + LogUtils.logD("SimStateReceiver instance created."); + mListener = listener; + } + + /** + * @see BroadcastReceiver#onReceive(Context, Intent) + */ + @Override + public void onReceive(Context context, Intent intent) { + + final int simState = SimCard.getState(context); + + LogUtils.logD("SimStateReceiver.onReceive() - simState="+simState); + + if (simState == TelephonyManager.SIM_STATE_READY) { + + mListener.onSimReadyState(); + } + } +} diff --git a/src/com/vodafone360/people/service/utils/UserDataProtection.java b/src/com/vodafone360/people/service/utils/UserDataProtection.java new file mode 100755 index 0000000..4222b80 --- /dev/null +++ b/src/com/vodafone360/people/service/utils/UserDataProtection.java @@ -0,0 +1,155 @@ +package com.vodafone360.people.service.utils; + +import android.content.Context; +import android.content.IntentFilter; +import android.telephony.TelephonyManager; +import android.text.TextUtils; + +import com.vodafone360.people.database.DatabaseHelper; +import com.vodafone360.people.datatypes.LoginDetails; +import com.vodafone360.people.engine.EngineManager; +import com.vodafone360.people.engine.login.LoginEngine; +import com.vodafone360.people.service.ServiceStatus; +import com.vodafone360.people.service.receivers.SimStateReceiver; +import com.vodafone360.people.utils.LogUtils; +import com.vodafone360.people.utils.SimCard; + +/** + * The UserDataProtection is responsible of putting in place mechanisms that will guarantee + * the User data safety. + * + * The case to watch are the following: + * -User uses SIM card A to log in 360 then restarting the device with SIM card B or without a SIM + * card will automatically log out from the 360 client. + * -User uses no SIM card to log in 360 then restarting the device with a SIM card will automatically + * log out from the 360 client. + */ +public class UserDataProtection implements SimStateReceiver.Listener { + + /** + * The Service context. + */ + private Context mContext; + + /** + * The DatabaseHelper used for our database access. + */ + private DatabaseHelper mDatabaseHelper; + + /** + * The BroadcastReceiver listening for SIM states changes. + */ + private SimStateReceiver mSimStateReceiver; + + /** + * The UserDataProtection constructor. + * + * @param context the Service context + * @param databaseHelper the DatabaseHelper + */ + public UserDataProtection(Context context, DatabaseHelper databaseHelper) { + + mContext = context; + mDatabaseHelper = databaseHelper; + } + + /** + * Performs the checks needed when the 360 Service is started. + * + * This method checks if the user has changed and if the SIM card id cannot be read, sets a + * SIM state changes listener. + */ + public void performStartupChecks() { + + LogUtils.logD("UserDataProtection.performStartupChecks()"); + + final LoginEngine loginEngine = EngineManager.getInstance().getLoginEngine(); + + if (loginEngine.isLoggedIn()) { + + final int simState = SimCard.getState(mContext); + + if (simState == TelephonyManager.SIM_STATE_ABSENT || simState == TelephonyManager.SIM_STATE_READY) { + + processUserChanges(); + } else { + + LogUtils.logD("UserDataProtection.performStartupChecks() - SIM_STATE_UNKNOWN, register a SimStateReceiver."); + // SIM is not ready, register a listener for Sim state changes to check + // the subscriber id when possible + mSimStateReceiver = new SimStateReceiver(this); + mContext.registerReceiver(mSimStateReceiver, new IntentFilter(SimStateReceiver.INTENT_SIM_STATE_CHANGED)); + } + } + } + + /** + * Requests to log out from 360 if the user has changed. + */ + public void processUserChanges() { + + LogUtils.logD("UserDataProtection.checkUserChanges()"); + + final LoginEngine loginEngine = EngineManager.getInstance().getLoginEngine(); + + if (loginEngine.isLoggedIn() && hasUserChanged()) { + + // User has changed, log out + LogUtils.logD("UserDataProtection.checkUserChanges() - User has changed! Request logout."); + loginEngine.addUiRemoveUserDataRequest(); + } + } + + /** + * Unregister the SIM state changes receiver. + */ + public void unregisterSimStateReceiver() { + + if (mSimStateReceiver != null) { + + LogUtils.logD("UserDataProtection.checkUserChanges() - unregister the SimStateReceiver"); + mContext.unregisterReceiver(mSimStateReceiver); + } + } + + /** + * Check wether or not the User has changed. + * + * @return true if the current User is different, false otherwise + */ + public boolean hasUserChanged() { + + final String loginSubscriberId = getSubscriberIdForLogin(); + final String currentSuscriberId = SimCard.getSubscriberId(mContext); + + return !TextUtils.equals(loginSubscriberId, currentSuscriberId); + } + + /** + * Gets the Subscriber Id used to log in 360. + * + * @param databaseHelper the DatabaseHelper + * @return the Subscriber Id used to log in 360, null if there was a problem while retrieving it + */ + public String getSubscriberIdForLogin() { + + final LoginDetails mLoginDetails = new LoginDetails(); + final ServiceStatus mServiceStatus = mDatabaseHelper.fetchLogonCredentials(mLoginDetails); + + if (mServiceStatus == ServiceStatus.SUCCESS) { + return mLoginDetails.mSubscriberId; + } + + return null; + } + + /** + * @see SimStateReceiver.Listener#onSimReadyState() + */ + @Override + public void onSimReadyState() { + + processUserChanges(); + unregisterSimStateReceiver(); + } +} diff --git a/src/com/vodafone360/people/utils/SimCard.java b/src/com/vodafone360/people/utils/SimCard.java new file mode 100755 index 0000000..ebd7da9 --- /dev/null +++ b/src/com/vodafone360/people/utils/SimCard.java @@ -0,0 +1,313 @@ +package com.vodafone360.people.utils; + +import java.util.HashMap; +import java.util.Map; + +import android.content.Context; +import android.telephony.TelephonyManager; + +/** + * The SimCard class provides utility methods to access SIM card data. + */ +public class SimCard { + + /** + * Digits beyond this count will be replaced by 0. + */ + private static final int ANONYMISED_DIGITS = 4; + + /** + * The Network. + */ + public enum Network { + + CH("ch", 41), // Switzerland + DE("de", 49), // Germany + FR("fr", 33), // France + GB("gb", 44), // Great Britain + IE("ie", 353), // Ireland + IT("it", 39), // Italy + NL("nl", 31), // Netherlands + SE("se", 46), // Sweden + TR("tr", 90), // Turkey + TW("tw", 886), // Taiwan + US("us", 1), // United States + ES("es", 34), // Spain + // ZA("za", 260), //Zambia/VodaCom-SA?? + UNKNOWN("unknown", 0); + + private final String mIso; + + private final int mPrefix; + + private Network(String iso, int prefix) { + mIso = iso; + mPrefix = prefix; + } + + private Network() { + mIso = null; + mPrefix = -1; + } + + public String iso() { + return mIso; + } + + protected int prefix() { + return mPrefix; + } + + /*** + * Returns the SimNetwork of a given ISO if known + * + * @param iso Country ISO value. + * @return SimNetwork or SimNetwork.UNKNOWN if not found. + */ + public static Network getNetwork(String iso) { + for (final Network network : Network.values()) { + if (network.iso().equals(iso)) { + return network; + } + } + return UNKNOWN; + } + } + + /** + * SIM card absent state. + * @see #getSubscriberId(Context) + */ + public final static String SIM_CARD_ABSENT = "SimAbsent"; + + /** + * SIM card not readable state. + * @see #getSubscriberId(Context) + */ + public final static String SIM_CARD_NOT_READABLE = "SimNotReadable"; + + /** + * Gets the SIM card state. + * + * @see TelephonyManager#getSimState() + * + * @param context the application context + * @return the SIM card state + */ + public static int getState(Context context) { + + try { + + final TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); + + return telephonyManager.getSimState(); + + } catch (final Exception e) { + LogUtils.logE("SimCard.getState() - Exception:", e); + } + + return TelephonyManager.SIM_STATE_UNKNOWN; + } + + /** + * Tells whether or not the SIM card is present. + * + * @param context the + * @return true if the SIM is ready, false otherwise (not ready or absent) + */ + public static boolean isSimReady(Context context) { + + return getState(context) == TelephonyManager.SIM_STATE_READY; + } + + /** + * Gets the Subscriber Id. + * + * @see SIM_CARD_NOT_READABLE + * @see SIM_CARD_ABSENT + * + * @param databaseHelper the DatabaseHelper + * @return the Subscriber Id or SIM_CARD_ABSENT or SIM_CARD_NOT_READABLE + */ + public static String getSubscriberId(Context context) { + + if (getState(context) == TelephonyManager.SIM_STATE_ABSENT) { + + return SIM_CARD_ABSENT; + + } else { + + try { + + final TelephonyManager mTelephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); + + return mTelephonyManager.getSubscriberId(); + + } catch (final Exception e) { + + LogUtils.logE("SimCard.getSubscriberId() - Exception: "+e); + } + } + return SIM_CARD_NOT_READABLE; + } + + /** + * Logs a MSISDN validation failure event to Flurry. + * + * @param context Android context. + * @param workflow Given work flow (either sign in or sign up). + * @param status Current status string. + * @param enteredMsisdn User provided MSISDN. + */ + public static void logMsisdnValidationFail(Context context, String workflow, String status, + String enteredMsisdn) { + final TelephonyManager telephonyManager = (TelephonyManager)context + .getSystemService(Context.TELEPHONY_SERVICE); + final Map<String, String> map = new HashMap<String, String>(); + map.put("NetworkCountryIso", telephonyManager.getNetworkCountryIso()); + map.put("NetworkOperator", telephonyManager.getNetworkOperator()); + map.put("NetworkOperatorName", telephonyManager.getNetworkOperatorName()); + map.put("SimCountryIso", telephonyManager.getSimCountryIso()); + map.put("SimOperator", telephonyManager.getSimOperator()); + map.put("SimOperatorName", telephonyManager.getSimOperatorName()); + map.put("AnonymisedMsisdn", getAnonymisedMsisdn(telephonyManager.getLine1Number())); + map.put("AnonymisedEntereddMsisdn", getAnonymisedMsisdn(enteredMsisdn)); + map.put("Workflow", workflow); + map.put("Error", status); + // FlurryAgent.onEvent("EnterMobileNumberActivity_FAIL", map); + + LogUtils.logV("SimUtils.logMsisdnValidationFail() enteredMsisdn[" + enteredMsisdn + "]"); + } + + /** + * Retrieves the full international MSISDN number from the SIM or NULL if + * unavailable or unsure. Note: This functionality is currently part of + * SignupEnterMobileNumberActivity so anonymised data can be sent back to + * Flurry, in order to verify this program logic on multiple SIMs. + * + * @param context Android Context + * @return Full international MSISDN, or NULL if unsure of conversion. + */ + public static String getFullMsisdn(Context context) { + final TelephonyManager telephonyManager = (TelephonyManager)context + .getSystemService(Context.TELEPHONY_SERVICE); + final String rawMsisdn = telephonyManager.getLine1Number(); + final String verifyedMsisdn = getVerifyedMsisdn(rawMsisdn, telephonyManager + .getNetworkCountryIso(), telephonyManager.getNetworkOperatorName(), + telephonyManager.getNetworkOperator()); + final Map<String, String> map = new HashMap<String, String>(); + map.put("NetworkCountryIso", telephonyManager.getNetworkCountryIso()); + map.put("NetworkOperator", telephonyManager.getNetworkOperator()); + map.put("NetworkOperatorName", telephonyManager.getNetworkOperatorName()); + map.put("SimCountryIso", telephonyManager.getSimCountryIso()); + map.put("SimOperator", telephonyManager.getSimOperator()); + map.put("SimOperatorName", telephonyManager.getSimOperatorName()); + map.put("AnonymisedMsisdn", getAnonymisedMsisdn(rawMsisdn)); + map.put("AnonymisedVerifyedMsisdn", getAnonymisedMsisdn(verifyedMsisdn)); + // FlurryAgent.onEvent("EnterMobileNumberActivity", map); + return verifyedMsisdn; + } + + /*** + * Convert raw MSISDN to a verified MSISDN with country code. + * + * @param rawMsisdn Unverified MSISDN. + * @param countryIso Country ISO value from the SIM. + * @param networkOperatorName Network operator name value from the SIM. + * @param networkOperator Network operator value from the SIM. + * @return Verified MSISDN, or "" if NULL or unsure of country code. + */ + public static String getVerifyedMsisdn(String rawMsisdn, String countryIso, + String networkOperatorName, String networkOperator) { + if (rawMsisdn == null || rawMsisdn.trim().equals("")) { + // Reject any NULL or empty values. + return ""; + + } else if (rawMsisdn.substring(0, 1).equals("+")) { + // Accept any values starting with "+". + return rawMsisdn; +// the MTS Russian SIM may have just "8" as a rawNsisdn string + } else if (rawMsisdn.length() > 1 && (rawMsisdn.substring(0, 2).equals("00"))) { + // Accept any values starting with "00", but at +. + return "+" + rawMsisdn.substring(2); + + } else if (countryIso != null && !countryIso.trim().equals("")) { + // Filter known values: + try { + final Network simNetwork = Network.getNetwork(countryIso); + if (simNetwork != Network.UNKNOWN) { + return "+" + smartAdd(simNetwork.prefix() + "", dropZero(rawMsisdn)); + } else { + // Rejected + return ""; + } + + } catch (final NumberFormatException e) { + // Rejected + return ""; + } + + } else { + // Rejected + return ""; + } + } + + /*** + * Concatenate the "start" value with the "end" value, except where the + * "start" value is already in place. + * + * @param start First part of String. + * @param end Last part of String. + * @return "start" + "end". + */ + private static String smartAdd(String start, String end) { + if (end == null || end.trim().equals("")) { + return ""; + } else if (end.startsWith(start)) { + return end; + } else { + return start + end; + } + } + + /*** + * Remove the preceding zero, if present. + * + * @param rawMsisdn Number to alter. + * @return Number without the zero. + */ + private static String dropZero(String rawMsisdn) { + if (rawMsisdn == null || rawMsisdn.trim().equals("")) { + return ""; + } else if (rawMsisdn.startsWith("0")) { + return rawMsisdn.substring(1); + } else { + return rawMsisdn; + } + } + + /*** + * Converts an identifiable MSISDN value to something that can be sent via a + * third party. E.g. "+49123456789" becomes "+49100000000". + * + * @param input Private MSISDN. + * @return Anonymous MSISDN. + */ + public static String getAnonymisedMsisdn(String input) { + if (input == null || input.trim().equals("")) { + return ""; + } else { + final int length = input.length(); + final StringBuffer result = new StringBuffer(); + for (int i = 0; i < length; i++) { + if (i < ANONYMISED_DIGITS) { + result.append(input.charAt(i)); + } else { + result.append("0"); + } + } + return result.toString(); + } + } +}
360/360-Engine-for-Android
f0fbb235b22d796986c1a7dc01a1ff356e819dd8
PAND-2360 code review clean up
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 485bca2..4935008 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,708 +1,708 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.identities; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import android.os.Bundle; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Identities; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.ThirdPartyAccount; /** * Engine responsible for handling retrieval and validation of Identities (e.g. * 3rd party/web accounts). The Identities engine can fetch a list of available * accounts, and set required capabilities and validate credentials for * specified accounts. */ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { /** * States for IdentitiesEngine. States are based on the requests that the * engine needs to handle. */ private enum State { IDLE, FETCHING_IDENTITIES, VALIDATING_IDENTITY_CREDENTIALS, SETTING_IDENTITY_STATUS, GETTING_MY_IDENTITIES, GETTING_MY_CHATABLE_IDENTITIES, DELETE_IDENTITY } /** * Mutex for thread synchronisation */ private final Object mMutex = new Object(); /** * Container class for Identity Capability Status request. Consists of a * network, identity id and a filter containing the required capabilities. */ private static class IdentityStatusRequest { private String mNetwork; private String mIdentityId; private String mIdentityStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setIdentityStatus(String status) { mIdentityStatus = status; } } /** * Container class encapsulating an Identity validation request containing: * dry-run flag, network, user-name, password, set of required capabilities. */ private static class IdentityValidateCredentialsRequest { /** Performs a dry run if true. */ private boolean mDryRun; /** Network to sign into. */ private String mNetwork; /** Username to sign into identity with. */ private String mUserName; /** Password to sign into identity with. */ private String mPassword; private Map<String, Boolean> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } /** * * Container class for Delete Identity request. Consist network and identity id. * */ private static class DeleteIdentityRequest { /** Network to delete.*/ private String mNetwork; /** IdentityID which needs to be Deleted.*/ private String mIdentityId; } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mMyIdentityList; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; /** * Maintaining DeleteIdentityRequest so that it can be later removed from * maintained cache. **/ private DeleteIdentityRequest identityToBeDeleted; /** * The hard coded list of capabilities we use to getAvailable~/MyIdentities(): chat and status. */ private final Map<String, List<String>> mCapabilitiesFilter; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; mMyIdentityList = new ArrayList<Identity>(); mAvailableIdentityList = new ArrayList<Identity>(); mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; // initialize identity capabilities filter mCapabilitiesFilter = new Hashtable<String, List<String>>(); final List<String> capabilities = new ArrayList<String>(); capabilities.add(IdentityCapability.CapabilityID.chat.name()); capabilities.add(IdentityCapability.CapabilityID.get_own_status.name()); - mCapabilitiesFilter.put("capability", capabilities); + mCapabilitiesFilter.put(Identities.CAPABILITY, capabilities); } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { final ArrayList<Identity> availableIdentityList; synchronized(mAvailableIdentityList) { // make a shallow copy availableIdentityList = new ArrayList<Identity>(mAvailableIdentityList); } if ((availableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return availableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { final ArrayList<Identity> myIdentityList; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } if ((myIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return myIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = getMyThirdPartyChattableIdentities(); // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chattableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chattableIdentities; } /** * * Takes all third party identities that have a chat capability set to true. * * @return A list of chattable 3rd party identities the user is signed in to. If the retrieval identities failed the returned list will be empty. * */ public ArrayList<Identity> getMyThirdPartyChattableIdentities() { final ArrayList<Identity> chattableIdentities = new ArrayList<Identity>(); final ArrayList<Identity> myIdentityList; final int identityListSize; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } identityListSize = myIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = myIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue)) { chattableIdentities.add(identity); break; } } } return chattableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, mCapabilitiesFilter); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, mCapabilitiesFilter); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * TODO: re-factor the method in the way that the UI doesn't pass the Bundle with capabilities * list to the Engine, but the Engine makes the list itself (UI/Engine separation). * * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Delete the given social network. * * @param network Name of the identity, * @param identityId Id of identity. */ public final void addUiDeleteIdentityRequest(final String network, final String identityId) { LogUtils.logD("IdentityEngine.addUiRemoveIdentity()"); DeleteIdentityRequest data = new DeleteIdentityRequest(); data.mNetwork = network; data.mIdentityId = identityId; /**maintaining the sent object*/ setIdentityToBeDeleted(data); addUiRequestToQueue(ServiceUiRequest.DELETE_IDENTITY, data); } /** * Setting the DeleteIdentityRequest object. * * @param data */ private void setIdentityToBeDeleted(final DeleteIdentityRequest data) { identityToBeDeleted = data; } /** * Return the DeleteIdentityRequest object. * */ private DeleteIdentityRequest getIdentityToBeDeleted() { return identityToBeDeleted; } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case GET_MY_IDENTITIES: sendGetMyIdentitiesRequest(); completeUiRequest(ServiceStatus.SUCCESS); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; case DELETE_IDENTITY: executeDeleteIdentityRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to delete the identity as specified . (Request is not issued if there * is currently no connectivity). * * @param data bundled request data containing network and identityId. */ private void executeDeleteIdentityRequest(final Object data) { if (!isConnected()) { completeUiRequest(ServiceStatus.ERROR_NO_INTERNET); } newState(State.DELETE_IDENTITY); DeleteIdentityRequest reqData = (DeleteIdentityRequest) data; if (!setReqId(Identities.deleteIdentity(this, reqData.mNetwork, reqData.mIdentityId))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(DecodedResponse resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if ((null == resp) || (null == resp.mDataTypes)) { LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); return; } // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; case BaseDataType.IDENTITY_DELETION_DATA_TYPE: handleDeleteIdentity(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); } } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { Identity identity = (Identity)item; mMyIdentityList.add(identity); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } diff --git a/src/com/vodafone360/people/service/io/api/Identities.java b/src/com/vodafone360/people/service/io/api/Identities.java index 486a2ce..8b91517 100644 --- a/src/com/vodafone360/people/service/io/api/Identities.java +++ b/src/com/vodafone360/people/service/io/api/Identities.java @@ -1,262 +1,262 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io.api; import java.util.Hashtable; import java.util.List; import java.util.Map; import com.vodafone360.people.Settings; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.utils.LogUtils; /** * Implementation of Now+ Identities APIs (used for access to 3rd party accounts * such as Facebook). */ public class Identities { private final static String FUNCTION_GET_AVAILABLE_IDENTITIES = "identities/getavailableidentities"; private final static String FUNCTION_GET_MY_IDENTITIES = "identities/getmyidentities"; // AA private final static String FUNCTION_SET_IDENTITY_CAPABILITY_STATUS = // "identities/setidentitycapabilitystatus"; private final static String FUNCTION_SET_IDENTITY_STATUS = "identities/setidentitystatus"; private final static String FUNCTION_VALIDATE_IDENTITY_CREDENTIALS = "identities/validateidentitycredentials"; private final static String FUNCTION_DELETE_IDENITY = "identities/deleteidentity"; public final static String ENABLE_IDENTITY = "enable"; public final static String DISABLE_IDENTITY = "disable"; - //public final static String SUSPENDED_IDENTITY = "suspended"; + public final static String CAPABILITY = "capability"; /** * Implementation of identities/getavailableidentities API. Parameters are; * [auth], Map<String, List<String>> filterlist [opt] * * @param engine handle to IdentitiesEngine * @param filterlist List of filters the get identities request is filtered * against. * @return request id generated for this request */ public static int getAvailableIdentities(BaseEngine engine, Map<String, List<String>> filterlist) { if (LoginEngine.getSession() == null) { LogUtils.logE("Identities.getAvailableIdentities() Invalid session, return -1"); return -1; } Request request = new Request(FUNCTION_GET_AVAILABLE_IDENTITIES, Request.Type.GET_AVAILABLE_IDENTITIES, engine.engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); if (filterlist != null) { request.addData("filterlist", ApiUtils.createHashTable(filterlist)); } QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } /** * Implementation of identities/getmyidentities API. Parameters are; [auth], * Map<String, List<String>> filterlist [opt] * * @param engine handle to IdentitiesEngine * @param filterlist List of filters the get identities request is filtered * against. * @return request id generated for this request */ public static int getMyIdentities(BaseEngine engine, Map<String, List<String>> filterlist) { if (LoginEngine.getSession() == null) { LogUtils.logE("Identities.getMyIdentities() Invalid session, return -1"); return -1; } Request request = new Request(FUNCTION_GET_MY_IDENTITIES, Request.Type.GET_MY_IDENTITIES, engine .engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); if (filterlist != null) { request.addData("filterlist", ApiUtils.createHashTable(filterlist)); } QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } /** * @param engine * @param network * @param identityid * @param identityStatus * @return */ public static int setIdentityStatus(BaseEngine engine, String network, String identityid, String identityStatus) { if (LoginEngine.getSession() == null) { LogUtils.logE("Identities.setIdentityStatus() Invalid session, return -1"); return -1; } if (identityid == null) { LogUtils.logE("Identities.setIdentityStatus() identityid cannot be NULL"); return -1; } if (network == null) { LogUtils.logE("Identities.setIdentityStatus() network cannot be NULL"); return -1; } if (identityStatus == null) { LogUtils.logE("Identities.setIdentityStatus() identity status cannot be NULL"); return -1; } Request request = new Request(FUNCTION_SET_IDENTITY_STATUS, Request.Type.EXPECTING_STATUS_ONLY, engine.engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); request.addData("network", network); request.addData("identityid", identityid); request.addData("status", identityStatus); QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } /** * Implementation of identities/validateidentitycredentials API. Parameters * are; [auth], Boolean dryrun [opt], String network [opt], String username, * String password, String server [opt], String contactdetail [opt], Map * identitycapabilitystatus [opt] * * @param engine handle to IdentitiesEngine * @param dryrun Whether this is a dry-run request. * @param network Name of network. * @param username User-name. * @param password Password. * @param server * @param contactdetail * @param identitycapabilitystatus Capabilities for this identity/network. * @return request id generated for this request */ public static int validateIdentityCredentials(BaseEngine engine, Boolean dryrun, String network, String username, String password, String server, String contactdetail, Map<String, Boolean> identitycapabilitystatus) { if (LoginEngine.getSession() == null) { LogUtils.logE("Identities.validateIdentityCredentials() Invalid session, return -1"); return -1; } if (network == null) { LogUtils.logE("Identities.validateIdentityCredentials() network cannot be NULL"); return -1; } if (username == null) { LogUtils.logE("Identities.validateIdentityCredentials() username cannot be NULL"); return -1; } if (password == null) { LogUtils.logE("Identities.validateIdentityCredentials() password cannot be NULL"); return -1; } Request request = new Request(FUNCTION_VALIDATE_IDENTITY_CREDENTIALS, Request.Type.EXPECTING_STATUS_ONLY, engine.engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); if (dryrun != null) { request.addData("dryrun", dryrun); } request.addData("network", network); request.addData("username", username); request.addData("password", password); if (server != null) { request.addData("server", server); } if (contactdetail != null) { request.addData("contactdetail", contactdetail); } if (identitycapabilitystatus != null) { request.addData("identitycapabilitystatus", new Hashtable<String, Object>( identitycapabilitystatus)); } QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } /** * Implementation of identities/deleteIdentity API. Parameters are; [auth], * String network, String identityid. * * @param engine * Handle to IdentitiesEngine. * @param network * Name of network. * @param identityId * The user's identity ID. * @return requestId The request ID generated for this request. */ public static int deleteIdentity(final BaseEngine engine, final String network, final String identityId) { if (LoginEngine.getSession() == null) { LogUtils .logE("Identities.deleteIdentity() Invalid session, return -1"); return -1; } if (network == null) { LogUtils.logE("Identities.deleteIdentity() network cannot be NULL"); return -1; } if (identityId == null) { LogUtils .logE("Identities.deleteIdentity() identityId cannot be NULL"); return -1; } Request request = new Request(FUNCTION_DELETE_IDENITY, Request.Type.DELETE_IDENTITY, engine.engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); request.addData("network", network); request.addData("identityid", identityId); LogUtils.logI("Identity to be removed : " + network + " : " + identityId); QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } }
360/360-Engine-for-Android
2e04410bf3e917b2413a8c772405d7a72577a146
PAND-2393 clean up and follow up the code review
diff --git a/src/com/vodafone360/people/MainApplication.java b/src/com/vodafone360/people/MainApplication.java index 52fa37d..eb50113 100644 --- a/src/com/vodafone360/people/MainApplication.java +++ b/src/com/vodafone360/people/MainApplication.java @@ -1,245 +1,240 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import android.app.Application; import android.os.Handler; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.service.PersistSettings; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.interfaces.IPeopleService; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.LoginPreferences; import com.vodafone360.people.utils.WidgetUtils; /** * Application class used to create the connection to the service and cache * state between Activities. */ public class MainApplication extends Application { private IPeopleService mServiceInterface; private Handler mServiceLoadedHandler; private DatabaseHelper mDatabaseHelper; private final ApplicationCache mApplicationCache = new ApplicationCache(); /** * Called when the Application is created. */ @Override public void onCreate() { super.onCreate(); SettingsManager.loadProperties(this); mDatabaseHelper = new DatabaseHelper(this); mDatabaseHelper.start(); LoginPreferences.getCurrentLoginActivity(this); } /** * Called when the Application is exited. */ @Override public void onTerminate() { // FlurryAgent.onEndSession(this); if (mDatabaseHelper != null) { mDatabaseHelper.close(); } super.onTerminate(); } /** * Return handle to DatabaseHelper, currently provides main point of access * to People client's database tables. * * @return Handle to DatabaseHelper. */ public DatabaseHelper getDatabase() { return mDatabaseHelper; } /** * Return handle to ApplicationCache. * * @return handle to ApplicationCache. */ public ApplicationCache getCache() { return mApplicationCache; } /** * Remove all user data from People client, this includes all account * information (downloaded contacts, login credentials etc.) and all cached * settings. */ public synchronized void removeUserData() { EngineManager mEngineManager = EngineManager.getInstance(); if (mEngineManager != null) { // Resets all the engines, the call will block until every engines // have been reset. mEngineManager.resetAllEngines(); } // Remove NAB Account at this point (does nothing on 1.X) NativeContactsApi.getInstance().removePeopleAccount(); // the same action as in NetworkSettingsActivity onChecked() setInternetAvail(InternetAvail.ALWAYS_CONNECT, false); mDatabaseHelper.removeUserData(); // Before clearing the Application cache, kick the widget update. Pref's // file contain the widget ID. WidgetUtils.kickWidgetUpdateNow(this); mApplicationCache.clearCachedData(this); } /** * Register a Handler to receive notification when the People service has * loaded. If mServiceInterface == NULL then this means that the UI is * starting before the service has loaded - in this case the UI registers to * be notified when the service is loaded using the serviceLoadedHandler. * TODO: consider any pitfalls in this situation. * * @param serviceLoadedHandler Handler that receives notification of service * being loaded. */ public synchronized void registerServiceLoadHandler(Handler serviceLoadedHandler) { if (mServiceInterface != null) { onServiceLoaded(); } else { mServiceLoadedHandler = serviceLoadedHandler; LogUtils.logI("MainApplication.registerServiceLoadHandler() mServiceInterface is NULL " + "- need to wait for service to be loaded"); } } /** * Un-register People service loading handler. */ public synchronized void unRegisterServiceLoadHandler() { mServiceLoadedHandler = null; } private void onServiceLoaded() { if (mServiceLoadedHandler != null) { mServiceLoadedHandler.sendEmptyMessage(0); } } /** * Set IPeopleService interface - this is the interface by which we * interface to People service. * * @param serviceInterface IPeopleService handle. */ public synchronized void setServiceInterface(IPeopleService serviceInterface) { if (serviceInterface == null) { LogUtils.logE("MainApplication.setServiceInterface() " + "New serviceInterface should not be NULL"); } mServiceInterface = serviceInterface; onServiceLoaded(); } /** * Return current IPeopleService interface. TODO: The case where * mServiceInterface = NULL needs to be considered. * * @return current IPeopleService interface (can be null). */ public synchronized IPeopleService getServiceInterface() { if (mServiceInterface == null) { LogUtils.logE("MainApplication.getServiceInterface() " + "mServiceInterface should not be NULL"); } return mServiceInterface; } /** * Set Internet availability - always makes Internet available, only * available in home network, allow manual connection only. This setting is * stored in People database. * * @param internetAvail Internet availability setting. * @param forwardToSyncAdapter TRUE if the SyncAdater needs to know about the changes, FALSE otherwise * @return SerivceStatus indicating whether the Internet availability * setting has been successfully updated in the database. */ public ServiceStatus setInternetAvail(InternetAvail internetAvail, boolean forwardToSyncAdapter) { - if(getInternetAvail() == internetAvail) { - // FIXME: This is a hack in order to set the system auto sync on/off depending on our data settings - if (forwardToSyncAdapter) { - NativeContactsApi.getInstance().setSyncAutomatically(internetAvail == InternetAvail.ALWAYS_CONNECT); - } + if (getInternetAvail() == internetAvail) { return ServiceStatus.SUCCESS; } if(internetAvail == InternetAvail.ALWAYS_CONNECT && !NativeContactsApi.getInstance().getMasterSyncAutomatically()) { // FIXME: Perhaps an abusive use of this error code for when // Master Sync Automatically is OFF, should have a different LogUtils.logW("ServiceStatus.setInternetAvail() [master sync is off]"); return ServiceStatus.ERROR_NO_AUTO_CONNECT; } PersistSettings mPersistSettings = new PersistSettings(); mPersistSettings.putInternetAvail(internetAvail); ServiceStatus ss = mDatabaseHelper.setOption(mPersistSettings); // FIXME: This is a hack in order to set the system auto sync on/off depending on our data settings if (forwardToSyncAdapter) { NativeContactsApi.getInstance().setSyncAutomatically(internetAvail == InternetAvail.ALWAYS_CONNECT); } synchronized (this) { if (mServiceInterface != null) { mServiceInterface.notifyDataSettingChanged(internetAvail); } else { LogUtils.logE("MainApplication.setInternetAvail() " + "mServiceInterface should not be NULL"); } } return ss; } /** * Retrieve Internet availability setting from People database. * * @return current Internet availability setting. */ - public synchronized InternetAvail getInternetAvail() { - InternetAvail internetAvail = mDatabaseHelper.fetchOption(PersistSettings.Option.INTERNETAVAIL).getInternetAvail(); - return internetAvail; + public InternetAvail getInternetAvail() { + return mDatabaseHelper.fetchOption(PersistSettings.Option.INTERNETAVAIL).getInternetAvail(); } } diff --git a/src/com/vodafone360/people/service/PersistSettings.java b/src/com/vodafone360/people/service/PersistSettings.java index 1c5b379..352b6d9 100644 --- a/src/com/vodafone360/people/service/PersistSettings.java +++ b/src/com/vodafone360/people/service/PersistSettings.java @@ -1,484 +1,478 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import android.content.ContentValues; import android.database.Cursor; import android.os.Parcel; import android.os.Parcelable; /** * Class responsible for handling persistent settings within the People client. * These settings are stored in the State table in the People client's database. */ public class PersistSettings implements Parcelable { // These two member variables must never be null private Option mOption = Option.INTERNETAVAIL; private Object mValue = InternetAvail.ALWAYS_CONNECT; /** * Constructor */ public PersistSettings() { putDefaultOptionData(); } /** * Internet availability settings, options are always connect or only allow * manual connection */ public static enum InternetAvail { ALWAYS_CONNECT, MANUAL_CONNECT; } /** * Definition for Settings type (boolean, string, integer, long). */ public static enum OptionType { BOOLEAN("BOOLEAN"), STRING("STRING"), INTEGER("INTEGER"), LONG("LONG"); /** Field name as stored in State table. */ private String mDbType = null; /** * OptionType constructor. * * @param dbType State table record name for current item. */ private OptionType(String dbType) { mDbType = dbType; } /** * Return the State table field name for this item. * * @return String containing State table field name for this item. */ public String getDbType() { return mDbType; } }; /** * Definition of a set of options handled by PersistSettings. These options * are; Internet availability (always available, only in home network or * manually activated) First time contact sync status. First time native * contact sync status. */ public static enum Option { - // Note: Currently it is crucial that default value for Option - // INTERNETAVAIL remains MANUAL_CONNECT. The LandingPageActivity - // sets the value to ALWAYS_CONNECT in its onCreate() method - // before login and triggers the correct computation of the - // AgentState in the NetworkAgentState class. For details see - // PAND-2305. INTERNETAVAIL("internetavail", OptionType.INTEGER, InternetAvail.ALWAYS_CONNECT.ordinal()), FIRST_TIME_SYNC_STARTED("ftsstarted", OptionType.BOOLEAN, false), FIRST_TIME_MESYNC_STARTED("ftmesyncstarted", OptionType.BOOLEAN, false), FIRST_TIME_SYNC_COMPLETE("ftscomplete", OptionType.BOOLEAN, false), FIRST_TIME_MESYNC_COMPLETE("ftmesynccomplete", OptionType.BOOLEAN, false), FIRST_TIME_NATIVE_SYNC_COMPLETE("ftnativecomplete", OptionType.BOOLEAN, false); private String mFieldName; private Object mDefaultValue; private OptionType mType; /** * Constructor * * @param fieldName Name of setting item. * @param type Type of field (String, boolean, integer, long). * @param defaultValue Default value for item. */ private Option(String fieldName, OptionType type, Object defaultValue) { mFieldName = fieldName; mType = type; mDefaultValue = defaultValue; } /** * Return the default value for current setting. * * @return the default value for current setting. */ public Object defaultValue() { return mDefaultValue; } /** * Return the type of current option (i.e. String, boolean, integer, * long). * * @return type of current option. */ public OptionType getType() { return mType; } @Override public String toString() { return "\nOption info:\nID = " + super.toString() + "\n" + "TableFieldName = " + mFieldName + "\n" + "Type: " + mType + "\n" + "Default: " + mDefaultValue + "\n"; } /** * Search for settings item by name. * * @param key Option name to search for. * @return Option item, null if item not found. */ private static Option lookupValue(String key) { for (Option option : Option.values()) { if (key.equals(option.mFieldName)) { return option; } } return null; } /** * Option's State table record name * * @return Name of the State table field corresponding to this Option. */ public String tableFieldName() { return mFieldName; } } /** {@inheritDoc} */ @Override public String toString() { return "Option: " + mOption.tableFieldName() + ", Value: " + mValue; } /** * Return the default (boolean) value for supplied Option. * * @param option Option * @return default boolean value for specified Option or false if if the * default value is null or not a boolean. */ private static boolean getDefaultBoolean(Option option) { if (option.defaultValue() != null && option.defaultValue().getClass().equals(Boolean.class)) { return (Boolean)option.defaultValue(); } return false; } /** * Return the default (integer) value for supplied Option. * * @param option Option * @return default integer value for specified Option or false if if the * default value is null or not a integer. */ private static int getDefaultInt(Option option) { if (option.defaultValue() != null && option.defaultValue().getClass().equals(Integer.class)) { return (Integer)option.defaultValue(); } return 0; } /** * Set the default value stored in PersistDettings for specified Option. * * @param option Option the default value held by PersistSettings is the * value set in the supplied Option. */ public void putDefaultOptionData(Option option) { if (option != null) { mOption = option; putDefaultOptionData(); } } /** * Set the default value stored in PersistDettings for current Option. */ public void putDefaultOptionData() { mValue = mOption.mDefaultValue; } /** * Set the default value for the specified Option * * @param option Option to set default data for. * @param data Value for default setting. */ public void putOptionData(Option option, Object data) { mOption = option; if (data != null) { mValue = data; } else { putDefaultOptionData(); } } /** * Add setting from supplied PersistSettings instance to supplied * ContentValues instance. * * @param contentValues ContentValue to update. * @param setting PersistSettings instance containing settings value. * @return true (cannot return false!). */ public static boolean addToContentValues(ContentValues contentValues, PersistSettings setting) { PersistSettings.Option option = setting.getOption(); switch (option.getType()) { case BOOLEAN: contentValues.put(option.tableFieldName(), (Boolean)setting.getValue()); break; case STRING: contentValues.put(option.tableFieldName(), (String)setting.getValue()); break; case INTEGER: contentValues.put(option.tableFieldName(), (Integer)setting.getValue()); break; case LONG: contentValues.put(option.tableFieldName(), (Long)setting.getValue()); break; default: contentValues.put(option.tableFieldName(), setting.getValue().toString()); break; } return true; } /** * Fetch Object from database Cursor. * * @param c Database Cursor pointing to item of interest. * @param colIndex Column index within item. * @param key Key used to obtain required Option item. * @return Value obtained for Cursor, null if option does not exist or key * does not match valid Option. */ public static Object fetchValueFromCursor(Cursor c, int colIndex, String key) { PersistSettings.Option option = PersistSettings.Option.lookupValue(key); if (option == null || c.isNull(colIndex)) { return null; } switch (option.getType()) { case BOOLEAN: return (c.getInt(colIndex) == 0 ? false : true); case STRING: return c.getString(colIndex); case INTEGER: return c.getInt(colIndex); case LONG: return c.getLong(colIndex); default: return c.getString(colIndex); } } /** * Set Internet availability value. * * @param value InternetAvail. */ public void putInternetAvail(InternetAvail value) { mOption = Option.INTERNETAVAIL; if (value != null) { mValue = (Integer)value.ordinal(); } else { mValue = InternetAvail.values()[getDefaultInt(mOption)]; } } /** * Get current InternetAvail value * * @return current InternetAvail value. */ public InternetAvail getInternetAvail() { if (mOption == Option.INTERNETAVAIL && mValue.getClass().equals(Integer.class)) { int val = (Integer)mValue; if (val < InternetAvail.values().length) { return InternetAvail.values()[val]; } } return InternetAvail.values()[getDefaultInt(Option.INTERNETAVAIL)]; } /** * Return value indicating whether first time native contact sync has * completed. * * @return stored boolean value indicating whether first time native contact * sync has completed. */ public boolean getFirstTimeNativeSyncComplete() { if (mOption == Option.FIRST_TIME_NATIVE_SYNC_COMPLETE && mValue.getClass().equals(Boolean.class)) { return (Boolean)mValue; } return getDefaultBoolean(Option.FIRST_TIME_NATIVE_SYNC_COMPLETE); } /** * Store value indicating whether first time native contact sync has * completed. * * @param value value indicating whether first time native contact sync has * completed. */ public void putFirstTimeNativeSyncComplete(boolean value) { mOption = Option.FIRST_TIME_NATIVE_SYNC_COMPLETE; mValue = (Boolean)value; } /** * Store value indicating whether first time contact sync has completed. * * @param value value indicating whether first time native contact sync has * completed. */ public void putFirstTimeSyncComplete(boolean value) { mOption = Option.FIRST_TIME_SYNC_COMPLETE; mValue = (Boolean)value; } public void putFirstTimeMeSyncComplete(boolean value) { mOption = Option.FIRST_TIME_MESYNC_COMPLETE; mValue = (Boolean)value; } /** * Return value indicating whether first time native contact sync has * completed. * * @return value indicating whether first time native contact sync has * completed. */ public boolean getFirstTimeSyncComplete() { if (mOption == Option.FIRST_TIME_SYNC_COMPLETE && mValue.getClass().equals(Boolean.class)) { return (Boolean)mValue; } return getDefaultBoolean(Option.FIRST_TIME_SYNC_COMPLETE); } public boolean getFirstTimeMeSyncComplete() { if (mOption == Option.FIRST_TIME_MESYNC_COMPLETE && mValue.getClass().equals(Boolean.class)) { return (Boolean)mValue; } return getDefaultBoolean(Option.FIRST_TIME_MESYNC_COMPLETE); } /** * Store value indicating whether first time native contact sync has * started. * * @param value value indicating whether first time native contact sync has * started. */ public void putFirstTimeSyncStarted(boolean value) { mOption = Option.FIRST_TIME_SYNC_STARTED; mValue = (Boolean)value; } public void putFirstTimeMeSyncStarted(boolean value) { mOption = Option.FIRST_TIME_MESYNC_STARTED; mValue = (Boolean)value; } /** * Return value indicating whether first time native contact sync has * started. * * @return value indicating whether first time native contact sync has * started. */ public boolean getFirstTimeSyncStarted() { if (mOption == Option.FIRST_TIME_SYNC_STARTED && mValue.getClass().equals(Boolean.class)) { return (Boolean)mValue; } return getDefaultBoolean(Option.FIRST_TIME_SYNC_STARTED); } public boolean getFirstTimeMeSyncStarted() { if (mOption == Option.FIRST_TIME_MESYNC_STARTED && mValue.getClass().equals(Boolean.class)) { return (Boolean)mValue; } return getDefaultBoolean(Option.FIRST_TIME_MESYNC_STARTED); } /** * Get Option associated with this PersistSettings. * * @return Option associated with this PersistSettings. */ public Option getOption() { return mOption; } /** * Get value associated with this PersistSettings. * * @return Object representing value associated with this PersistSettings. */ private Object getValue() { return mValue; } /** {@inheritDoc} */ @Override public int describeContents() { return 0; } /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mOption.ordinal()); switch (mOption.getType()) { case BOOLEAN: dest.writeByte((byte)(((Boolean)mValue) ? 1 : 0)); break; case STRING: dest.writeString((String)mValue); break; case INTEGER: dest.writeInt((Integer)mValue); break; case LONG: dest.writeLong((Long)mValue); break; default: break; } } } diff --git a/src/com/vodafone360/people/service/SyncAdapter.java b/src/com/vodafone360/people/service/SyncAdapter.java index 16fdc90..e706f3d 100644 --- a/src/com/vodafone360/people/service/SyncAdapter.java +++ b/src/com/vodafone360/people/service/SyncAdapter.java @@ -1,304 +1,304 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import android.accounts.Account; import android.accounts.AccountManager; import android.content.AbstractThreadedSyncAdapter; import android.content.BroadcastReceiver; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SyncResult; import android.content.SyncStatusObserver; import android.os.Bundle; import android.os.Handler; import android.provider.ContactsContract; import com.vodafone360.people.MainApplication; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.utils.LogUtils; /** * SyncAdapter implementation which basically just ties in with * the old Contacts Sync Engine code for the moment and waits for the sync to be finished. * In the future we may want to improve this, particularly if the sync * is actually be done in this thread which would also enable disable sync altogether. */ public class SyncAdapter extends AbstractThreadedSyncAdapter implements IContactSyncObserver { // TODO: RE-ENABLE SYNC VIA SYSTEM // /** // * Direct access to Sync Engine stored for convenience // */ // private final ContactSyncEngine mSyncEngine = EngineManager.getInstance().getContactSyncEngine(); // // /** // * Boolean used to remember if we have requested a sync. // * Useful to ignore events // */ // private boolean mPerformSyncRequested = false; // /** * Delay when checking our Sync Setting when there is a authority auto-sync setting change. * This waiting time is necessary because in case it is our sync adapter authority setting * that changes we cannot query in the callback because the value is not yet changed! */ private static final int SYNC_SETTING_CHECK_DELAY = 2000; /** * Same as ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS * The reason we have this is just because the constant is not publicly defined before 2.2. */ private static final int SYNC_OBSERVER_TYPE_SETTINGS = 1; /** * Application object instance */ private final MainApplication mApplication; /** * Broadcast receiver used to listen for changes in the Master Auto Sync setting * intent: com.android.sync.SYNC_CONN_STATUS_CHANGED */ private final BroadcastReceiver mAutoSyncChangeBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { actOnAutoSyncSettings(); } }; /** * Observer for the global sync status setting. * There is no known way to only observe our sync adapter's setting. */ private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() { @Override public void onStatusChanged(int which) { mHandler.postDelayed(mRunnable, SYNC_SETTING_CHECK_DELAY); } }; /** * Handler used to post to a runnable in order to wait * for a short time before checking the sync adapter * authority sync setting after a global change occurs. */ private final Handler mHandler = new Handler(); /** * Runnable used to post to a runnable in order to wait * for a short time before checking the sync adapter * authority sync setting after a global change occurs. * The reason we use this kind of mechanism is because: * a) There is an intent(com.android.sync.SYNC_CONN_STATUS_CHANGED) * we can listen to for the Master Auto-sync but, * b) The authority auto-sync observer pattern using ContentResolver * listens to EVERY sync adapter setting on the device AND * when the callback is received the value is not yet changed so querying for it is useless. */ private final Runnable mRunnable = new Runnable() { @Override public void run() { actOnAutoSyncSettings(); } }; public SyncAdapter(Context context, MainApplication application) { // Automatically initialized (true) due to PAND-2304 super(context, true); mApplication = application; context.registerReceiver(mAutoSyncChangeBroadcastReceiver, new IntentFilter( "com.android.sync.SYNC_CONN_STATUS_CHANGED")); ContentResolver.addStatusChangeListener( SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver); // Necessary in case of Application update forceSyncSettingsInCaseOfAppUpdate(); // Register for sync event callbacks // TODO: RE-ENABLE SYNC VIA SYSTEM // mSyncEngine.addEventCallback(this); } /** * {@inheritDoc} */ @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { if(extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false)) { initialize(account, authority); return; } actOnAutoSyncSettings(); // TODO: RE-ENABLE SYNC VIA SYSTEM // try { // synchronized(this) { // mPerformSyncRequested = true; // if(!mSyncEngine.isSyncing()) { // mSyncEngine.startFullSync(); // } // // while(mSyncEngine.isSyncing()) { // wait(POOLING_WAIT_INTERVAL); // } // mPerformSyncRequested = false; // } // } catch (InterruptedException e) { // e.printStackTrace(); // } } /** * @see IContactSyncObserver#onContactSyncStateChange(Mode, State, State) */ @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { // TODO: RE-ENABLE SYNC VIA SYSTEM // synchronized(this) { // /* // * This check is done so that we can also update the native UI // * when the client devices to sync on it own // */ // if(!mPerformSyncRequested && // mode != Mode.NONE) { // mPerformSyncRequested = true; // Account account = new Account( // LoginPreferences.getUsername(), // NativeContactsApi2.PEOPLE_ACCOUNT_TYPE); // ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); // } // } } /** * @see IContactSyncObserver#onProgressEvent(State, int) */ @Override public void onProgressEvent(State currentState, int percent) { // Nothing to do } /** * @see IContactSyncObserver#onSyncComplete(ServiceStatus) */ @Override public void onSyncComplete(ServiceStatus status) { // Nothing to do } /** * Initializes Sync settings for this Sync Adapter * @param account The account associated with the initialization * @param authority The authority of the content */ public static void initialize(Account account, String authority) { ContentResolver.setIsSyncable(account, authority, 1); // > 0 means syncable ContentResolver.setSyncAutomatically(account, authority, true); } /** * Checks if this Sync Adapter is allowed to Sync Automatically * Basically just checking if the Master and its own Auto-sync are on. * The Master Auto-sync takes precedence over the authority Auto-sync. * @return true if the settings are enabled, false otherwise */ private boolean canSyncAutomatically() { Account account = getPeopleAccount(); if (account == null) { // There's no account in the system anyway so // just say true to avoid any issues with the application. return true; } boolean masterSyncAuto = ContentResolver.getMasterSyncAutomatically(); boolean syncAuto = ContentResolver.getSyncAutomatically(account, ContactsContract.AUTHORITY); - LogUtils.logE("SyncAdapter.canSyncAutomatically() [masterSync=" + + LogUtils.logD("SyncAdapter.canSyncAutomatically() [masterSync=" + masterSyncAuto + ", syncAuto=" + syncAuto + "]"); return masterSyncAuto && syncAuto; } /** * Sets the application data connection setting depending on whether or not * the Sync Adapter is allowed to Sync Automatically. * If Automatic Sync is enabled then connection is to online ("always connect") * Otherwise connection is set to offline ("manual connect") */ private synchronized void actOnAutoSyncSettings() { if(canSyncAutomatically()) { // Enable data connection mApplication.setInternetAvail(InternetAvail.ALWAYS_CONNECT, false); } else { // Disable data connection mApplication.setInternetAvail(InternetAvail.MANUAL_CONNECT, false); } } /** * This method is essentially needed to force the sync settings * to a consistent state in case of an Application Update. * This is because old versions of the client do not set * the sync adapter to syncable for the contacts authority. */ private void forceSyncSettingsInCaseOfAppUpdate() { NativeContactsApi nabApi = NativeContactsApi.getInstance(); nabApi.setSyncable(true); nabApi.setSyncAutomatically( mApplication.getInternetAvail() == InternetAvail.ALWAYS_CONNECT); } /** * Gets the first People Account found on the device or * null if none is found. * Beware! This method is basically duplicate code from * NativeContactsApi2.getPeopleAccount(). * Duplicating the code was found to be cleanest way to acess the functionality. * @return The Android People account found or null */ private Account getPeopleAccount() { android.accounts.Account[] accounts = AccountManager.get(mApplication).getAccountsByType(NativeContactsApi.PEOPLE_ACCOUNT_TYPE_STRING); if (accounts != null && accounts.length > 0) { Account ret = new Account(accounts[0].name, accounts[0].type); return ret; } return null; } }
360/360-Engine-for-Android
faf96193d24c1ae6de4d75fe8252d454b5e778f8
PAND-2360 follow-up on the code review
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 3396162..485bca2 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,977 +1,956 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.identities; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import android.os.Bundle; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Identities; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.ThirdPartyAccount; /** * Engine responsible for handling retrieval and validation of Identities (e.g. * 3rd party/web accounts). The Identities engine can fetch a list of available * accounts, and set required capabilities and validate credentials for * specified accounts. */ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { /** * States for IdentitiesEngine. States are based on the requests that the * engine needs to handle. */ private enum State { IDLE, FETCHING_IDENTITIES, VALIDATING_IDENTITY_CREDENTIALS, SETTING_IDENTITY_STATUS, GETTING_MY_IDENTITIES, GETTING_MY_CHATABLE_IDENTITIES, DELETE_IDENTITY } /** * Mutex for thread synchronisation */ private final Object mMutex = new Object(); /** * Container class for Identity Capability Status request. Consists of a * network, identity id and a filter containing the required capabilities. */ private static class IdentityStatusRequest { private String mNetwork; private String mIdentityId; private String mIdentityStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setIdentityStatus(String status) { mIdentityStatus = status; } } /** * Container class encapsulating an Identity validation request containing: * dry-run flag, network, user-name, password, set of required capabilities. */ private static class IdentityValidateCredentialsRequest { /** Performs a dry run if true. */ private boolean mDryRun; /** Network to sign into. */ private String mNetwork; /** Username to sign into identity with. */ private String mUserName; /** Password to sign into identity with. */ private String mPassword; private Map<String, Boolean> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } /** * * Container class for Delete Identity request. Consist network and identity id. * */ private static class DeleteIdentityRequest { /** Network to delete.*/ private String mNetwork; /** IdentityID which needs to be Deleted.*/ private String mIdentityId; } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mMyIdentityList; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; /** * Maintaining DeleteIdentityRequest so that it can be later removed from * maintained cache. **/ private DeleteIdentityRequest identityToBeDeleted; + + /** + * The hard coded list of capabilities we use to getAvailable~/MyIdentities(): chat and status. + */ + private final Map<String, List<String>> mCapabilitiesFilter; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; mMyIdentityList = new ArrayList<Identity>(); mAvailableIdentityList = new ArrayList<Identity>(); - + mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; + + // initialize identity capabilities filter + mCapabilitiesFilter = new Hashtable<String, List<String>>(); + final List<String> capabilities = new ArrayList<String>(); + capabilities.add(IdentityCapability.CapabilityID.chat.name()); + capabilities.add(IdentityCapability.CapabilityID.get_own_status.name()); + mCapabilitiesFilter.put("capability", capabilities); } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { final ArrayList<Identity> availableIdentityList; synchronized(mAvailableIdentityList) { // make a shallow copy availableIdentityList = new ArrayList<Identity>(mAvailableIdentityList); } if ((availableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return availableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { final ArrayList<Identity> myIdentityList; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } if ((myIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return myIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = getMyThirdPartyChattableIdentities(); // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chattableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chattableIdentities; } /** * * Takes all third party identities that have a chat capability set to true. * * @return A list of chattable 3rd party identities the user is signed in to. If the retrieval identities failed the returned list will be empty. * */ public ArrayList<Identity> getMyThirdPartyChattableIdentities() { final ArrayList<Identity> chattableIdentities = new ArrayList<Identity>(); final ArrayList<Identity> myIdentityList; final int identityListSize; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } identityListSize = myIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = myIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue)) { chattableIdentities.add(identity); break; } } } return chattableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { - Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); + Identities.getMyIdentities(this, mCapabilitiesFilter); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { - Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); + Identities.getAvailableIdentities(this, mCapabilitiesFilter); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** + * TODO: re-factor the method in the way that the UI doesn't pass the Bundle with capabilities + * list to the Engine, but the Engine makes the list itself (UI/Engine separation). + * * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Delete the given social network. * * @param network Name of the identity, * @param identityId Id of identity. */ public final void addUiDeleteIdentityRequest(final String network, final String identityId) { LogUtils.logD("IdentityEngine.addUiRemoveIdentity()"); DeleteIdentityRequest data = new DeleteIdentityRequest(); data.mNetwork = network; data.mIdentityId = identityId; /**maintaining the sent object*/ setIdentityToBeDeleted(data); addUiRequestToQueue(ServiceUiRequest.DELETE_IDENTITY, data); } /** * Setting the DeleteIdentityRequest object. * * @param data */ private void setIdentityToBeDeleted(final DeleteIdentityRequest data) { identityToBeDeleted = data; } /** * Return the DeleteIdentityRequest object. * */ private DeleteIdentityRequest getIdentityToBeDeleted() { return identityToBeDeleted; } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case GET_MY_IDENTITIES: sendGetMyIdentitiesRequest(); completeUiRequest(ServiceStatus.SUCCESS); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; case DELETE_IDENTITY: executeDeleteIdentityRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to delete the identity as specified . (Request is not issued if there * is currently no connectivity). * * @param data bundled request data containing network and identityId. */ private void executeDeleteIdentityRequest(final Object data) { if (!isConnected()) { completeUiRequest(ServiceStatus.ERROR_NO_INTERNET); } newState(State.DELETE_IDENTITY); DeleteIdentityRequest reqData = (DeleteIdentityRequest) data; if (!setReqId(Identities.deleteIdentity(this, reqData.mNetwork, reqData.mIdentityId))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(DecodedResponse resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if ((null == resp) || (null == resp.mDataTypes)) { LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); return; } // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; case BaseDataType.IDENTITY_DELETION_DATA_TYPE: handleDeleteIdentity(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); } } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { Identity identity = (Identity)item; mMyIdentityList.add(identity); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); if (errorStatus == ServiceStatus.SUCCESS) { addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, null); } } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response of request to delete the identity. The response * should be a status that whether the operation is succeeded or not. The * response will be a status result otherwise ERROR_UNEXPECTED_RESPONSE if * the response is not as expected. * * @param data * List of BaseDataTypes generated from Server response. */ private void handleDeleteIdentity(final List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus( BaseDataType.IDENTITY_DELETION_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { for (BaseDataType item : data) { if (item.getType() == BaseDataType.IDENTITY_DELETION_DATA_TYPE) { synchronized(mMyIdentityList) { // iterating through the subscribed identities for (Identity identity : mMyIdentityList) { if (identity.mIdentityId .equals(getIdentityToBeDeleted().mIdentityId)) { mMyIdentityList.remove(identity); break; } } } completeUiRequest(ServiceStatus.SUCCESS); return; } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } } completeUiRequest(errorStatus, bu); } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; synchronized (mAvailableIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mAvailableIdentityList); } } else { requestKey = KEY_MY_IDS; synchronized (mMyIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mMyIdentityList); } } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } - - /** - * - * Retrieves the filter for the getAvailableIdentities and getMyIdentities - * calls. - * - * @return The identities filter in form of a bundle. - * - */ - private Bundle getIdentitiesFilter() { - Bundle b = new Bundle(); - ArrayList<String> l = new ArrayList<String>(); - l.add(IdentityCapability.CapabilityID.chat.name()); - l.add(IdentityCapability.CapabilityID.get_own_status.name()); - b.putStringArrayList("capability", l); - return b; - } - + @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } - - /** - * Generate Map containing String capability filters for m supplied Bundle. - * - * @param filter Bundle containing filter. - * @return Map containing set of capabilities. - */ - private static Map<String, List<String>> prepareStringFilter(Bundle filter) { - Map<String, List<String>> returnFilter = null; - if (filter != null && filter.keySet().size() > 0) { - returnFilter = new Hashtable<String, List<String>>(); - for (String key : filter.keySet()) { - returnFilter.put(key, filter.getStringArrayList(key)); - } - } else { - returnFilter = null; - } - return returnFilter; - } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ /** {@inheritDoc} */ @Override public final void onReset() { super.onReset(); mMyIdentityList.clear(); mAvailableIdentityList.clear(); mStatusList.clear(); mState = State.IDLE; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of Identity objects, can be NULL. * @return TRUE if the given Identity contains a Facebook account. */ public boolean isFacebookInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_FACEBOOK)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given Identity contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given Identity contains a Hyves account. */ public boolean isHyvesInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_HYVES)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Hyves not found in list"); return false; } }
360/360-Engine-for-Android
4b6871bf8831916d5509eacf0f5b9b83ff78feaf
PAND-2393 reset network and sync adapter settings on Change_User menu
diff --git a/src/com/vodafone360/people/MainApplication.java b/src/com/vodafone360/people/MainApplication.java index ffc9e4b..52fa37d 100644 --- a/src/com/vodafone360/people/MainApplication.java +++ b/src/com/vodafone360/people/MainApplication.java @@ -1,234 +1,245 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import android.app.Application; import android.os.Handler; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.service.PersistSettings; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.interfaces.IPeopleService; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.LoginPreferences; import com.vodafone360.people.utils.WidgetUtils; /** * Application class used to create the connection to the service and cache * state between Activities. */ public class MainApplication extends Application { private IPeopleService mServiceInterface; private Handler mServiceLoadedHandler; private DatabaseHelper mDatabaseHelper; private final ApplicationCache mApplicationCache = new ApplicationCache(); /** * Called when the Application is created. */ @Override public void onCreate() { super.onCreate(); SettingsManager.loadProperties(this); mDatabaseHelper = new DatabaseHelper(this); mDatabaseHelper.start(); LoginPreferences.getCurrentLoginActivity(this); } /** * Called when the Application is exited. */ @Override public void onTerminate() { // FlurryAgent.onEndSession(this); if (mDatabaseHelper != null) { mDatabaseHelper.close(); } super.onTerminate(); } /** * Return handle to DatabaseHelper, currently provides main point of access * to People client's database tables. * * @return Handle to DatabaseHelper. */ public DatabaseHelper getDatabase() { return mDatabaseHelper; } /** * Return handle to ApplicationCache. * * @return handle to ApplicationCache. */ public ApplicationCache getCache() { return mApplicationCache; } /** * Remove all user data from People client, this includes all account * information (downloaded contacts, login credentials etc.) and all cached * settings. */ public synchronized void removeUserData() { EngineManager mEngineManager = EngineManager.getInstance(); if (mEngineManager != null) { // Resets all the engines, the call will block until every engines // have been reset. mEngineManager.resetAllEngines(); } + // Remove NAB Account at this point (does nothing on 1.X) + NativeContactsApi.getInstance().removePeopleAccount(); + + // the same action as in NetworkSettingsActivity onChecked() + setInternetAvail(InternetAvail.ALWAYS_CONNECT, false); + mDatabaseHelper.removeUserData(); + // Before clearing the Application cache, kick the widget update. Pref's // file contain the widget ID. WidgetUtils.kickWidgetUpdateNow(this); mApplicationCache.clearCachedData(this); } /** * Register a Handler to receive notification when the People service has * loaded. If mServiceInterface == NULL then this means that the UI is * starting before the service has loaded - in this case the UI registers to * be notified when the service is loaded using the serviceLoadedHandler. * TODO: consider any pitfalls in this situation. * * @param serviceLoadedHandler Handler that receives notification of service * being loaded. */ public synchronized void registerServiceLoadHandler(Handler serviceLoadedHandler) { if (mServiceInterface != null) { onServiceLoaded(); } else { mServiceLoadedHandler = serviceLoadedHandler; LogUtils.logI("MainApplication.registerServiceLoadHandler() mServiceInterface is NULL " + "- need to wait for service to be loaded"); } } /** * Un-register People service loading handler. */ public synchronized void unRegisterServiceLoadHandler() { mServiceLoadedHandler = null; } private void onServiceLoaded() { if (mServiceLoadedHandler != null) { mServiceLoadedHandler.sendEmptyMessage(0); } } /** * Set IPeopleService interface - this is the interface by which we * interface to People service. * * @param serviceInterface IPeopleService handle. */ public synchronized void setServiceInterface(IPeopleService serviceInterface) { if (serviceInterface == null) { LogUtils.logE("MainApplication.setServiceInterface() " + "New serviceInterface should not be NULL"); } mServiceInterface = serviceInterface; onServiceLoaded(); } /** * Return current IPeopleService interface. TODO: The case where * mServiceInterface = NULL needs to be considered. * * @return current IPeopleService interface (can be null). */ public synchronized IPeopleService getServiceInterface() { if (mServiceInterface == null) { LogUtils.logE("MainApplication.getServiceInterface() " + "mServiceInterface should not be NULL"); } return mServiceInterface; } /** * Set Internet availability - always makes Internet available, only * available in home network, allow manual connection only. This setting is * stored in People database. * * @param internetAvail Internet availability setting. * @param forwardToSyncAdapter TRUE if the SyncAdater needs to know about the changes, FALSE otherwise * @return SerivceStatus indicating whether the Internet availability * setting has been successfully updated in the database. */ public ServiceStatus setInternetAvail(InternetAvail internetAvail, boolean forwardToSyncAdapter) { if(getInternetAvail() == internetAvail) { - // Nothing to do + // FIXME: This is a hack in order to set the system auto sync on/off depending on our data settings + if (forwardToSyncAdapter) { + NativeContactsApi.getInstance().setSyncAutomatically(internetAvail == InternetAvail.ALWAYS_CONNECT); + } return ServiceStatus.SUCCESS; } if(internetAvail == InternetAvail.ALWAYS_CONNECT && !NativeContactsApi.getInstance().getMasterSyncAutomatically()) { // FIXME: Perhaps an abusive use of this error code for when // Master Sync Automatically is OFF, should have a different LogUtils.logW("ServiceStatus.setInternetAvail() [master sync is off]"); return ServiceStatus.ERROR_NO_AUTO_CONNECT; } PersistSettings mPersistSettings = new PersistSettings(); mPersistSettings.putInternetAvail(internetAvail); ServiceStatus ss = mDatabaseHelper.setOption(mPersistSettings); // FIXME: This is a hack in order to set the system auto sync on/off depending on our data settings if (forwardToSyncAdapter) { NativeContactsApi.getInstance().setSyncAutomatically(internetAvail == InternetAvail.ALWAYS_CONNECT); } synchronized (this) { if (mServiceInterface != null) { mServiceInterface.notifyDataSettingChanged(internetAvail); } else { LogUtils.logE("MainApplication.setInternetAvail() " + "mServiceInterface should not be NULL"); } } return ss; } /** * Retrieve Internet availability setting from People database. * * @return current Internet availability setting. */ - public InternetAvail getInternetAvail() { - return mDatabaseHelper.fetchOption(PersistSettings.Option.INTERNETAVAIL).getInternetAvail(); + public synchronized InternetAvail getInternetAvail() { + InternetAvail internetAvail = mDatabaseHelper.fetchOption(PersistSettings.Option.INTERNETAVAIL).getInternetAvail(); + return internetAvail; } } diff --git a/src/com/vodafone360/people/engine/login/LoginEngine.java b/src/com/vodafone360/people/engine/login/LoginEngine.java index 267ffe9..0009b01 100644 --- a/src/com/vodafone360/people/engine/login/LoginEngine.java +++ b/src/com/vodafone360/people/engine/login/LoginEngine.java @@ -381,1048 +381,1047 @@ public class LoginEngine extends BaseEngine { return; } if (processTimeout()) { return; } switch (mState) { case NOT_INITIALISED: initialiseEngine(); return; case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: if (mActivationCode != null) { handleSmsResponse(); return; } break; case RETRIEVING_PUBLIC_KEY: break; case LOGGED_OFF: case LOGGED_OFF_WAITING_FOR_NETWORK: AuthSessionHolder session = StateTable.fetchSession(mDb.getReadableDatabase()); // if session is null we try to login automatically again if (null == session) { if (retryAutoLogin()) { return; } } else { // otherwise we try to reuse the session sActivatedSession = session; newState(State.LOGGED_ON); } default: // do nothing. break; } if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { if (!isUiRequestOutstanding()) { return false; } switch (mState) { case NOT_REGISTERED: case LOGGED_OFF: case LOGGED_ON: case LOGIN_FAILED: case CREATING_SESSION_AUTO: case LOGIN_FAILED_WRONG_CREDENTIALS: case LOGGED_OFF_WAITING_FOR_RETRY: return true; default: return false; } } /** * Determines if the user is currently logged in with a valid session. * * @return true if logged in, false otherwise */ public boolean isLoggedIn() { return mState == State.LOGGED_ON; } /** * Add a listener which will receive events whenever the login state * changes. * * @param listener The callback interface */ public synchronized void addListener(ILoginEventsListener listener) { LogUtils.logD("LoginEngine.addListener()"); if (!mEventsListener.contains(listener)) { mEventsListener.add(listener); } } /** * Remove a listener added by the addListener function. * * @param listener The same callback interface passed in to the add function */ public synchronized void removeListener(ILoginEventsListener listener) { LogUtils.logD("LoginEngine.removeListener()"); mEventsListener.remove(listener); } /** * Remove all ILoginStateChangeListener (done as part of cleanup). */ private synchronized void removeAllListeners() { LogUtils.logD("LoginEngine.removeAllListeners()"); if (mEventsListener != null) { mEventsListener.clear(); } } /** * Once the engine has finished processing a user request, this function is * called to restore the state back to an appropriate value (based on the * user login state). */ private synchronized void restoreLoginState() { LogUtils.logD("LoginEngine.restoreLoginState"); if (mIsRegistrationComplete) { if (sActivatedSession != null) { newState(State.LOGGED_ON); } else { if (mAreLoginDetailsValid) { newState(State.LOGGED_OFF); } else { newState(State.LOGIN_FAILED); } } } else { newState(State.NOT_REGISTERED); } } /** * Called when a server response is received, processes the response based * on the engine state. * * @param resp Response data from server */ @Override protected void processCommsResponse(ResponseQueue.DecodedResponse resp) { LogUtils.logD("LoginEngine.processCommsResponse() - resp = " + resp); switch (mState) { case SIGNING_UP: handleSignUpResponse(resp.mDataTypes); break; case RETRIEVING_PUBLIC_KEY: handleNewPublicKeyResponse(resp.mDataTypes); break; case CREATING_SESSION_MANUAL: handleCreateSessionManualResponse(resp.mDataTypes); break; case CREATING_SESSION_AUTO: handleCreateSessionAutoResponse(resp.mDataTypes); break; case REQUESTING_ACTIVATION_CODE: handleRequestingActivationResponse(resp.mDataTypes); break; case ACTIVATING_ACCOUNT: handleActivateAccountResponse(resp.mDataTypes); break; case FETCHING_TERMS_OF_SERVICE: case FETCHING_PRIVACY_STATEMENT: case FETCHING_USERNAME_STATE: handleServerSimpleTextResponse(resp.mDataTypes, mState); break; default: // do nothing. break; } } /** * Called when a UI request is ready to be processed. Handlers the UI * request based on the type. * * @param requestId UI request type * @param data Interpretation of this data depends on the request type */ @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { LogUtils.logD("LoginEngine.processUiRequest() - reqID = " + requestId); switch (requestId) { case LOGIN: startManualLoginProcess((LoginDetails)data); break; case REGISTRATION: startRegistrationProcessCrypted((RegistrationDetails)data); break; case REMOVE_USER_DATA: startLogout(); // Remove NAB Account at this point (does nothing on 1.X) NativeContactsApi.getInstance().removePeopleAccount(); super.onReset(); // Sets the reset flag as done break; case LOGOUT: startLogout(); break; case FETCH_TERMS_OF_SERVICE: startFetchTermsOfService(); break; case FETCH_PRIVACY_STATEMENT: startFetchPrivacyStatement(); break; case USERNAME_AVAILABILITY: startFetchUsernameState((String)data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); } } /** * Called by the run() function the first time it is executed to perform * non-trivial initialisation such as auto login. */ private void initialiseEngine() { LogUtils.logD("LoginEngine.initialiseEngine()"); if (ServiceStatus.SUCCESS == mDb.fetchLogonCredentialsAndPublicKey(mLoginDetails, mPublicKey)) { if (mLoginDetails.mSubscriberId != null && !mLoginDetails.mSubscriberId.equals(mCurrentSubscriberId)) { LogUtils.logW("SIM card has changed. Login session invalid"); } else { sActivatedSession = StateTable.fetchSession(mDb.getReadableDatabase()); } } mAreLoginDetailsValid = true; restoreLoginState(); clearTimeout(); } /** * Starts the sign-up process where the password is RSA encrypted. A setting * determines if this function is used in preference to * {@link #startRegistrationProcess(RegistrationDetails)} function. * * @param details Registration details received from the UI request */ private void startRegistrationProcessCrypted(RegistrationDetails details) { LogUtils.logD("startRegistrationCrypted"); if (details == null || details.mUsername == null || details.mPassword == null) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } setRegistrationComplete(false); setActivatedSession(null); mRegistrationDetails.copy(details); mLoginDetails.mUsername = mRegistrationDetails.mUsername; mLoginDetails.mPassword = mRegistrationDetails.mPassword; try { final long timestampInSeconds = System.currentTimeMillis() / MS_IN_SECONDS; final byte[] theBytes = prepareBytesForSignup(timestampInSeconds); mLoginDetails.mAutoConnect = true; mLoginDetails.mRememberMe = true; mLoginDetails.mMobileNo = mRegistrationDetails.mMsisdn; mLoginDetails.mSubscriberId = mCurrentSubscriberId; mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); startSignUpCrypted(theBytes, timestampInSeconds); } catch (InvalidCipherTextException e) { e.printStackTrace(); } } /** * Encrypts the sign-up data ready for sending to the server * * @param timeStampInSeconds Current time in milliseconds * @return Raw data that can be sent to the server */ private byte[] prepareBytesForSignup(long timeStampInSeconds) throws InvalidCipherTextException { byte[] theBytes = null; if (mPublicKey != null) { if (mPublicKey.mExponential != null && (mPublicKey.mModulus != null)) { theBytes = RSAEncryptionUtils.encryptRSA(RSAEncryptionUtils.getRSAPubKey( mPublicKey.mModulus, mPublicKey.mExponential), makeSecurePassword( mLoginDetails.mUsername, mLoginDetails.mPassword, timeStampInSeconds)); } } if (theBytes == null) { RSAEncryptionUtils.copyDefaultPublicKey(mPublicKey);// we'll store // the default // public key // into the db theBytes = RSAEncryptionUtils.encryptRSA(RSAEncryptionUtils.getDefaultPublicKey(), makeSecurePassword(mLoginDetails.mUsername, mLoginDetails.mPassword, timeStampInSeconds)); } return theBytes; } /** * Concatenates the username, password, current time and some other data * into a string which can be encrypted and sent to the server. * * @param userName User name for sign-in or sign-up * @param password Password as entered by user * @param ts Current time in milliseconds * @return Concatenated data */ private static String makeSecurePassword(String userName, String password, long ts) { String appSecret = SettingsManager.getProperty(Settings.APP_SECRET_KEY);// RSAEncrypter.testAppSecretThrottled; final char amp = '&'; if (ts <= 0 || // userName == null || userName.trim().length() == 0 || // password == null || password.trim().length() == 0 || // // set application key somewhere appSecret == null || appSecret.trim().length() == 0) return null; final String passwordT = password.trim(); final String userNameT = userName.trim(); final StringBuffer sb = new StringBuffer(); sb.append(appSecret).append(amp).append(Long.toString(ts)).append(amp).append(userNameT) .append(amp).append(passwordT); return sb.toString(); } /** * Puts the engine into the signing up state and sends an encrypted sign-up * request to the server. * * @param theBytes byte-array containing encrypted password data. * @param timestamp Current timestamp. */ private void startSignUpCrypted(byte[] theBytes, long timestamp) { LogUtils.logD("startSignUpCrypted()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mActivationCode = null; newState(State.SIGNING_UP); if (!validateRegistrationDetails()) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } int reqId = Auth.signupUserCrypted( this, mRegistrationDetails.mFullname, mRegistrationDetails.mUsername, theBytes, // what is encrypted timestamp, mRegistrationDetails.mEmail, mRegistrationDetails.mBirthdayDate, mRegistrationDetails.mMsisdn, mRegistrationDetails.mAcceptedTAndC, mRegistrationDetails.mCountrycode, mRegistrationDetails.mTimezone, mRegistrationDetails.mLanguage, mRegistrationDetails.mMobileOperatorId, mRegistrationDetails.mMobileModelId, mRegistrationDetails.mSendConfirmationMail, mRegistrationDetails.mSendConfirmationSms, mRegistrationDetails.mSubscribeToNewsLetter); if (!setReqId(reqId)) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Basic check to determine if the registration details given by the user * are valid * * @return true if the details are valid, false otherwise. */ private boolean validateRegistrationDetails() { if (mRegistrationDetails.mFullname == null || mRegistrationDetails.mEmail == null || mRegistrationDetails.mBirthdayDate == null || mRegistrationDetails.mMsisdn == null || mRegistrationDetails.mAcceptedTAndC == null || mRegistrationDetails.mCountrycode == null || mRegistrationDetails.mTimezone == null || mRegistrationDetails.mLanguage == null || mRegistrationDetails.mMobileOperatorId == null || mRegistrationDetails.mMobileModelId == null || mRegistrationDetails.mSendConfirmationMail == null || mRegistrationDetails.mSendConfirmationSms == null || mRegistrationDetails.mSubscribeToNewsLetter == null) { return false; } return true; } /** * Requests a new Public Key from the server. */ public void getNewPublicKey() { LogUtils.logD("LoginEngine.getNewPublicKey"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mActivationCode = null; newState(State.RETRIEVING_PUBLIC_KEY); if (!setReqId(Auth.getPublicKey(this))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch terms of service request to the server. */ private void startFetchTermsOfService() { LogUtils.logD("LoginEngine.startFetchTermsOfService()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } newState(State.FETCHING_TERMS_OF_SERVICE); if (!setReqId(Auth.getTermsAndConditions(this))) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch privacy statement request to the server. */ private void startFetchPrivacyStatement() { LogUtils.logD("LoginEngine.startFetchPrivacyStatement()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } newState(State.FETCHING_PRIVACY_STATEMENT); if (!setReqId(Auth.getPrivacyStatement(this))) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch user-name state request to the server. * * @param username, the user-name to retrieve information for. */ private void startFetchUsernameState(String username) { LogUtils.logD("LoginEngine.startFetchUsernameState()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mLoginDetails.mUsername = username; newState(State.FETCHING_USERNAME_STATE); if (!setReqId(Auth.getUsernameState(this, username))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sets registration complete flag to false then starts a new sign-in * request. * * @param details Login details received from the UI request */ private void startManualLoginProcess(LoginDetails details) { LogUtils.logD("LoginEngine.startManualLoginProcess()"); setRegistrationComplete(false); setActivatedSession(null); if (details == null) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } mLoginDetails.copy(details); mLoginDetails.mSubscriberId = mCurrentSubscriberId; mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); if (Settings.ENABLE_ACTIVATION) { startRequestActivationCode(); } else { startGetSessionManual(); } } /** * Sends a request activation code request to the server. */ private void startRequestActivationCode() { LogUtils.logD("LoginEngine.startRequestActivationCode()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mActivationCode = null; newState(State.REQUESTING_ACTIVATION_CODE); if (!setReqId(Auth.requestActivationCode(this, mLoginDetails.mUsername, mLoginDetails.mMobileNo))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a get session by credentials request to the server. */ private void startGetSessionManual() { LogUtils.logD("LoginEngine.startGetSessionManual()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } newState(State.CREATING_SESSION_MANUAL); if (!setReqId(Auth.getSessionByCredentials(this, mLoginDetails.mUsername, mLoginDetails.mPassword, null))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a activate account request to the server. */ private void startActivateAccount() { LogUtils.logD("LoginEngine.startActivateAccount()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } + if (Settings.ENABLE_ACTIVATION) { newState(State.ACTIVATING_ACCOUNT); if (!setReqId(Auth.activate(this, mActivationCode))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } else { setRegistrationComplete(true); completeUiRequest(ServiceStatus.SUCCESS, null); } } /** * Clears the session and registration complete information so that the user * will need to manually login again to use the now+ services. Does not * currently send a request to the server to log out. */ private void startLogout() { LogUtils.logD("LoginEngine.startLogout()"); setRegistrationComplete(false); setActivatedSession(null); completeUiRequest(ServiceStatus.SUCCESS, null); } /** * Clears the session and registration complete information so that the user * will need to manually login again to use the now+ services. Does not * currently send a request to the server to log out. */ public final void logoutAndRemoveUser() { LogUtils.logD("LoginEngine.startLogout()"); addUiRemoveUserDataRequest(); LoginPreferences.clearPreferencesFile(mContext); mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UNSOLICITED_GO_TO_LANDING_PAGE, null); } /** * Retries to log the user in based on credential information stored in the * database. * * @return true if the login process was able to start */ public boolean retryAutoLogin() { LogUtils.logD("LoginEngine.retryAutoLogin()"); setActivatedSession(null); if (ServiceStatus.SUCCESS != mDb.fetchLogonCredentialsAndPublicKey(mLoginDetails, mPublicKey)) { LogUtils .logE("LoginEngine.retryAutoLogin() - Unable to fetch credentials from database"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } // AA: commented the condition out if (Settings.ENABLE_ACTIVATION) { // AA: the old version if (mCurrentSubscriberId == null || // !mCurrentSubscriberId.equals(mLoginDetails.mSubscriberId)) { // // logging off/fail will be done in another way according to bug 8288 if (mCurrentSubscriberId != null && !mCurrentSubscriberId.equals(mLoginDetails.mSubscriberId)) { LogUtils.logV("LoginEngine.retryAutoLogin() -" + " SIM card has changed or is missing (old subId = " + mLoginDetails.mSubscriberId + ", new subId = " + mCurrentSubscriberId + ")"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } // } if (mLoginDetails.mUsername == null || mLoginDetails.mPassword == null || mLoginDetails.mMobileNo == null) { LogUtils.logV("LoginEngine.retryAutoLogin() - Username, password " + "or mobile number are missing (old username = " + mLoginDetails.mUsername + ", mobile no = " + mLoginDetails.mMobileNo + ")"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } mAreLoginDetailsValid = true; if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { newState(State.LOGGED_OFF_WAITING_FOR_NETWORK); LogUtils.logV("LoginEngine.retryAutoLogin() - Internet connection down. " + "Will try again when connection is available"); return false; } newState(State.CREATING_SESSION_AUTO); if (!setReqId(Auth.getSessionByCredentials(this, mLoginDetails.mUsername, mLoginDetails.mPassword, null))) { return false; } return true; } /** * Helper function to set the registration complete flag and update the * database with the new state. * * @param value true if registration is completed */ private void setRegistrationComplete(boolean value) { LogUtils.logD("LoginEngine.setRegistrationComplete(" + value + ")"); if (value != mIsRegistrationComplete) { StateTable.setRegistrationComplete(value, mDb.getWritableDatabase()); mIsRegistrationComplete = value; if (mIsRegistrationComplete) { // Create NAB Account at this point (does nothing on 1.X // devices) final NativeContactsApi nabApi = NativeContactsApi.getInstance(); if (!nabApi.isPeopleAccountCreated()) { // TODO: React upon failure to create account nabApi.addPeopleAccount(LoginPreferences.getUsername()); } } } } /** * Changes the state of the engine. Also displays the login notification if * necessary. * * @param newState The new state */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("LoginEngine.newState: " + oldState + " -> " + mState); Intent intent = null; // Update notification switch (mState) { case LOGIN_FAILED_WRONG_CREDENTIALS: intent = new Intent(); intent.setAction(Intents.START_LOGIN_ACTIVITY); mContext.sendBroadcast(intent); setRegistrationComplete(false); break; // here should be no break case NOT_REGISTERED: case LOGIN_FAILED: // intent = new Intent(); // intent.setAction(Intents.LOGIN_FAILED); // mContext.sendBroadcast(intent); setRegistrationComplete(false); // startLogout(); // mDb.removeUserData(); // sending user to login screen again // should be done by UI itself because // when it's done from here it cause problems when user tries to // login // giving wrong credentials, ui flow will be broken break; case LOGGED_OFF: case LOGGED_OFF_WAITING_FOR_NETWORK: case LOGGED_OFF_WAITING_FOR_RETRY: case LOGGED_ON: // intent = new Intent(); // intent.setAction(Intents.HIDE_LOGIN_NOTIFICATION); // mContext.sendBroadcast(intent); break; default:// do nothing break; } // Update listeners with any state changes switch (mState) { case NOT_REGISTERED: case LOGIN_FAILED: case LOGIN_FAILED_WRONG_CREDENTIALS: case LOGGED_OFF: onLoginStateChanged(false); break; case LOGGED_ON: onLoginStateChanged(true); break; default: // do nothing. break; } } /** * Called when the engine transitions between the logged in and logged out * states. Notifies listeners. * * @param loggedIn true if the user is now logged in, false otherwise. */ private synchronized void onLoginStateChanged(boolean loggedIn) { LogUtils.logD("LoginEngine.onLoginStateChanged() Login state changed to " + (loggedIn ? "logged in." : "logged out.")); if (loggedIn == mCurrentLoginState) { return; } mCurrentLoginState = loggedIn; for (ILoginEventsListener listener : mEventsListener) { listener.onLoginStateChanged(loggedIn); } } /** * A helper function which determines which activity should be displayed * when the UI is loaded. * * @return true if landing page should be displayed, false otherwise */ public synchronized boolean getLoginRequired() { LogUtils.logD("LoginEngine.getLoginRequired() - " + !mIsRegistrationComplete); return !mIsRegistrationComplete; } /** * Retrieves the active comms session. * * @return The session or NULL if the user is logged out. */ public static AuthSessionHolder getSession() { return sActivatedSession; } /** * Helper function to store the new session in the database and inform * clients that the session has changed. * * @param session The new session or NULL if the user has logged off. */ public synchronized void setActivatedSession(AuthSessionHolder session) { LogUtils.logD("LoginEngine.setActivatedSession() session[" + session + "]"); sActivatedSession = session; if (session != null) { LogUtils.logD("LoginEngine.setActivatedSession() Login successful"); } else { LogUtils.logW("LoginEngine.setActivatedSession() " + "Login unsuccessful, the session is NULL"); } StateTable.setSession(session, mDb.getWritableDatabase()); } /** * Called when a response to the sign-up API is received. In case of success * sets a timeout value waiting for the activation SMS to arrive. * * @param data The received data */ private void handleSignUpResponse(List<BaseDataType> data) { ServiceStatus errorStatus = getResponseStatus(BaseDataType.CONTACT_DATA_TYPE, data); LogUtils.logD("LoginEngine.handleSignUpResponse() errorStatus[" + errorStatus.name() + "]"); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils.logD("LoginEngine.handleSignUpResponse() - Registration successful"); if (!Settings.ENABLE_ACTIVATION) { startGetSessionManual(); } else { // Now waiting for SMS... setTimeout(ACTIVATE_LOGIN_TIMEOUT); } // AA } else if (errorStatus == ServiceStatus.ERROR_INVALID_PUBLIC_KEY) { // start new key retrieval and make the new cycle getNewPublicKey(); } else { completeUiRequest(errorStatus, null); } } /** * Called when a response to the server fetch public key request is * received. Validates the response and stores the new public key details. * * @param mDataTypes Response data from server. */ private void handleNewPublicKeyResponse(List<BaseDataType> mDataTypes) { LogUtils.logD("LoginEngine.handleNewPublicKeyResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.PUBLIC_KEY_DETAILS_DATA_TYPE, mDataTypes); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils.logD("LoginEngine.handleNewPublicKeyResponse() - Succesfully retrieved"); // AA // 1. save to DB; save the flag that we aren't using default and // have to use one from DB // 2. start registration again mPublicKey = (PublicKeyDetails)mDataTypes.get(0); // done in startRegistrationProcessCrypted already // mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); startRegistrationProcessCrypted(mRegistrationDetails); } else { completeUiRequest(errorStatus, null); } } /** * Called when a response to the GetSessionByCredentials API is received * (manual login). In case of success, tries to activate the account using * the activation code received by SMS. * * @param data The received data */ private void handleCreateSessionManualResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleCreateSessionManualResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AUTH_SESSION_HOLDER_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS && (data.size() > 0)) { setActivatedSession((AuthSessionHolder)data.get(0)); startActivateAccount(); return; } completeUiRequest(errorStatus, null); } /** * Called when a response to the GetSessionByCredentials API is received * (auto login). In case of success, moves to the logged in state * * @param data The received data */ private void handleCreateSessionAutoResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleCreateSessionResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AUTH_SESSION_HOLDER_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { clearTimeout(); setActivatedSession((AuthSessionHolder)data.get(0)); newState(State.LOGGED_ON); } else { LogUtils.logE("LoginEngine.handleCreateSessionResponse() - Auto Login Failed Error " + errorStatus); // AA:the 1st retry failed, just go to the start page, // if (loginAttemptsRemaining() // && errorStatus!=ServiceStatus.ERROR_INVALID_PASSWORD) { // newState(State.LOGGED_OFF_WAITING_FOR_RETRY); // setTimeout(LOGIN_RETRY_TIME); // } else { // mAreLoginDetailsValid = false; if (errorStatus == ServiceStatus.ERROR_INVALID_PASSWORD) { mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED_WRONG_CREDENTIALS); } else { newState(State.LOGIN_FAILED); } // } } } /** * Called when a response to the RequestActivationCode API is received * (manual login). In case of success, tries to fetch a login session from * the server. * * @param data The received data */ private void handleRequestingActivationResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleRequestingActivationResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { // Now waiting for SMS... setTimeout(ACTIVATE_LOGIN_TIMEOUT); return; } completeUiRequest(errorStatus, null); } /** * Called when a response to the Activate API is received (manual login or * sign-up). In case of success, moves to the logged in state and completes * the manual login or sign-up request. * * @param data The received data */ private void handleActivateAccountResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleActivateAccountResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils .logD("LoginEngine.handleActivateAccountResponse: ** Mobile number activated **"); setRegistrationComplete(true); completeUiRequest(ServiceStatus.SUCCESS, null); return; } setActivatedSession(null); completeUiRequest(ServiceStatus.ERROR_ACCOUNT_ACTIVATION_FAILED, null); } /** * Called when a response to the GetTermsAndConditions, GetPrivacyStatement * and GetUsernameState APIs are received. In case of success, completes the * request and passes the response data to the UI. * * @param data The received data */ private void handleServerSimpleTextResponse(List<BaseDataType> data, State type) { LogUtils.logV("LoginEngine.handleServerSimpleTextResponse()"); ServiceStatus serviceStatus = getResponseStatus(BaseDataType.SIMPLE_TEXT_DATA_TYPE, data); String result = null; if (serviceStatus == ServiceStatus.SUCCESS) { result = ((SimpleText) data.get(0)).mValue.toString().replace( CARRIAGE_RETURN_CHARACTER, SPACE_CHARACTER); switch (type) { case FETCHING_TERMS_OF_SERVICE: LogUtils.logD("LoginEngine.handleServerSimpleTextResponse() Terms of Service"); ApplicationCache.setTermsOfService(result, mContext); break; case FETCHING_PRIVACY_STATEMENT: LogUtils.logD("LoginEngine.handleServerSimpleTextResponse() Privacy Statemet"); ApplicationCache.setPrivacyStatemet(result, mContext); break; case FETCHING_USERNAME_STATE: // TODO: Unused by UI. break; } } updateTermsState(serviceStatus, result); } /*** * Informs the UI to update any terms which are being shown on screen. * * @param serviceStatus Current ServiceStatus. * @param messageText Legacy call for old UI (TODO: remove after UI-Refresh * merge). NULL when combined with a ServiceStatus of * ERROR_COMMS, or contains the Privacy or Terms and Conditions * text to be displayed in the UI. */ private void updateTermsState(ServiceStatus serviceStatus, String messageText) { ApplicationCache.setTermsStatus(serviceStatus); /** Trigger UiAgent. **/ mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.TERMS_CHANGED_EVENT, null); /** Clear this request from the UI queue. **/ completeUiRequest(serviceStatus, messageText); } /** * A broadcast receiver which is used to receive notifications when a data * SMS arrives. */ private final BroadcastReceiver mEventReceiver = new BroadcastReceiver() { /** * Called when an SMS arrives. The activation code is extracted from the * given intent and the worker thread kicked. * * @param context Context from which the intent was broadcast * @param intent Will only process the SMS which the action is * {@link SmsBroadcastReceiver#ACTION_ACTIVATION_CODE}. */ @Override public void onReceive(Context context, Intent intent) { LogUtils.logD("LoginEngine.BroadcastReceiver.onReceive - Processing data sms"); if (intent.getAction().equals(SmsBroadcastReceiver.ACTION_ACTIVATION_CODE)) { String activationCode = intent.getStringExtra("code"); LogUtils .logD("LoginEngine.BroadcastReceiver.onReceive - Activation code Received: " + activationCode); synchronized (LoginEngine.this) { mActivationCode = activationCode; } mEventCallback.kickWorkerThread(); } } }; /** * Called when an SMS is received during sign-up or manual login. Starts * requesting a session from the server. */ private void handleSmsResponse() { LogUtils.logD("LoginEngine.handleSmsResponse(" + mActivationCode + ")"); clearTimeout(); startGetSessionManual(); } /** * Called by the base engine implementation whenever a UI request is * completed to do any necessary cleanup. We use it to restore our state to * a suitable value. */ @Override protected void onRequestComplete() { LogUtils.logD("LoginEngine.onRequestComplete()"); restoreLoginState(); } /** * Handles timeouts for SMS activation and auto login retries. */ protected synchronized void onTimeoutEvent() { LogUtils.logD("LoginEngine.onTimeoutEvent()"); switch (mState) { case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: completeUiRequest(ServiceStatus.ERROR_SMS_CODE_NOT_RECEIVED, null); break; case LOGGED_OFF_WAITING_FOR_RETRY: retryAutoLogin(); break; default: // do nothing. break; } } /** * Called by the framework before a remove user data operation takes place. * Initiates a suitable UI request which will kick the worker thread. */ @Override public void onReset() { // reset the engine as if it was just created super.onReset(); setRegistrationComplete(false); setActivatedSession(null); mState = State.NOT_INITIALISED; mRegistrationDetails = new RegistrationDetails(); mActivationCode = null; onLoginStateChanged(false); - // Remove NAB Account at this point (does nothing on 1.X) - NativeContactsApi.getInstance().removePeopleAccount(); } /** * Set 'dummy' auth session for test purposes only. * * @param session 'dummy' session supplied to LoginEngine */ public static void setTestSession(AuthSessionHolder session) { sActivatedSession = session; } } diff --git a/src/com/vodafone360/people/service/PersistSettings.java b/src/com/vodafone360/people/service/PersistSettings.java index 16ca6ed..1c5b379 100644 --- a/src/com/vodafone360/people/service/PersistSettings.java +++ b/src/com/vodafone360/people/service/PersistSettings.java @@ -1,484 +1,484 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import android.content.ContentValues; import android.database.Cursor; import android.os.Parcel; import android.os.Parcelable; /** * Class responsible for handling persistent settings within the People client. * These settings are stored in the State table in the People client's database. */ public class PersistSettings implements Parcelable { // These two member variables must never be null private Option mOption = Option.INTERNETAVAIL; private Object mValue = InternetAvail.ALWAYS_CONNECT; /** * Constructor */ public PersistSettings() { putDefaultOptionData(); } /** * Internet availability settings, options are always connect or only allow * manual connection */ public static enum InternetAvail { ALWAYS_CONNECT, MANUAL_CONNECT; } /** * Definition for Settings type (boolean, string, integer, long). */ public static enum OptionType { BOOLEAN("BOOLEAN"), STRING("STRING"), INTEGER("INTEGER"), LONG("LONG"); /** Field name as stored in State table. */ private String mDbType = null; /** * OptionType constructor. * * @param dbType State table record name for current item. */ private OptionType(String dbType) { mDbType = dbType; } /** * Return the State table field name for this item. * * @return String containing State table field name for this item. */ public String getDbType() { return mDbType; } }; /** * Definition of a set of options handled by PersistSettings. These options * are; Internet availability (always available, only in home network or * manually activated) First time contact sync status. First time native * contact sync status. */ public static enum Option { // Note: Currently it is crucial that default value for Option // INTERNETAVAIL remains MANUAL_CONNECT. The LandingPageActivity // sets the value to ALWAYS_CONNECT in its onCreate() method // before login and triggers the correct computation of the // AgentState in the NetworkAgentState class. For details see // PAND-2305. - INTERNETAVAIL("internetavail", OptionType.INTEGER, InternetAvail.MANUAL_CONNECT.ordinal()), + INTERNETAVAIL("internetavail", OptionType.INTEGER, InternetAvail.ALWAYS_CONNECT.ordinal()), FIRST_TIME_SYNC_STARTED("ftsstarted", OptionType.BOOLEAN, false), FIRST_TIME_MESYNC_STARTED("ftmesyncstarted", OptionType.BOOLEAN, false), FIRST_TIME_SYNC_COMPLETE("ftscomplete", OptionType.BOOLEAN, false), FIRST_TIME_MESYNC_COMPLETE("ftmesynccomplete", OptionType.BOOLEAN, false), FIRST_TIME_NATIVE_SYNC_COMPLETE("ftnativecomplete", OptionType.BOOLEAN, false); private String mFieldName; private Object mDefaultValue; private OptionType mType; /** * Constructor * * @param fieldName Name of setting item. * @param type Type of field (String, boolean, integer, long). * @param defaultValue Default value for item. */ private Option(String fieldName, OptionType type, Object defaultValue) { mFieldName = fieldName; mType = type; mDefaultValue = defaultValue; } /** * Return the default value for current setting. * * @return the default value for current setting. */ public Object defaultValue() { return mDefaultValue; } /** * Return the type of current option (i.e. String, boolean, integer, * long). * * @return type of current option. */ public OptionType getType() { return mType; } @Override public String toString() { return "\nOption info:\nID = " + super.toString() + "\n" + "TableFieldName = " + mFieldName + "\n" + "Type: " + mType + "\n" + "Default: " + mDefaultValue + "\n"; } /** * Search for settings item by name. * * @param key Option name to search for. * @return Option item, null if item not found. */ private static Option lookupValue(String key) { for (Option option : Option.values()) { if (key.equals(option.mFieldName)) { return option; } } return null; } /** * Option's State table record name * * @return Name of the State table field corresponding to this Option. */ public String tableFieldName() { return mFieldName; } } /** {@inheritDoc} */ @Override public String toString() { return "Option: " + mOption.tableFieldName() + ", Value: " + mValue; } /** * Return the default (boolean) value for supplied Option. * * @param option Option * @return default boolean value for specified Option or false if if the * default value is null or not a boolean. */ private static boolean getDefaultBoolean(Option option) { if (option.defaultValue() != null && option.defaultValue().getClass().equals(Boolean.class)) { return (Boolean)option.defaultValue(); } return false; } /** * Return the default (integer) value for supplied Option. * * @param option Option * @return default integer value for specified Option or false if if the * default value is null or not a integer. */ private static int getDefaultInt(Option option) { if (option.defaultValue() != null && option.defaultValue().getClass().equals(Integer.class)) { return (Integer)option.defaultValue(); } return 0; } /** * Set the default value stored in PersistDettings for specified Option. * * @param option Option the default value held by PersistSettings is the * value set in the supplied Option. */ public void putDefaultOptionData(Option option) { if (option != null) { mOption = option; putDefaultOptionData(); } } /** * Set the default value stored in PersistDettings for current Option. */ public void putDefaultOptionData() { mValue = mOption.mDefaultValue; } /** * Set the default value for the specified Option * * @param option Option to set default data for. * @param data Value for default setting. */ public void putOptionData(Option option, Object data) { mOption = option; if (data != null) { mValue = data; } else { putDefaultOptionData(); } } /** * Add setting from supplied PersistSettings instance to supplied * ContentValues instance. * * @param contentValues ContentValue to update. * @param setting PersistSettings instance containing settings value. * @return true (cannot return false!). */ public static boolean addToContentValues(ContentValues contentValues, PersistSettings setting) { PersistSettings.Option option = setting.getOption(); switch (option.getType()) { case BOOLEAN: contentValues.put(option.tableFieldName(), (Boolean)setting.getValue()); break; case STRING: contentValues.put(option.tableFieldName(), (String)setting.getValue()); break; case INTEGER: contentValues.put(option.tableFieldName(), (Integer)setting.getValue()); break; case LONG: contentValues.put(option.tableFieldName(), (Long)setting.getValue()); break; default: contentValues.put(option.tableFieldName(), setting.getValue().toString()); break; } return true; } /** * Fetch Object from database Cursor. * * @param c Database Cursor pointing to item of interest. * @param colIndex Column index within item. * @param key Key used to obtain required Option item. * @return Value obtained for Cursor, null if option does not exist or key * does not match valid Option. */ public static Object fetchValueFromCursor(Cursor c, int colIndex, String key) { PersistSettings.Option option = PersistSettings.Option.lookupValue(key); if (option == null || c.isNull(colIndex)) { return null; } switch (option.getType()) { case BOOLEAN: return (c.getInt(colIndex) == 0 ? false : true); case STRING: return c.getString(colIndex); case INTEGER: return c.getInt(colIndex); case LONG: return c.getLong(colIndex); default: return c.getString(colIndex); } } /** * Set Internet availability value. * * @param value InternetAvail. */ public void putInternetAvail(InternetAvail value) { mOption = Option.INTERNETAVAIL; if (value != null) { mValue = (Integer)value.ordinal(); } else { mValue = InternetAvail.values()[getDefaultInt(mOption)]; } } /** * Get current InternetAvail value * * @return current InternetAvail value. */ public InternetAvail getInternetAvail() { if (mOption == Option.INTERNETAVAIL && mValue.getClass().equals(Integer.class)) { int val = (Integer)mValue; if (val < InternetAvail.values().length) { return InternetAvail.values()[val]; } } return InternetAvail.values()[getDefaultInt(Option.INTERNETAVAIL)]; } /** * Return value indicating whether first time native contact sync has * completed. * * @return stored boolean value indicating whether first time native contact * sync has completed. */ public boolean getFirstTimeNativeSyncComplete() { if (mOption == Option.FIRST_TIME_NATIVE_SYNC_COMPLETE && mValue.getClass().equals(Boolean.class)) { return (Boolean)mValue; } return getDefaultBoolean(Option.FIRST_TIME_NATIVE_SYNC_COMPLETE); } /** * Store value indicating whether first time native contact sync has * completed. * * @param value value indicating whether first time native contact sync has * completed. */ public void putFirstTimeNativeSyncComplete(boolean value) { mOption = Option.FIRST_TIME_NATIVE_SYNC_COMPLETE; mValue = (Boolean)value; } /** * Store value indicating whether first time contact sync has completed. * * @param value value indicating whether first time native contact sync has * completed. */ public void putFirstTimeSyncComplete(boolean value) { mOption = Option.FIRST_TIME_SYNC_COMPLETE; mValue = (Boolean)value; } public void putFirstTimeMeSyncComplete(boolean value) { mOption = Option.FIRST_TIME_MESYNC_COMPLETE; mValue = (Boolean)value; } /** * Return value indicating whether first time native contact sync has * completed. * * @return value indicating whether first time native contact sync has * completed. */ public boolean getFirstTimeSyncComplete() { if (mOption == Option.FIRST_TIME_SYNC_COMPLETE && mValue.getClass().equals(Boolean.class)) { return (Boolean)mValue; } return getDefaultBoolean(Option.FIRST_TIME_SYNC_COMPLETE); } public boolean getFirstTimeMeSyncComplete() { if (mOption == Option.FIRST_TIME_MESYNC_COMPLETE && mValue.getClass().equals(Boolean.class)) { return (Boolean)mValue; } return getDefaultBoolean(Option.FIRST_TIME_MESYNC_COMPLETE); } /** * Store value indicating whether first time native contact sync has * started. * * @param value value indicating whether first time native contact sync has * started. */ public void putFirstTimeSyncStarted(boolean value) { mOption = Option.FIRST_TIME_SYNC_STARTED; mValue = (Boolean)value; } public void putFirstTimeMeSyncStarted(boolean value) { mOption = Option.FIRST_TIME_MESYNC_STARTED; mValue = (Boolean)value; } /** * Return value indicating whether first time native contact sync has * started. * * @return value indicating whether first time native contact sync has * started. */ public boolean getFirstTimeSyncStarted() { if (mOption == Option.FIRST_TIME_SYNC_STARTED && mValue.getClass().equals(Boolean.class)) { return (Boolean)mValue; } return getDefaultBoolean(Option.FIRST_TIME_SYNC_STARTED); } public boolean getFirstTimeMeSyncStarted() { if (mOption == Option.FIRST_TIME_MESYNC_STARTED && mValue.getClass().equals(Boolean.class)) { return (Boolean)mValue; } return getDefaultBoolean(Option.FIRST_TIME_MESYNC_STARTED); } /** * Get Option associated with this PersistSettings. * * @return Option associated with this PersistSettings. */ public Option getOption() { return mOption; } /** * Get value associated with this PersistSettings. * * @return Object representing value associated with this PersistSettings. */ private Object getValue() { return mValue; } /** {@inheritDoc} */ @Override public int describeContents() { return 0; } /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mOption.ordinal()); switch (mOption.getType()) { case BOOLEAN: dest.writeByte((byte)(((Boolean)mValue) ? 1 : 0)); break; case STRING: dest.writeString((String)mValue); break; case INTEGER: dest.writeInt((Integer)mValue); break; case LONG: dest.writeLong((Long)mValue); break; default: break; } } } diff --git a/src/com/vodafone360/people/service/SyncAdapter.java b/src/com/vodafone360/people/service/SyncAdapter.java index e706f3d..16fdc90 100644 --- a/src/com/vodafone360/people/service/SyncAdapter.java +++ b/src/com/vodafone360/people/service/SyncAdapter.java @@ -1,304 +1,304 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import android.accounts.Account; import android.accounts.AccountManager; import android.content.AbstractThreadedSyncAdapter; import android.content.BroadcastReceiver; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SyncResult; import android.content.SyncStatusObserver; import android.os.Bundle; import android.os.Handler; import android.provider.ContactsContract; import com.vodafone360.people.MainApplication; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.utils.LogUtils; /** * SyncAdapter implementation which basically just ties in with * the old Contacts Sync Engine code for the moment and waits for the sync to be finished. * In the future we may want to improve this, particularly if the sync * is actually be done in this thread which would also enable disable sync altogether. */ public class SyncAdapter extends AbstractThreadedSyncAdapter implements IContactSyncObserver { // TODO: RE-ENABLE SYNC VIA SYSTEM // /** // * Direct access to Sync Engine stored for convenience // */ // private final ContactSyncEngine mSyncEngine = EngineManager.getInstance().getContactSyncEngine(); // // /** // * Boolean used to remember if we have requested a sync. // * Useful to ignore events // */ // private boolean mPerformSyncRequested = false; // /** * Delay when checking our Sync Setting when there is a authority auto-sync setting change. * This waiting time is necessary because in case it is our sync adapter authority setting * that changes we cannot query in the callback because the value is not yet changed! */ private static final int SYNC_SETTING_CHECK_DELAY = 2000; /** * Same as ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS * The reason we have this is just because the constant is not publicly defined before 2.2. */ private static final int SYNC_OBSERVER_TYPE_SETTINGS = 1; /** * Application object instance */ private final MainApplication mApplication; /** * Broadcast receiver used to listen for changes in the Master Auto Sync setting * intent: com.android.sync.SYNC_CONN_STATUS_CHANGED */ private final BroadcastReceiver mAutoSyncChangeBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { actOnAutoSyncSettings(); } }; /** * Observer for the global sync status setting. * There is no known way to only observe our sync adapter's setting. */ private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() { @Override public void onStatusChanged(int which) { mHandler.postDelayed(mRunnable, SYNC_SETTING_CHECK_DELAY); } }; /** * Handler used to post to a runnable in order to wait * for a short time before checking the sync adapter * authority sync setting after a global change occurs. */ private final Handler mHandler = new Handler(); /** * Runnable used to post to a runnable in order to wait * for a short time before checking the sync adapter * authority sync setting after a global change occurs. * The reason we use this kind of mechanism is because: * a) There is an intent(com.android.sync.SYNC_CONN_STATUS_CHANGED) * we can listen to for the Master Auto-sync but, * b) The authority auto-sync observer pattern using ContentResolver * listens to EVERY sync adapter setting on the device AND * when the callback is received the value is not yet changed so querying for it is useless. */ private final Runnable mRunnable = new Runnable() { @Override public void run() { actOnAutoSyncSettings(); } }; public SyncAdapter(Context context, MainApplication application) { // Automatically initialized (true) due to PAND-2304 super(context, true); mApplication = application; context.registerReceiver(mAutoSyncChangeBroadcastReceiver, new IntentFilter( "com.android.sync.SYNC_CONN_STATUS_CHANGED")); ContentResolver.addStatusChangeListener( SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver); // Necessary in case of Application update forceSyncSettingsInCaseOfAppUpdate(); // Register for sync event callbacks // TODO: RE-ENABLE SYNC VIA SYSTEM // mSyncEngine.addEventCallback(this); } /** * {@inheritDoc} */ @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { if(extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false)) { initialize(account, authority); return; } actOnAutoSyncSettings(); // TODO: RE-ENABLE SYNC VIA SYSTEM // try { // synchronized(this) { // mPerformSyncRequested = true; // if(!mSyncEngine.isSyncing()) { // mSyncEngine.startFullSync(); // } // // while(mSyncEngine.isSyncing()) { // wait(POOLING_WAIT_INTERVAL); // } // mPerformSyncRequested = false; // } // } catch (InterruptedException e) { // e.printStackTrace(); // } } /** * @see IContactSyncObserver#onContactSyncStateChange(Mode, State, State) */ @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { // TODO: RE-ENABLE SYNC VIA SYSTEM // synchronized(this) { // /* // * This check is done so that we can also update the native UI // * when the client devices to sync on it own // */ // if(!mPerformSyncRequested && // mode != Mode.NONE) { // mPerformSyncRequested = true; // Account account = new Account( // LoginPreferences.getUsername(), // NativeContactsApi2.PEOPLE_ACCOUNT_TYPE); // ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); // } // } } /** * @see IContactSyncObserver#onProgressEvent(State, int) */ @Override public void onProgressEvent(State currentState, int percent) { // Nothing to do } /** * @see IContactSyncObserver#onSyncComplete(ServiceStatus) */ @Override public void onSyncComplete(ServiceStatus status) { // Nothing to do } /** * Initializes Sync settings for this Sync Adapter * @param account The account associated with the initialization * @param authority The authority of the content */ public static void initialize(Account account, String authority) { ContentResolver.setIsSyncable(account, authority, 1); // > 0 means syncable ContentResolver.setSyncAutomatically(account, authority, true); } /** * Checks if this Sync Adapter is allowed to Sync Automatically * Basically just checking if the Master and its own Auto-sync are on. * The Master Auto-sync takes precedence over the authority Auto-sync. * @return true if the settings are enabled, false otherwise */ private boolean canSyncAutomatically() { Account account = getPeopleAccount(); if (account == null) { // There's no account in the system anyway so // just say true to avoid any issues with the application. return true; } boolean masterSyncAuto = ContentResolver.getMasterSyncAutomatically(); boolean syncAuto = ContentResolver.getSyncAutomatically(account, ContactsContract.AUTHORITY); - LogUtils.logD("SyncAdapter.canSyncAutomatically() [masterSync=" + + LogUtils.logE("SyncAdapter.canSyncAutomatically() [masterSync=" + masterSyncAuto + ", syncAuto=" + syncAuto + "]"); return masterSyncAuto && syncAuto; } /** * Sets the application data connection setting depending on whether or not * the Sync Adapter is allowed to Sync Automatically. * If Automatic Sync is enabled then connection is to online ("always connect") * Otherwise connection is set to offline ("manual connect") */ private synchronized void actOnAutoSyncSettings() { if(canSyncAutomatically()) { // Enable data connection mApplication.setInternetAvail(InternetAvail.ALWAYS_CONNECT, false); } else { // Disable data connection mApplication.setInternetAvail(InternetAvail.MANUAL_CONNECT, false); } } /** * This method is essentially needed to force the sync settings * to a consistent state in case of an Application Update. * This is because old versions of the client do not set * the sync adapter to syncable for the contacts authority. */ private void forceSyncSettingsInCaseOfAppUpdate() { NativeContactsApi nabApi = NativeContactsApi.getInstance(); nabApi.setSyncable(true); nabApi.setSyncAutomatically( mApplication.getInternetAvail() == InternetAvail.ALWAYS_CONNECT); } /** * Gets the first People Account found on the device or * null if none is found. * Beware! This method is basically duplicate code from * NativeContactsApi2.getPeopleAccount(). * Duplicating the code was found to be cleanest way to acess the functionality. * @return The Android People account found or null */ private Account getPeopleAccount() { android.accounts.Account[] accounts = AccountManager.get(mApplication).getAccountsByType(NativeContactsApi.PEOPLE_ACCOUNT_TYPE_STRING); if (accounts != null && accounts.length > 0) { Account ret = new Account(accounts[0].name, accounts[0].type); return ret; } return null; } } diff --git a/src/com/vodafone360/people/service/agent/NetworkAgent.java b/src/com/vodafone360/people/service/agent/NetworkAgent.java index 8a77804..fbbaf8f 100644 --- a/src/com/vodafone360/people/service/agent/NetworkAgent.java +++ b/src/com/vodafone360/people/service/agent/NetworkAgent.java @@ -1,714 +1,707 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.agent; import java.security.InvalidParameterException; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.ContentObserver; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.telephony.TelephonyManager; import android.text.format.DateUtils; import com.vodafone360.people.Intents; import com.vodafone360.people.MainApplication; import com.vodafone360.people.service.PersistSettings; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.interfaces.IConnectionManagerInterface; import com.vodafone360.people.service.interfaces.IWorkerThreadControl; import com.vodafone360.people.utils.LogUtils; /** * The network Agent monitors the connectivity status of the device and makes * decisions about the communication strategy. The Agent has the following * states {connected | disconnected}, with changes reported to various listeners * in the service. */ public class NetworkAgent { /** Roaming notification is on */ public static final int ROAMING_DIALOG_GLOBAL_ON = 0; /** Roaming notification is off */ public static final int ROAMING_DIALOG_GLOBAL_OFF = 1; private static final int TYPE_WIFI = 1; private static AgentState mAgentState = AgentState.UNKNOWN; private ConnectivityManager mConnectivityManager; private ContentResolver mContentResolver; private static AgentDisconnectReason sDisconnectReason = AgentDisconnectReason.UNKNOWN; private SettingsContentObserver mDataRoamingSettingObserver; private boolean mInternetConnected; private boolean mDataRoaming; private boolean mBackgroundData; private boolean mIsRoaming; private boolean mIsInBackground; private boolean mNetworkWorking = true; // dateTime value in milliseconds private Long mDisableRoamingNotificationUntil = null; private IWorkerThreadControl mWorkerThreadControl; private IConnectionManagerInterface mConnectionMgrIf; private Context mContext; public enum AgentState { CONNECTED, DISCONNECTED, UNKNOWN }; private boolean mWifiNetworkAvailable; private boolean mMobileNetworkAvailable; /** * Reasons for Service Agent changing state to disconnected */ public enum AgentDisconnectReason { AGENT_IS_CONNECTED, // Sanity check NO_INTERNET_CONNECTION, NO_WORKING_NETWORK, DATA_SETTING_SET_TO_MANUAL_CONNECTION, DATA_ROAMING_DISABLED, BACKGROUND_CONNECTION_DISABLED, // WIFI_INACTIVE, UNKNOWN } public enum StatesOfService { IS_CONNECTED_TO_INTERNET, IS_NETWORK_WORKING, IS_ROAMING, IS_ROAMING_ALLOWED, IS_INBACKGROUND, IS_BG_CONNECTION_ALLOWED, IS_WIFI_ACTIVE }; /** * Listens for changes made to People client's status. The NetworkAgent is * specifically interested in changes to the data settings (e.g. data * disabled, only in home network or roaming). */ private class SettingsContentObserver extends ContentObserver { private String mSettingName; private SettingsContentObserver(String settingName) { super(new Handler()); mSettingName = settingName; } /** * Start content observer. */ private void start() { if (mContentResolver != null) { mContentResolver.registerContentObserver(Settings.Secure.getUriFor(mSettingName), true, this); } } /** * De-activate content observer. */ private void close() { if (mContentResolver != null) { mContentResolver.unregisterContentObserver(this); } } @Override public void onChange(boolean selfChange) { onDataSettingChanged(mSettingName); } public boolean getBooleanValue() { if (mContentResolver != null) { try { return (Settings.Secure.getInt(mContentResolver, mSettingName) != 0); } catch (SettingNotFoundException e) { LogUtils.logE("NetworkAgent.SettingsContentObserver.getBooleanValue() " + "SettingNotFoundException", e); return false; } } return false; } } /** * The constructor. * * @param context Android context. * @param workerThreadControl Handle to kick the worker thread. * @param connMgrIf Handler to signal the connection manager. * @throws InvalidParameterException Context is NULL. * @throws InvalidParameterException IWorkerThreadControl is NULL. * @throws InvalidParameterException IConnectionManagerInterface is NULL. */ public NetworkAgent(Context context, IWorkerThreadControl workerThreadControl, IConnectionManagerInterface connMgrIf) { if (context == null) { throw new InvalidParameterException("NetworkAgent() Context canot be NULL"); } if (workerThreadControl == null) { throw new InvalidParameterException("NetworkAgent() IWorkerThreadControl canot be NULL"); } if (connMgrIf == null) { throw new InvalidParameterException( "NetworkAgent() IConnectionManagerInterface canot be NULL"); } mContext = context; mWorkerThreadControl = workerThreadControl; mConnectionMgrIf = connMgrIf; mContentResolver = context.getContentResolver(); mConnectivityManager = (ConnectivityManager)context .getSystemService(Context.CONNECTIVITY_SERVICE); mDataRoamingSettingObserver = new SettingsContentObserver(Settings.Secure.DATA_ROAMING); } /** * Create NetworkAgent and start observers of device connectivity state. * * @throws InvalidParameterException DataRoamingSettingObserver is NULL. * @throws InvalidParameterException Context is NULL. * @throws InvalidParameterException ConnectivityManager is NULL. */ public void onCreate() { if (mDataRoamingSettingObserver == null) { throw new InvalidParameterException( "NetworkAgent.onCreate() DataRoamingSettingObserver canot be NULL"); } if (mContext == null) { throw new InvalidParameterException("NetworkAgent.onCreate() Context canot be NULL"); } if (mConnectivityManager == null) { throw new InvalidParameterException( "NetworkAgent.onCreate() ConnectivityManager canot be NULL"); } mDataRoamingSettingObserver.start(); mDataRoaming = mDataRoamingSettingObserver.getBooleanValue(); mContext.registerReceiver(mBackgroundDataBroadcastReceiver, new IntentFilter( ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED)); mContext.registerReceiver(mInternetConnectivityReceiver, new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION)); mContext.registerReceiver(mServiceStateRoamingReceiver, new IntentFilter( "android.intent.action.SERVICE_STATE")); NetworkInfo info = mConnectivityManager.getActiveNetworkInfo(); if (info != null) { mInternetConnected = (info.getState() == NetworkInfo.State.CONNECTED); mWifiNetworkAvailable = (info.getType() == TYPE_WIFI); mIsRoaming = info.isRoaming(); } mBackgroundData = mConnectivityManager.getBackgroundDataSetting(); onConnectionStateChanged(); } /** * Destroy NetworkAgent and un-register observers. * * @throws InvalidParameterException Context is NULL. * @throws InvalidParameterException DataRoamingSettingObserver is NULL. */ public void onDestroy() { if (mContext == null) { throw new InvalidParameterException("NetworkAgent.onCreate() Context canot be NULL"); } if (mDataRoamingSettingObserver == null) { throw new InvalidParameterException( "NetworkAgent.onDestroy() DataRoamingSettingObserver canot be NULL"); } mContext.unregisterReceiver(mInternetConnectivityReceiver); mContext.unregisterReceiver(mBackgroundDataBroadcastReceiver); mContext.unregisterReceiver(mServiceStateRoamingReceiver); mDataRoamingSettingObserver.close(); mDataRoamingSettingObserver = null; } /** * Receive notification from * ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED */ private final BroadcastReceiver mBackgroundDataBroadcastReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogUtils .logV("NetworkAgent.broadcastReceiver.onReceive() ACTION_BACKGROUND_DATA_SETTING_CHANGED"); synchronized (NetworkAgent.this) { if (mConnectivityManager != null) { mBackgroundData = mConnectivityManager.getBackgroundDataSetting(); onConnectionStateChanged(); } } } }; /** * Receive notification from ConnectivityManager.CONNECTIVITY_ACTION */ private final BroadcastReceiver mInternetConnectivityReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() CONNECTIVITY_ACTION"); synchronized (NetworkAgent.this) { NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); if (info == null) { LogUtils.logW("NetworkAgent.broadcastReceiver.onReceive() EXTRA_NETWORK_INFO not found."); } else { if (info.getType() == TYPE_WIFI) { mWifiNetworkAvailable = (info.getState() == NetworkInfo.State.CONNECTED); } else { mMobileNetworkAvailable = (info.getState() == NetworkInfo.State.CONNECTED); } } if (noConnectivity) { LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() EXTRA_NO_CONNECTIVITY found!"); mInternetConnected = false; } else { mInternetConnected = mWifiNetworkAvailable || mMobileNetworkAvailable; } LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() mInternetConnected = " + mInternetConnected + ", mWifiNetworkAvailable = " + mWifiNetworkAvailable + ", mMobileNetworkAvailable = " + mMobileNetworkAvailable); onConnectionStateChanged(); } } }; /** * Receive notification from android.intent.action.SERVICE_STATE */ private final BroadcastReceiver mServiceStateRoamingReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() SERVICE_STATE"); synchronized (NetworkAgent.this) { // //ConnectivityManager provides wrong information about // roaming // NetworkInfo info = // mConnectivityManager.getActiveNetworkInfo(); // if (info != null) { // mIsRoaming = info.isRoaming(); // } LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() Extras are: " + intent.getExtras()); Bundle bu = intent.getExtras(); // int state = bu.getInt("state"); boolean roam = bu.getBoolean("roaming"); mIsRoaming = roam; onConnectionStateChanged(); LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() Network Roaming = " + mIsRoaming); LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() WiFi active = " + mWifiNetworkAvailable); } processRoaming(null); } }; /** * Notify interested parties of changes in Internet setting. * * @param val updated InternetAvail value. */ public void notifyDataSettingChanged(InternetAvail val) { processRoaming(val); onConnectionStateChanged(); } /** * Displaying notification to the user about roaming * * @param InternetAvail value. */ private void processRoaming(InternetAvail val) { InternetAvail internetAvail; if (val != null) { internetAvail = val; } else { internetAvail = getInternetAvailSetting(); } Intent intent = new Intent(); if (mContext != null && mIsRoaming && (internetAvail == InternetAvail.ALWAYS_CONNECT) && (mDisableRoamingNotificationUntil == null || mDisableRoamingNotificationUntil < System .currentTimeMillis())) { LogUtils.logV("NetworkAgent.processRoaming() " + "Displaying notification - DisplayRoaming[" + mIsRoaming + "]"); intent.setAction(Intents.ROAMING_ON); } else { /* * We are not roaming then we should remove notification, if no * notification were before nothing happens */ LogUtils.logV("NetworkAgent.processRoaming() Removing notification - " + " DisplayRoaming[" + mIsRoaming + "]"); intent.setAction(Intents.ROAMING_OFF); } mContext.sendBroadcast(intent); } private InternetAvail getInternetAvailSetting() { if (mContext != null) { PersistSettings setting = ((MainApplication)((RemoteService)mContext).getApplication()) .getDatabase().fetchOption(PersistSettings.Option.INTERNETAVAIL); if (setting != null) { return setting.getInternetAvail(); } } return null; } public int getRoamingNotificationType() { int type; if (mDataRoaming) { type = ROAMING_DIALOG_GLOBAL_ON; } else { type = ROAMING_DIALOG_GLOBAL_OFF; } return type; } /** * Get current device roaming setting. * * @return current device roaming setting. */ public boolean getRoamingDeviceSetting() { return mDataRoaming; } public void setShowRoamingNotificationAgain(boolean showAgain) { LogUtils.logV("NetworkAgent.setShowRoamingNotificationAgain() " + "showAgain[" + showAgain + "]"); if (showAgain) { mDisableRoamingNotificationUntil = null; } else { mDisableRoamingNotificationUntil = System.currentTimeMillis() + DateUtils.DAY_IN_MILLIS; if (mContext != null) { LogUtils.logV("NetworkAgent.setShowRoamingNotificationAgain() " + "Next notification on [" + DateUtils.formatDateTime(mContext, mDisableRoamingNotificationUntil, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_YEAR) + "]"); } } processRoaming(null); } /** * Received when user modifies one of the system settings */ private synchronized void onDataSettingChanged(String settingName) { LogUtils.logV("NetworkAgent.onDataSettingChanged() settingName[" + settingName + "]" + " has changed"); if (settingName.equals(Settings.Secure.DATA_ROAMING)) { if (mDataRoamingSettingObserver != null) { mDataRoaming = mDataRoamingSettingObserver.getBooleanValue(); onConnectionStateChanged(); } } } /** * Contains the main logic that determines the agent state for network * access */ private void onConnectionStateChanged() { if (mContext != null) { MainApplication app = (MainApplication)((RemoteService)mContext).getApplication(); - if ((app.getInternetAvail() == InternetAvail.MANUAL_CONNECT)/* - * AA: I - * commented - * it - - * TBD - * &&! - * mWifiNetworkAvailable - */) { + if ((app.getInternetAvail() == InternetAvail.MANUAL_CONNECT)) { LogUtils.logV("NetworkAgent.onConnectionStateChanged()" + " Internet allowed only in manual mode"); sDisconnectReason = AgentDisconnectReason.DATA_SETTING_SET_TO_MANUAL_CONNECTION; setNewState(AgentState.DISCONNECTED); return; } } if (!mNetworkWorking) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() Network is not working"); sDisconnectReason = AgentDisconnectReason.NO_WORKING_NETWORK; setNewState(AgentState.DISCONNECTED); return; } if (mIsRoaming && !mDataRoaming && !mWifiNetworkAvailable) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() " + "Connect while roaming not allowed"); sDisconnectReason = AgentDisconnectReason.DATA_ROAMING_DISABLED; setNewState(AgentState.DISCONNECTED); return; } if (mIsInBackground && !mBackgroundData) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() Background connection not allowed"); sDisconnectReason = AgentDisconnectReason.BACKGROUND_CONNECTION_DISABLED; setNewState(AgentState.DISCONNECTED); return; } if (!mInternetConnected) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() No internet connection"); sDisconnectReason = AgentDisconnectReason.NO_INTERNET_CONNECTION; setNewState(AgentState.DISCONNECTED); return; } if (mWifiNetworkAvailable) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() WIFI connected"); } else { LogUtils.logV("NetworkAgent.onConnectionStateChanged() Cellular connected"); } LogUtils.logV("NetworkAgent.onConnectionStateChanged() Connection available"); setNewState(AgentState.CONNECTED); } public static AgentState getAgentState() { LogUtils.logV("NetworkAgent.getAgentState() mAgentState[" + mAgentState.name() + "]"); return mAgentState; } public static ServiceStatus getServiceStatusfromDisconnectReason() { if (sDisconnectReason != null) switch (sDisconnectReason) { case AGENT_IS_CONNECTED: return ServiceStatus.SUCCESS; case NO_WORKING_NETWORK: return ServiceStatus.ERROR_NO_INTERNET; case NO_INTERNET_CONNECTION: return ServiceStatus.ERROR_NO_INTERNET; case DATA_ROAMING_DISABLED: return ServiceStatus.ERROR_ROAMING_INTERNET_NOT_ALLOWED; case DATA_SETTING_SET_TO_MANUAL_CONNECTION: return ServiceStatus.ERROR_NO_AUTO_CONNECT; case BACKGROUND_CONNECTION_DISABLED: // TODO: define appropriate ServiceStatus return ServiceStatus.ERROR_COMMS; } return ServiceStatus.ERROR_COMMS; } private void setNewState(AgentState newState) { if (newState == mAgentState) { return; } LogUtils.logI("NetworkAgent.setNewState(): " + mAgentState + " -> " + newState); mAgentState = newState; if (newState == AgentState.CONNECTED) { sDisconnectReason = AgentDisconnectReason.AGENT_IS_CONNECTED; onConnected(); } else if (newState == AgentState.DISCONNECTED) { onDisconnected(); } } private void onConnected() { checkActiveNetworkState(); if (mWorkerThreadControl != null) { mWorkerThreadControl.kickWorkerThread(); } if (mConnectionMgrIf != null) { mConnectionMgrIf.signalConnectionManager(true); } } private void onDisconnected() { // AA:need to kick it to make engines run and set the if (mWorkerThreadControl != null) { mWorkerThreadControl.kickWorkerThread(); } if (mConnectionMgrIf != null) { mConnectionMgrIf.signalConnectionManager(false); } } private void checkActiveNetworkState() { if (mConnectivityManager != null) { NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo == null) { LogUtils.logW("NetworkAgent.checkActiveNetworkInfoy() " + "mConnectivityManager.getActiveNetworkInfo() Returned null"); return; } else { if (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { LogUtils.logV("NetworkAgent.checkActiveNetworkInfoy() WIFI network"); // TODO: Do something } else if (mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { LogUtils.logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE and ROAMING"); // TODO: Do something // Only works when you are registering with network switch (mNetworkInfo.getSubtype()) { case TelephonyManager.NETWORK_TYPE_EDGE: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE EDGE network"); // TODO: Do something break; case TelephonyManager.NETWORK_TYPE_GPRS: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE GPRS network"); // TODO: Do something break; case TelephonyManager.NETWORK_TYPE_UMTS: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE UMTS network"); // TODO: Do something break; case TelephonyManager.NETWORK_TYPE_UNKNOWN: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE UNKNOWN network"); // TODO: Do something break; default: // Do nothing. break; } ; } } } else { LogUtils.logW("NetworkAgent.checkActiveNetworkInfoy() mConnectivityManager is null"); } } public void setNetworkAgentState(NetworkAgentState state) { LogUtils.logD("NetworkAgent.setNetworkAgentState() state[" + state + "]"); // TODO: make assignments if any changes boolean changes[] = state.getChanges(); if (changes[StatesOfService.IS_CONNECTED_TO_INTERNET.ordinal()]) mInternetConnected = state.isInternetConnected(); if (changes[StatesOfService.IS_NETWORK_WORKING.ordinal()]) mNetworkWorking = state.isNetworkWorking(); if (changes[StatesOfService.IS_ROAMING_ALLOWED.ordinal()]) mDataRoaming = state.isRoamingAllowed(); if (changes[StatesOfService.IS_INBACKGROUND.ordinal()]) mIsInBackground = state.isInBackGround(); if (changes[StatesOfService.IS_BG_CONNECTION_ALLOWED.ordinal()]) mBackgroundData = state.isBackDataAllowed(); if (changes[StatesOfService.IS_WIFI_ACTIVE.ordinal()]) mWifiNetworkAvailable = state.isWifiActive(); if (changes[StatesOfService.IS_ROAMING.ordinal()]) {// special case for // roaming mIsRoaming = state.isRoaming(); // This method sets the mAgentState, and mDisconnectReason as well // by calling setNewState(); onConnectionStateChanged(); processRoaming(null); } else // This method sets the mAgentState, and mDisconnectReason as well // by calling setNewState(); onConnectionStateChanged(); } public NetworkAgentState getNetworkAgentState() { NetworkAgentState state = new NetworkAgentState(); state.setRoaming(mIsRoaming); state.setRoamingAllowed(mDataRoaming); state.setBackgroundDataAllowed(mBackgroundData); state.setInBackGround(mIsInBackground); state.setInternetConnected(mInternetConnected); state.setNetworkWorking(mNetworkWorking); state.setWifiActive(mWifiNetworkAvailable); state.setDisconnectReason(sDisconnectReason); state.setAgentState(mAgentState); LogUtils.logD("NetworkAgent.getNetworkAgentState() state[" + state + "]"); return state; } // ///////////////////////////// // FOR TESTING PURPOSES ONLY // // ///////////////////////////// /** * Forces the AgentState to a specific value. * * @param newState the state to set Note: to be used only for test purposes */ public static void setAgentState(AgentState newState) { mAgentState = newState; } }
360/360-Engine-for-Android
ae9de93fd6647fe0b14bf53774a82e5d0d03b2f8
PAND-2360 call getMyIdentities() after the credentials are validated
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 9fffe3e..3396162 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,969 +1,977 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.identities; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import android.os.Bundle; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Identities; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.ThirdPartyAccount; /** * Engine responsible for handling retrieval and validation of Identities (e.g. * 3rd party/web accounts). The Identities engine can fetch a list of available * accounts, and set required capabilities and validate credentials for * specified accounts. */ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { /** * States for IdentitiesEngine. States are based on the requests that the * engine needs to handle. */ private enum State { IDLE, FETCHING_IDENTITIES, VALIDATING_IDENTITY_CREDENTIALS, SETTING_IDENTITY_STATUS, GETTING_MY_IDENTITIES, GETTING_MY_CHATABLE_IDENTITIES, DELETE_IDENTITY } /** * Mutex for thread synchronisation */ private final Object mMutex = new Object(); /** * Container class for Identity Capability Status request. Consists of a * network, identity id and a filter containing the required capabilities. */ private static class IdentityStatusRequest { private String mNetwork; private String mIdentityId; private String mIdentityStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setIdentityStatus(String status) { mIdentityStatus = status; } } /** * Container class encapsulating an Identity validation request containing: * dry-run flag, network, user-name, password, set of required capabilities. */ private static class IdentityValidateCredentialsRequest { /** Performs a dry run if true. */ private boolean mDryRun; /** Network to sign into. */ private String mNetwork; /** Username to sign into identity with. */ private String mUserName; /** Password to sign into identity with. */ private String mPassword; private Map<String, Boolean> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } /** * * Container class for Delete Identity request. Consist network and identity id. * */ private static class DeleteIdentityRequest { /** Network to delete.*/ private String mNetwork; /** IdentityID which needs to be Deleted.*/ private String mIdentityId; } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mMyIdentityList; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; /** * Maintaining DeleteIdentityRequest so that it can be later removed from * maintained cache. **/ private DeleteIdentityRequest identityToBeDeleted; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; mMyIdentityList = new ArrayList<Identity>(); mAvailableIdentityList = new ArrayList<Identity>(); mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { final ArrayList<Identity> availableIdentityList; synchronized(mAvailableIdentityList) { // make a shallow copy availableIdentityList = new ArrayList<Identity>(mAvailableIdentityList); } if ((availableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return availableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { final ArrayList<Identity> myIdentityList; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } if ((myIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return myIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = getMyThirdPartyChattableIdentities(); // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chattableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chattableIdentities; } /** * * Takes all third party identities that have a chat capability set to true. * * @return A list of chattable 3rd party identities the user is signed in to. If the retrieval identities failed the returned list will be empty. * */ public ArrayList<Identity> getMyThirdPartyChattableIdentities() { final ArrayList<Identity> chattableIdentities = new ArrayList<Identity>(); final ArrayList<Identity> myIdentityList; final int identityListSize; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } identityListSize = myIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = myIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue)) { chattableIdentities.add(identity); break; } } } return chattableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Delete the given social network. * * @param network Name of the identity, * @param identityId Id of identity. */ public final void addUiDeleteIdentityRequest(final String network, final String identityId) { LogUtils.logD("IdentityEngine.addUiRemoveIdentity()"); DeleteIdentityRequest data = new DeleteIdentityRequest(); data.mNetwork = network; data.mIdentityId = identityId; /**maintaining the sent object*/ setIdentityToBeDeleted(data); addUiRequestToQueue(ServiceUiRequest.DELETE_IDENTITY, data); } /** * Setting the DeleteIdentityRequest object. * * @param data */ private void setIdentityToBeDeleted(final DeleteIdentityRequest data) { identityToBeDeleted = data; } /** * Return the DeleteIdentityRequest object. * */ private DeleteIdentityRequest getIdentityToBeDeleted() { return identityToBeDeleted; } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { + case GET_MY_IDENTITIES: + sendGetMyIdentitiesRequest(); + completeUiRequest(ServiceStatus.SUCCESS); + break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; case DELETE_IDENTITY: executeDeleteIdentityRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to delete the identity as specified . (Request is not issued if there * is currently no connectivity). * * @param data bundled request data containing network and identityId. */ private void executeDeleteIdentityRequest(final Object data) { if (!isConnected()) { completeUiRequest(ServiceStatus.ERROR_NO_INTERNET); } newState(State.DELETE_IDENTITY); DeleteIdentityRequest reqData = (DeleteIdentityRequest) data; if (!setReqId(Identities.deleteIdentity(this, reqData.mNetwork, reqData.mIdentityId))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(DecodedResponse resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if ((null == resp) || (null == resp.mDataTypes)) { LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); return; } // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; case BaseDataType.IDENTITY_DELETION_DATA_TYPE: handleDeleteIdentity(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); } } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { Identity identity = (Identity)item; mMyIdentityList.add(identity); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); + + if (errorStatus == ServiceStatus.SUCCESS) { + addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, null); + } } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response of request to delete the identity. The response * should be a status that whether the operation is succeeded or not. The * response will be a status result otherwise ERROR_UNEXPECTED_RESPONSE if * the response is not as expected. * * @param data * List of BaseDataTypes generated from Server response. */ private void handleDeleteIdentity(final List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus( BaseDataType.IDENTITY_DELETION_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { for (BaseDataType item : data) { if (item.getType() == BaseDataType.IDENTITY_DELETION_DATA_TYPE) { synchronized(mMyIdentityList) { // iterating through the subscribed identities for (Identity identity : mMyIdentityList) { if (identity.mIdentityId .equals(getIdentityToBeDeleted().mIdentityId)) { mMyIdentityList.remove(identity); break; } } } completeUiRequest(ServiceStatus.SUCCESS); return; } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } } completeUiRequest(errorStatus, bu); } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; synchronized (mAvailableIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mAvailableIdentityList); } } else { requestKey = KEY_MY_IDS; synchronized (mMyIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mMyIdentityList); } } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } /** * * Retrieves the filter for the getAvailableIdentities and getMyIdentities * calls. * * @return The identities filter in form of a bundle. * */ private Bundle getIdentitiesFilter() { Bundle b = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); l.add(IdentityCapability.CapabilityID.get_own_status.name()); b.putStringArrayList("capability", l); return b; } @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } /** * Generate Map containing String capability filters for m supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, List<String>> prepareStringFilter(Bundle filter) { Map<String, List<String>> returnFilter = null; if (filter != null && filter.keySet().size() > 0) { returnFilter = new Hashtable<String, List<String>>(); for (String key : filter.keySet()) { returnFilter.put(key, filter.getStringArrayList(key)); } } else { returnFilter = null; } return returnFilter; } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ /** {@inheritDoc} */ @Override public final void onReset() { super.onReset(); mMyIdentityList.clear(); mAvailableIdentityList.clear(); mStatusList.clear(); mState = State.IDLE; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of Identity objects, can be NULL. * @return TRUE if the given Identity contains a Facebook account. */ public boolean isFacebookInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_FACEBOOK)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given Identity contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given Identity contains a Hyves account. */ public boolean isHyvesInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_HYVES)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Hyves not found in list"); return false; } }
360/360-Engine-for-Android
7676a982f733134ca8a834001242ed918869f163
Fix for PAND-2379.
diff --git a/src/com/vodafone360/people/Settings.java b/src/com/vodafone360/people/Settings.java index 3fca4e1..d4da58a 100644 --- a/src/com/vodafone360/people/Settings.java +++ b/src/com/vodafone360/people/Settings.java @@ -1,307 +1,306 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; /** * All application settings. */ public final class Settings { /* * LogCat. */ /** LogCat TAG prefix. **/ public static final String LOG_TAG = "People_"; /* * Transport. */ /** Milliseconds until HTTP connection will time out. */ public static final int HTTP_CONNECTION_TIMEOUT = 30000; /** Maximum number of HTTP connection attempts. */ public static final int HTTP_MAX_RETRY_COUNT = 3; /** HTTP header content type. */ public static final String HTTP_HEADER_CONTENT_TYPE = "application/binary"; /** Number of empty RPG poll responses before stopping RPG poll. */ public static final int BLANK_RPG_HEADER_COUNT = 4; /** TCP Heartbeat interval (10 seconds). */ public static final long TCP_VF_HEARTBEAT_INTERVAL = 10 * 60 * 1000; /** TCP retry interval if we have lost the connection (30 seconds). */ public static final long TCP_RETRY_BROKEN_CONNECTION_INTERVAL = 30 * 60 * 1000; /** TCP socket read time out for the read-operation. */ public static final int TCP_SOCKET_READ_TIMEOUT = 10 * 60 * 1000; /* * Notifications. */ /** LED colour. */ public static final int NOTIFICATION_LED_COLOR = 0xff00ff00; // Green /** LED on time. */ public static final int NOTIFICATION_LED_OFF_TIME = 300; /** LED on time. */ public static final int NOTIFICATION_LED_ON_TIME = 1000; /* * Upgrade Engine */ /** * See UpdateSettingsActivity.FREQUENCY_SETTING_LONG array for meaning (i.e. * Every 6 hours) */ public static final int PREFS_CHECK_FREQUENCY_DEFAULT = 3; /** Show the upgrade dialog box every 10 minutes. */ public static final int DIALOG_CHECK_FREQUENCY_MILLIS = 10 * 60 * 1000; /** * Component trace flags (always checked in as false, not part of build * script). */ /** Trace output for engine components. **/ public static final boolean ENABLED_ENGINE_TRACE = false; /** Trace output for database components. **/ public static final boolean ENABLED_DATABASE_TRACE = false; /** Trace output for contact synchronisation components. **/ public static final boolean ENABLED_CONTACTS_SYNC_TRACE = false; /** Log engine runtime information to file for profiling. **/ public static final boolean ENABLED_PROFILE_ENGINES = false; /** Trace output for protocol (i.e. network IO) components. **/ public static boolean sEnableProtocolTrace = false; /** * This is a list of strings containing the names of engines to be * deactivated in the build. A de-activated engine is constructed but will * never be run (nor will onCreate or onDestroy be called). Any UI requests * will be automatically completed by the framework with a * ServiceStatus.ERROR_NOT_IMPLEMENTED error. */ public static final String DEACTIVATE_ENGINE_LIST_KEY = "deactivated-engines-list"; /* * Hard coded settings */ /** Enable dialler cheat code. **/ public static final boolean DIALER_CHEATCODES_ENABLED = true; /** Enable SMS account activation. **/ public static final boolean ENABLE_ACTIVATION = false; /** * Enable SIM inserted check. Always set to TRUE. Makes the application * unusable if there is no valid SIM card inserted into the device. */ public static final boolean ENABLE_SIM_CHECK = true; /** Enable fetching native contacts. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS = true; /** Enable fetching native contacts on change. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS_ON_CHANGE = true; /** Enable ME profile synchronisation. **/ public static final boolean ENABLE_ME_PROFILE_SYNC = true; /** Enable server contact synchronisation. **/ public static final boolean ENABLE_SERVER_CONTACT_SYNC = true; /** Enable server thumbnail synchronisation. **/ public static final boolean ENABLE_THUMBNAIL_SYNC = true; /** Enable update native contacts synchronisation. **/ public static final boolean ENABLE_UPDATE_NATIVE_CONTACTS = true; /** Enable hiding of connected friends group. **/ public static final boolean HIDE_CONNECTED_FRIENDS_GROUP = true; /** Disable the native sync after the first time import for Android 1.X devices only **/ public static final boolean DISABLE_NATIVE_SYNC_AFTER_IMPORT_ON_ANDROID_1X = true; /* * Keys for properties that can be changed at build time. */ /** Key for application ID setting. **/ public static final String APP_KEY_ID = "app-key-id"; /** Key for application secret key setting. **/ public static final String APP_SECRET_KEY = "app-secret-key"; /** Key for enable logging setting. **/ protected static final String ENABLE_LOGCAT_KEY = "enable-logcat"; /** Key for enable RPG setting. **/ public static final String ENABLE_RPG_KEY = "use-rpg"; /** Key for enable SNS resource icon setting. **/ public static final String ENABLE_SNS_RESOURCE_ICON_KEY = "enable-sns-resource-icon"; /** Key for RPG server URL setting. **/ public static final String RPG_SERVER_KEY = "rpg-url"; /** Key for Hessian URL setting. **/ public static final String SERVER_URL_HESSIAN_KEY = "hessian-url"; /** Key for enabling 3rd party applications to access data via AIDL. **/ public static final String ENABLE_AIDL_KEY = "allow-aidl"; /** Default setting ENABLE_AIDL_KEY. **/ public static final String ENABLE_AIDL_DEFAULT = "false"; /* * Keys without defaults. */ /** Key for TCP server URL setting. **/ public static final String TCP_RPG_URL_KEY = "rpg-tcp-url"; /** Key for TCP port setting. **/ public static final String TCP_RPG_PORT_KEY = "rpg-tcp-port"; /** Key for upgrade check URL setting. **/ public static final String UPGRADE_CHECK_URL_KEY = "upgrade-url"; /* * Default for properties that can be changed at build time. */ /** Default for logging enabled setting. **/ protected static final String DEFAULT_ENABLE_LOGCAT = "true"; /** Default for RPG enabled setting. **/ protected static final String DEFAULT_ENABLE_RPG = "true"; /** Default for SNS resource icon setting. **/ protected static final String DEFAULT_ENABLE_SNS_RESOURCE_ICON = "true"; /** Default for RPG server URL setting. **/ protected static final String DEFAULT_RPG_SERVER = "http://rpg.vodafone360.com/rpg/mcomet/"; /** Default for Hessian URL setting. **/ protected static final String DEFAULT_SERVER_URL_HESSIAN = "http://api.vodafone360.com/services/hessian/"; /* * Request timeouts for all engines and requests, except for fire and * forget calls to RPG: SET_AVAILABILITY and SEND_CHAT_MSG. */ /** Do not handle timeouts for this API. **/ private static final long DONT_HANDLE_TIMEOUTS = -1; /** Generic timeout for requests. **/ private static final long ALL_ENGINES_REQUESTS_TIMEOUT = 60000; /** Timeout for all presence API requests. **/ private static final long PRESENCE_ENGINE_REQUESTS_TIMEOUT = 120000; /** Number of milliseconds in a week. **/ public static final long HISTORY_IS_WEEK_LONG = 7 * 24 * 60 * 60 * 1000; /** Timeout for request waiting in queue. **/ public static final long REMOVE_REQUEST_FROM_QUEUE_MILLIS = 15 * 60 * 1000; /* * The timeouts in milliseconds for the different APIs. */ /** Timeout for activities API. **/ public static final long API_REQUESTS_TIMEOUT_ACTIVITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for authentication API. **/ public static final long API_REQUESTS_TIMEOUT_AUTH = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat create conversation API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_CREATE_CONV = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat send message API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_SEND_MESSAGE = DONT_HANDLE_TIMEOUTS; /** Timeout for contacts API. **/ public static final long API_REQUESTS_TIMEOUT_CONTACTS = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for group privacy API. **/ public static final long API_REQUESTS_TIMEOUT_GROUP_PRIVACY = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for identities API. **/ public static final long API_REQUESTS_TIMEOUT_IDENTITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for presence list API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_LIST = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Timeout for presence set availability API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Enable Facebook chat. **/ public static boolean sEnableFacebookChat = true; /** * Danger! Only set to true if you know what you are doing! This logs each * response no matter if gzipped or not to the SD card under the given * request ID. */ - public static boolean sEnableSuperExpensiveResponseFileLogging - = false; + public static boolean sEnableSuperExpensiveResponseFileLogging = false; /** * Private constructor to prevent instantiation. */ private Settings() { } /** * a debug flag to see what's coming with availability state change push messages. */ public static boolean LOG_PRESENCE_PUSH_ON_LOGCAT = false; } \ No newline at end of file diff --git a/src/com/vodafone360/people/database/DatabaseHelper.java b/src/com/vodafone360/people/database/DatabaseHelper.java index 25ecb2e..ec1b2e7 100644 --- a/src/com/vodafone360/people/database/DatabaseHelper.java +++ b/src/com/vodafone360/people/database/DatabaseHelper.java @@ -1,1336 +1,1334 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.database; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Timer; import java.util.TimerTask; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import android.os.Handler; import android.os.Message; import android.util.Log; import com.vodafone360.people.MainApplication; import com.vodafone360.people.Settings; import com.vodafone360.people.database.tables.ActivitiesTable; import com.vodafone360.people.database.tables.ContactChangeLogTable; import com.vodafone360.people.database.tables.ContactDetailsTable; import com.vodafone360.people.database.tables.ContactGroupsTable; import com.vodafone360.people.database.tables.ContactSourceTable; import com.vodafone360.people.database.tables.ContactSummaryTable; import com.vodafone360.people.database.tables.ContactsTable; import com.vodafone360.people.database.tables.ConversationsTable; import com.vodafone360.people.database.tables.GroupsTable; import com.vodafone360.people.database.tables.MePresenceCacheTable; import com.vodafone360.people.database.tables.NativeChangeLogTable; import com.vodafone360.people.database.tables.PresenceTable; import com.vodafone360.people.database.tables.StateTable; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.database.tables.ContactChangeLogTable.ContactChangeInfo; import com.vodafone360.people.database.tables.ContactDetailsTable.Field; import com.vodafone360.people.datatypes.ActivityItem; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactDetail; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.PublicKeyDetails; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.ContactDetail.DetailKeyTypes; import com.vodafone360.people.datatypes.ContactDetail.DetailKeys; import com.vodafone360.people.engine.contactsync.ContactChange; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.engine.presence.PresenceDbUtils; import com.vodafone360.people.service.PersistSettings; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.interfaces.IPeopleService; import com.vodafone360.people.utils.CloseUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.StringBufferPool; import com.vodafone360.people.utils.ThumbnailUtils; import com.vodafone360.people.utils.WidgetUtils; /** * The main interface to the client database. * <p> * The {@link #DATABASE_VERSION} field must be increased each time any change is * made to the database schema. This includes any changes to the table name or * fields in table classes and any change to persistent settings. * <p> * All database functionality should be implemented in one of the table Table or * Utility sub classes * * @version %I%, %G% */ public class DatabaseHelper extends SQLiteOpenHelper { private static final String LOG_TAG = Settings.LOG_TAG + "Database"; /** * The name of the database file. */ private static final String DATABASE_NAME = "people.db"; /** * The name of the presence database file which is in memory. */ public static final String DATABASE_PRESENCE = "presence1_db"; /** * Contains the database version. Must be increased each time the schema is * changed. **/ private static final int DATABASE_VERSION = 63; private final List<Handler> mUiEventCallbackList = new ArrayList<Handler>(); private Context mContext; private boolean mMeProfileAvatarChangedFlag; private boolean mDbUpgradeRequired; /** * Time period in which the sending of database change events to the UI is delayed. * During this time period duplicate event types are discarded to avoid clogging the * event queue (esp. during first time sync). */ private static final long DATABASE_EVENT_DELAY = 1000; // ms /** * Timer to implement a wait before sending database change events to the UI in * order to prevent clogging the queue with duplicate events. */ private final Timer mDbEventTimer = new Timer(); /** * SELECT DISTINCT LocalId FROM NativeChangeLog UNION SELECT DISTINCT * LocalId FROM ContactDetails WHERE NativeSyncId IS NULL OR NativeSyncId <> * -1 ORDER BY 1 */ private final static String QUERY_NATIVE_SYNCABLE_CONTACTS_LOCAL_IDS = NativeChangeLogTable.QUERY_MODIFIED_CONTACTS_LOCAL_IDS_NO_ORDERBY + " UNION " + ContactDetailsTable.QUERY_NATIVE_SYNCABLE_CONTACTS_LOCAL_IDS + " ORDER BY 1"; /** * Datatype holding a database change event. This datatype is used to collect unique * events for a certain period before sending them to the UI to avoid clogging of the * event queue. */ private class DbEventType { @Override public boolean equals(Object o) { boolean isEqual = false; if (o instanceof DbEventType) { DbEventType event = (DbEventType) o; if ( (event.ordinal == this.ordinal) &&(event.isExternal == this.isExternal)) { isEqual = true; } } return isEqual; } int ordinal; boolean isExternal; } /** * List of database change events which needs to be sent to the UI as soon as the a * certain amount of time has passed. */ private final List<DbEventType> mDbEvents = new ArrayList<DbEventType>(); /** * Timer task which implements the actualy sending of all stored database change events * to the UI. */ private class DbEventTimerTask extends TimerTask { public void run() { synchronized (mDbEvents) { for (DbEventType event:mDbEvents ) { fireEventToUi(ServiceUiRequest.DATABASE_CHANGED_EVENT, event.ordinal, (event.isExternal ? 1 : 0), null); } mDbEvents.clear(); } } }; /** * Used for passing server contact IDs around. */ public static class ServerIdInfo { public Long localId; public Long serverId; public Long userId; } /** * Used for passing contact avatar information around. * * @see #fetchThumbnailUrls */ public static class ThumbnailInfo { public Long localContactId; public String photoServerUrl; } /** * An instance of this enum is passed to database change listeners to define * the database change type. */ public static enum DatabaseChangeType { CONTACTS, ACTIVITIES, ME_PROFILE, ME_PROFILE_PRESENCE_TEXT } /*** * Public Constructor. * * @param context Android context */ public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mContext = context; /* * // Uncomment the next line to reset the database // * context.deleteDatabase(DATABASE_NAME); // copyDatabaseToSd(); */ } /** * Constructor. * * @param context the Context where to create the database * @param name the name of the database */ public DatabaseHelper(Context context, String name) { super(context, name, null, DATABASE_VERSION); mContext = context; } /** * Called the first time the database is generated to create all tables. * * @param db An open SQLite database object */ @Override public void onCreate(SQLiteDatabase db) { try { ContactsTable.create(db); ContactDetailsTable.create(db); ContactSummaryTable.create(db); StateTable.create(db); ContactChangeLogTable.create(db); NativeChangeLogTable.create(db); GroupsTable.create(mContext, db); ContactGroupsTable.create(db); ContactSourceTable.create(db); ActivitiesTable.create(db); ConversationsTable.create(db); } catch (SQLException e) { LogUtils.logE("DatabaseHelper.onCreate() SQLException: Unable to create DB table", e); } } /** * Called whenever the database is opened. * * @param db An open SQLite database object */ @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); // Adding the creation code for the MePresenceCacheTable here because this older // versions of the client do not contain this table MePresenceCacheTable.create(db); db.execSQL("ATTACH DATABASE ':memory:' AS " + DATABASE_PRESENCE + ";"); PresenceTable.create(db); } /*** * Delete and then recreate a newer database structure. Note: Only called * from tests. * * @param db An open SQLite database object * @param oldVersion The current database version on the device * @param newVersion The required database version */ // TODO: This is only called from the tests!!!! @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { try { trace(true, "DatabaseHelper.onUpgrade() Upgrading database version from [" + oldVersion + "] to [" + newVersion + "]"); mContext.deleteDatabase(DATABASE_NAME); mDbUpgradeRequired = true; } catch (SQLException e) { LogUtils.logE("DatabaseHelper.onUpgrade() SQLException: Unable to upgrade database", e); } } /*** * Deletes the database and then fires a Database Changed Event to the UI. */ private void deleteDatabase() { trace(true, "DatabaseHelper.deleteDatabase()"); synchronized (this) { getReadableDatabase().close(); mContext.deleteDatabase(DATABASE_NAME); } fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); } /*** * Called when the Application is first started. */ public void start() { SQLiteDatabase mDb = getReadableDatabase(); if (mDbUpgradeRequired) { mDbUpgradeRequired = false; mDb.close(); mDb = getReadableDatabase(); } mMeProfileAvatarChangedFlag = StateTable.fetchMeProfileAvatarChangedFlag(mDb); } /*** * Adds a contact to the database and fires an internal database change * event. * * @param contact A {@link Contact} object which contains the details to be * added * @return SUCCESS or a suitable error code * @see #deleteContact(long) * @see #addContactDetail(ContactDetail) * @see #modifyContactDetail(ContactDetail) * @see #deleteContactDetail(long) * @see #addContactToGroup(long, long) * @see #deleteContactFromGroup(long, long) */ public ServiceStatus addContact(Contact contact) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.addContact() contactID[" + contact.contactID + "] nativeContactId[" + contact.nativeContactId + "]"); } List<Contact> mContactList = new ArrayList<Contact>(); mContactList.add(contact); ServiceStatus mStatus = syncAddContactList(mContactList, true, true); if (ServiceStatus.SUCCESS == mStatus) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); } return mStatus; } /*** * Deletes a contact from the database and fires an internal database change * event. * * @param localContactID The local ID of the contact to delete * @return SUCCESS or a suitable error code * @see #addContact(Contact) * @see #addContactDetail(ContactDetail) * @see #modifyContactDetail(ContactDetail) * @see #deleteContactDetail(long) * @see #addContactToGroup(long, long) * @see #deleteContactFromGroup(long, long) */ public ServiceStatus deleteContact(long localContactID) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.deleteContact() localContactID[" + localContactID + "]"); } if (SyncMeDbUtils.getMeProfileLocalContactId(this) != null && SyncMeDbUtils.getMeProfileLocalContactId(this).longValue() == localContactID) { LogUtils.logW("DatabaseHelper.deleteContact() Can not delete the Me profile contact"); return ServiceStatus.ERROR_NOT_FOUND; } ContactsTable.ContactIdInfo mContactIdInfo = ContactsTable.validateContactId( localContactID, getWritableDatabase()); List<ContactsTable.ContactIdInfo> idList = new ArrayList<ContactsTable.ContactIdInfo>(); idList.add(mContactIdInfo); ServiceStatus mStatus = syncDeleteContactList(idList, true, true); if (ServiceStatus.SUCCESS == mStatus) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); } return mStatus; } /*** * Adds a contact detail to the database and fires an internal database * change event. * * @param detail A {@link ContactDetail} object which contains the detail to * add * @return SUCCESS or a suitable error code * @see #modifyContactDetail(ContactDetail) * @see #deleteContactDetail(long) * @see #addContact(Contact) * @see #deleteContact(long) * @see #addContactToGroup(long, long) * @see #deleteContactFromGroup(long, long) * @throws NullPointerException When detail is NULL */ public ServiceStatus addContactDetail(ContactDetail detail) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.addContactDetail() name[" + detail.getName() + "]"); } if (detail == null) { throw new NullPointerException( "DatabaseHelper.addContactDetail() detail should not be NULL"); } boolean isMeProfile = (SyncMeDbUtils.getMeProfileLocalContactId(this) != null && detail.localContactID != null && detail.localContactID.equals(SyncMeDbUtils .getMeProfileLocalContactId(this))); List<ContactDetail> mDetailList = new ArrayList<ContactDetail>(); mDetailList.add(detail); ServiceStatus mStatus = syncAddContactDetailList(mDetailList, !isMeProfile, !isMeProfile); if (mStatus == ServiceStatus.SUCCESS) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); if (isMeProfile) { WidgetUtils.kickWidgetUpdateNow(mContext); } } return mStatus; } /*** * Modifies an existing contact detail in the database. Also fires an * internal database change event. * * @param detail A {@link ContactDetail} object which contains the detail to * add * @return SUCCESS or a suitable error code * @see #addContactDetail(ContactDetail) * @see #deleteContactDetail(long) * @see #addContact(Contact) * @see #deleteContact(long) * @see #addContactToGroup(long, long) * @see #deleteContactFromGroup(long, long) */ public ServiceStatus modifyContactDetail(ContactDetail detail) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.modifyContactDetail() name[" + detail.getName() + "]"); } boolean isMeProfile = false; // me profile has changed List<ContactDetail> mDetailList = new ArrayList<ContactDetail>(); mDetailList.add(detail); ServiceStatus mStatus = syncModifyContactDetailList(mDetailList, !isMeProfile, !isMeProfile); if (ServiceStatus.SUCCESS == mStatus) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); if (isMeProfile) { WidgetUtils.kickWidgetUpdateNow(mContext); } } return mStatus; } /*** * Deletes a contact detail from the database. Also fires an internal * database change event. * * @param localContactDetailID The local ID of the detail to delete * @return SUCCESS or a suitable error code * @see #addContactDetail(ContactDetail) * @see #modifyContactDetail(ContactDetail) * @see #addContact(Contact) * @see #deleteContact(long) * @see #addContactToGroup(long, long) * @see #deleteContactFromGroup(long, long) */ public ServiceStatus deleteContactDetail(long localContactDetailID) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.deleteContactDetail() localContactDetailID[" + localContactDetailID + "]"); } SQLiteDatabase mDb = getReadableDatabase(); ContactDetail mDetail = ContactDetailsTable.fetchDetail(localContactDetailID, mDb); if (mDetail == null) { LogUtils.logE("Database.deleteContactDetail() Unable to find detail for deletion"); return ServiceStatus.ERROR_NOT_FOUND; } boolean isMeProfile = false; if (mDetail.localContactID.equals(SyncMeDbUtils.getMeProfileLocalContactId(this))) { isMeProfile = true; } List<ContactDetail> mDetailList = new ArrayList<ContactDetail>(); mDetailList.add(mDetail); ServiceStatus mStatus = syncDeleteContactDetailList(mDetailList, true, !isMeProfile); if (ServiceStatus.SUCCESS == mStatus) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); if (isMeProfile) { WidgetUtils.kickWidgetUpdateNow(mContext); } } return mStatus; } /*** * Modifies the server Contact Id and User ID stored in the database for a * specific contact. * * @param localId The local Id of the contact to modify * @param serverId The new server Id * @param userId The new user Id * @return true if successful * @see #fetchContactByServerId(Long, Contact) * @see #fetchServerId(long) */ public boolean modifyContactServerId(long localId, Long serverId, Long userId) { trace(false, "DatabaseHelper.modifyContactServerId() localId[" + localId + "] " + "serverId[" + serverId + "] userId[" + userId + "]"); final SQLiteDatabase mDb = getWritableDatabase(); try { mDb.beginTransaction(); if (!ContactsTable.modifyContactServerId(localId, serverId, userId, mDb)) { return false; } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } return true; } /*** * Sets the Server Id for a contact detail and flags it as synchronized * with the server. * * @param localDetailId The local Id of the contact detail to modify * @param serverDetailId The new server Id * @return true if successful */ public boolean syncContactDetail(Long localDetailId, Long serverDetailId) { trace(false, "DatabaseHelper.modifyContactDetailServerId() localDetailId[" + localDetailId + "]" + " serverDetailId[" + serverDetailId + "]"); SQLiteDatabase mDb = getWritableDatabase(); try { mDb.beginTransaction(); if (!ContactDetailsTable.syncSetServerId(localDetailId, serverDetailId, mDb)) { return false; } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } return true; } /*** * Fetches the user's logon credentials from the database. * * @param details An empty LoginDetails object which will be filled on * return * @return SUCCESS or a suitable error code * @see #fetchLogonCredentialsAndPublicKey(LoginDetails, PublicKeyDetails) * @see #modifyCredentials(LoginDetails) * @see #modifyCredentialsAndPublicKey(LoginDetails, PublicKeyDetails) */ public ServiceStatus fetchLogonCredentials(LoginDetails details) { return StateTable.fetchLogonCredentials(details, getReadableDatabase()); } /*** * Fetches the user's logon credentials and public key information from the * database. * * @param details An empty LoginDetails object which will be filled on * return * @param pubKeyDetails An empty PublicKeyDetails object which will be * filled on return * @return SUCCESS or a suitable error code * @see #fetchLogonCredentials(LoginDetails) * @see #modifyCredentials(LoginDetails) * @see #modifyCredentialsAndPublicKey(LoginDetails, PublicKeyDetails) */ public ServiceStatus fetchLogonCredentialsAndPublicKey(LoginDetails details, PublicKeyDetails pubKeyDetails) { return StateTable.fetchLogonCredentialsAndPublicKey(details, pubKeyDetails, getReadableDatabase()); } /*** * Modifies the user's logon credentials. Note: Only called from tests. * * @param details The login details to store * @return SUCCESS or a suitable error code * @see #fetchLogonCredentials(LoginDetails) * @see #fetchLogonCredentialsAndPublicKey(LoginDetails, PublicKeyDetails) * @see #modifyCredentialsAndPublicKey(LoginDetails, PublicKeyDetails) */ public ServiceStatus modifyCredentials(LoginDetails details) { return StateTable.modifyCredentials(details, getWritableDatabase()); } /*** * Modifies the user's logon credentials and public key details. * * @param details The login details to store * @param pubKeyDetails The public key details to store * @return SUCCESS or a suitable error code * @see #fetchLogonCredentials(LoginDetails) * @see #fetchLogonCredentialsAndPublicKey(LoginDetails, PublicKeyDetails) * @see #modifyCredentials(LoginDetails) */ public ServiceStatus modifyCredentialsAndPublicKey(LoginDetails details, PublicKeyDetails pubKeyDetails) { return StateTable.modifyCredentialsAndPublicKey(details, pubKeyDetails, getWritableDatabase()); } /*** * Remove contact changes from the change log. This will be called once the * changes have been sent to the server. * * @param changeInfoList A list of changeInfoIDs (none of the other fields * in the {@link ContactChangeInfo} object are required). * @return true if successful */ public boolean deleteContactChanges(List<ContactChangeLogTable.ContactChangeInfo> changeInfoList) { return ContactChangeLogTable.deleteContactChanges(changeInfoList, getWritableDatabase()); } /*** * Fetches a setting from the database. * * @param option The option required. * @return A {@link PersistSettings} object which contains the setting data * if successful, null otherwise * @see #setOption(PersistSettings) */ public PersistSettings fetchOption(PersistSettings.Option option) { PersistSettings mSetting = StateTable.fetchOption(option, getWritableDatabase()); if (mSetting == null) { mSetting = new PersistSettings(); mSetting.putDefaultOptionData(); } return mSetting; } /*** * Modifies a setting in the database. * * @param setting A {@link PersistSetting} object which is populated with an * option set to a value. * @return SUCCESS or a suitable error code * @see #fetchOption(com.vodafone360.people.service.PersistSettings.Option) */ public ServiceStatus setOption(PersistSettings setting) { ServiceStatus mStatus = StateTable.setOption(setting, getWritableDatabase()); if (ServiceStatus.SUCCESS == mStatus) { fireSettingChangedEvent(setting); } return mStatus; } /*** * Removes all groups from the database. * * @return SUCCESS or a suitable error code */ public ServiceStatus deleteAllGroups() { SQLiteDatabase mDb = getWritableDatabase(); ServiceStatus mStatus = GroupsTable.deleteAllGroups(mDb); if (ServiceStatus.SUCCESS == mStatus) { mStatus = GroupsTable.populateSystemGroups(mContext, mDb); } return mStatus; } /*** * Fetches Avatar URLs from the database for all contacts which have an * Avatar and have not yet been loaded. * * @param thumbInfoList An empty list where the {@link ThumbnailInfo} * objects will be stored containing the URLs * @param firstIndex The 0-based index of the first item to fetch from the * database * @param count The maximum number of items to fetch * @return SUCCESS or a suitable error code * @see ThumbnailInfo * @see #fetchThumbnailUrlCount() */ public ServiceStatus fetchThumbnailUrls(List<ThumbnailInfo> thumbInfoList, int firstIndex, int count) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.fetchThumbnailUrls() firstIndex[" + firstIndex + "] " + "count[" + count + "]"); } Cursor mCursor = null; try { thumbInfoList.clear(); mCursor = getReadableDatabase().rawQuery( "SELECT " + ContactDetailsTable.TABLE_NAME + "." + ContactDetailsTable.Field.LOCALCONTACTID + "," + Field.STRINGVAL + " FROM " + ContactDetailsTable.TABLE_NAME + " INNER JOIN " + ContactSummaryTable.TABLE_NAME + " WHERE " + ContactDetailsTable.TABLE_NAME + "." + ContactDetailsTable.Field.LOCALCONTACTID + "=" + ContactSummaryTable.TABLE_NAME + "." + ContactSummaryTable.Field.LOCALCONTACTID + " AND " + ContactSummaryTable.Field.PICTURELOADED + " =0 " + " AND " + ContactDetailsTable.Field.KEY + "=" + ContactDetail.DetailKeys.PHOTO.ordinal() + " LIMIT " + firstIndex + "," + count, null); ArrayList<String> urls = new ArrayList<String>(); ThumbnailInfo mThumbnailInfo = null; while (mCursor.moveToNext()) { mThumbnailInfo = new ThumbnailInfo(); if (!mCursor.isNull(0)) { mThumbnailInfo.localContactId = mCursor.getLong(0); } mThumbnailInfo.photoServerUrl = mCursor.getString(1); if (!urls.contains(mThumbnailInfo.photoServerUrl)) { urls.add(mThumbnailInfo.photoServerUrl); thumbInfoList.add(mThumbnailInfo); } } // LogUtils.logWithName("THUMBNAILS:","urls:\n" + urls); return ServiceStatus.SUCCESS; } catch (SQLException e) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(mCursor); } } /*** * Fetches Avatar URLs from the database for all contacts from contactList * which have an Avatar and have not yet been loaded. * * @param thumbInfoList An empty list where the {@link ThumbnailInfo} * objects will be stored containing the URLs * @param contactList list of contacts to fetch the thumbnails for * @return SUCCESS or a suitable error code * @see ThumbnailInfo * @see #fetchThumbnailUrlCount() */ public ServiceStatus fetchThumbnailUrlsForContacts(List<ThumbnailInfo> thumbInfoList, final List<Long> contactList) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.fetchThumbnailUrls()"); } StringBuilder localContactIdList = new StringBuilder(); localContactIdList.append("("); Long localContactId = -1l; for (Long contactId : contactList) { if (localContactId != -1) { localContactIdList.append(","); } localContactId = contactId; localContactIdList.append(contactId); } localContactIdList.append(")"); Cursor cursor = null; try { thumbInfoList.clear(); cursor = getReadableDatabase().rawQuery( "SELECT " + ContactDetailsTable.TABLE_NAME + "." + ContactDetailsTable.Field.LOCALCONTACTID + "," + ContactDetailsTable.Field.STRINGVAL + " FROM " + ContactDetailsTable.TABLE_NAME + " INNER JOIN " + ContactSummaryTable.TABLE_NAME + " WHERE " + ContactDetailsTable.TABLE_NAME + "." + ContactDetailsTable.Field.LOCALCONTACTID + " in " + localContactIdList.toString() + " AND " + ContactSummaryTable.Field.PICTURELOADED + " =0 " + " AND " + ContactDetailsTable.Field.KEY + "=" + ContactDetail.DetailKeys.PHOTO.ordinal(), null); - ArrayList<String> urls = new ArrayList<String>(); + HashSet<String> urlSet = new HashSet<String>(); ThumbnailInfo mThumbnailInfo = null; while (cursor.moveToNext()) { mThumbnailInfo = new ThumbnailInfo(); - if (!cursor - .isNull(cursor - .getColumnIndexOrThrow(ContactDetailsTable.Field.LOCALCONTACTID - .toString()))) { - mThumbnailInfo.localContactId = cursor.getLong(cursor - .getColumnIndexOrThrow(ContactDetailsTable.Field.LOCALCONTACTID - .toString())); + if (!cursor.isNull(cursor.getColumnIndexOrThrow( + ContactDetailsTable.Field.LOCALCONTACTID.toString()))) { + mThumbnailInfo.localContactId = cursor.getLong(cursor.getColumnIndexOrThrow( + ContactDetailsTable.Field.LOCALCONTACTID.toString())); } - mThumbnailInfo.photoServerUrl = cursor.getString(cursor - .getColumnIndexOrThrow(ContactDetailsTable.Field.STRINGVAL.toString())); + mThumbnailInfo.photoServerUrl = cursor.getString(cursor.getColumnIndexOrThrow( + ContactDetailsTable.Field.STRINGVAL.toString())); + // TODO: Investigate if this is really needed - if (!urls.contains(mThumbnailInfo.photoServerUrl)) { - urls.add(mThumbnailInfo.photoServerUrl); + if (urlSet.add(mThumbnailInfo.photoServerUrl)) { thumbInfoList.add(mThumbnailInfo); } } return ServiceStatus.SUCCESS; } catch (SQLException e) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } } /** * Fetches the list of all the contactIds for which the Thumbnail still needs to * be downloaded. Firstly, the list of all the contactIds whose picture_loaded * flag is set to false is retrieved from the ContactSummaryTable. Then these contactids * are further filtered based on whether they have a photo URL assigned to them * in the ContactDetails table. * @param contactIdList An empty list where the retrieved contact IDs are stored. * @return SUCCESS or a suitable error code */ public ServiceStatus fetchContactIdsWithThumbnails(List<Long> contactIdList) { SQLiteDatabase db = getReadableDatabase(); Cursor cr = null; try { String sql = "SELECT " + ContactSummaryTable.Field.LOCALCONTACTID + " FROM " + ContactSummaryTable.TABLE_NAME + " WHERE " + ContactSummaryTable.Field.PICTURELOADED + " =0 AND " + ContactSummaryTable.Field.LOCALCONTACTID + " IN (SELECT " + ContactDetailsTable.Field.LOCALCONTACTID + " FROM " + ContactDetailsTable.TABLE_NAME + " WHERE " + ContactDetailsTable.Field.KEY + "=" + ContactDetail.DetailKeys.PHOTO.ordinal() + ")"; cr = db.rawQuery(sql, null); Long localContactId = -1L; while (cr.moveToNext()) { if (!cr .isNull(cr .getColumnIndexOrThrow(ContactDetailsTable.Field.LOCALCONTACTID .toString()))) { localContactId = cr.getLong(cr .getColumnIndexOrThrow(ContactDetailsTable.Field.LOCALCONTACTID .toString())); contactIdList.add(localContactId); } } return ServiceStatus.SUCCESS; } catch (SQLException e) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cr); } } /*** * Fetches the number of Contact Avatars which have not yet been loaded. * * @return The number of Avatars * @see ThumbnailInfo * @see #fetchThumbnailUrls(List, int, int) */ public int fetchThumbnailUrlCount() { trace(false, "DatabaseHelper.fetchThumbnailUrlCount()"); Cursor mCursor = null; try { mCursor = getReadableDatabase().rawQuery( "SELECT COUNT(" + ContactSummaryTable.Field.SUMMARYID + ") FROM " + ContactSummaryTable.TABLE_NAME + " WHERE " + ContactSummaryTable.Field.PICTURELOADED + " =0 ", null); if (mCursor.moveToFirst()) { if (!mCursor.isNull(0)) { return mCursor.getInt(0); } } return 0; } catch (SQLException e) { return 0; } finally { CloseUtils.close(mCursor); } } /*** * Modifies the Me Profile Avatar Changed Flag. When this flag is set to * true, it indicates that the avatar needs to be synchronised with the * server. * * @param avatarChanged true to set the flag, false to clear the flag * @return SUCCESS or a suitable error code */ public ServiceStatus modifyMeProfileAvatarChangedFlag(boolean avatarChanged) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.modifyMeProfileAvatarChangedFlag() avatarChanged[" + avatarChanged + "]"); } if (avatarChanged == mMeProfileAvatarChangedFlag) { return ServiceStatus.SUCCESS; } ServiceStatus mResult = StateTable.modifyMeProfileChangedFlag(avatarChanged, getWritableDatabase()); if (ServiceStatus.SUCCESS == mResult) { mMeProfileAvatarChangedFlag = avatarChanged; } return mResult; } /*** * Fetches a cursor which can be used to iterate through the main contact * list. * <p> * The ContactSummaryTable.getQueryData static method can be used on the * cursor returned by this method to create a ContactSummary object. * * @param groupFilterId The local ID of a group to filter, or null if no * filter is required * @param constraint A search string to filter the contact name, or null if * no filter is required * @return The cursor result */ public synchronized Cursor openContactSummaryCursor(Long groupFilterId, CharSequence constraint) { return ContactSummaryTable.openContactSummaryCursor(groupFilterId, constraint, SyncMeDbUtils.getMeProfileLocalContactId(this), getReadableDatabase()); } public synchronized Cursor openContactsCursor() { return ContactsTable.openContactsCursor(getReadableDatabase()); } /*** * Fetches a contact from the database by its localContactId. The method * {@link #fetchBaseContact(long, Contact)} should be used if the contact * details properties are not required. * * @param localContactId Local ID of the contact to fetch. * @param contact Empty {@link Contact} object which will be populated with * data. * @return SUCCESS or a suitable ServiceStatus error code. */ public synchronized ServiceStatus fetchContact(long localContactId, Contact contact) { SQLiteDatabase db = getReadableDatabase(); ServiceStatus status = fetchBaseContact(localContactId, contact, db); if (ServiceStatus.SUCCESS != status) { return status; } status = ContactDetailsTable.fetchContactDetails(localContactId, contact.details, db); if (ServiceStatus.SUCCESS != status) { return status; } return ServiceStatus.SUCCESS; } /*** * Fetches a contact detail from the database. * * @param localDetailId The local ID of the detail to fetch * @param detail A empty {@link ContactDetail} object which will be filled * with the data * @return SUCCESS or a suitable error code */ public synchronized ServiceStatus fetchContactDetail(long localDetailId, ContactDetail detail) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.fetchContactDetail() localDetailId[" + localDetailId + "]"); } Cursor mCursor = null; try { try { String[] args = { String.format("%d", localDetailId) }; mCursor = getReadableDatabase() .rawQuery( ContactDetailsTable .getQueryStringSql(ContactDetailsTable.Field.DETAILLOCALID + " = ?"), args); } catch (SQLiteException e) { LogUtils.logE("DatabaseHelper.fetchContactDetail() Unable to fetch contact detail", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } if (!mCursor.moveToFirst()) { return ServiceStatus.ERROR_NOT_FOUND; } detail.copy(ContactDetailsTable.getQueryData(mCursor)); return ServiceStatus.SUCCESS; } finally { CloseUtils.close(mCursor); } } /*** * Searches the database for a contact with a given phone number. * * @param phoneNumber The telephone number to find * @param contact An empty Contact object which will be filled if a contact * is found * @param phoneDetail An empty {@link ContactDetail} object which will be * filled with the matching phone number detail * @return SUCCESS or a suitable error code */ public synchronized ServiceStatus fetchContactInfo(String phoneNumber, Contact contact, ContactDetail phoneDetail) { ServiceStatus mStatus = ContactDetailsTable.fetchContactInfo(phoneNumber, phoneDetail, null, getReadableDatabase()); if (ServiceStatus.SUCCESS != mStatus) { return mStatus; } return fetchContact(phoneDetail.localContactID, contact); } /*** * Puts a contact into a group. * * @param localContactId The local Id of the contact * @param groupId The local group Id * @return SUCCESS or a suitable error code * @see #deleteContactFromGroup(long, long) */ public ServiceStatus addContactToGroup(long localContactId, long groupId) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.addContactToGroup() localContactId[" + localContactId + "] " + "groupId[" + groupId + "]"); } SQLiteDatabase mDb = getWritableDatabase(); List<Long> groupIds = new ArrayList<Long>(); ContactGroupsTable.fetchContactGroups(localContactId, groupIds, mDb); if (groupIds.contains(groupId)) { // group is already in db than it's ok return ServiceStatus.SUCCESS; } boolean syncToServer = true; boolean mIsMeProfile = false; if (SyncMeDbUtils.getMeProfileLocalContactId(this) != null && SyncMeDbUtils.getMeProfileLocalContactId(this).longValue() == localContactId) { mIsMeProfile = true; syncToServer = false; } Contact mContact = new Contact(); ServiceStatus mStatus = fetchContact(localContactId, mContact); if (ServiceStatus.SUCCESS != mStatus) { return mStatus; } try { mDb.beginTransaction(); if (!ContactGroupsTable.addContactToGroup(localContactId, groupId, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } if (syncToServer) { if (!ContactChangeLogTable.addGroupRel(localContactId, mContact.contactID, groupId, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } if (syncToServer && !mIsMeProfile) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); } return ServiceStatus.SUCCESS; } /*** * Removes a group from a contact. * * @param localContactId The local Id of the contact * @param groupId The local group Id * @return SUCCESS or a suitable error code * @see #addContactToGroup(long, long) */ public ServiceStatus deleteContactFromGroup(long localContactId, long groupId) { if (Settings.ENABLED_DATABASE_TRACE) trace(false, "DatabaseHelper.deleteContactFromGroup() localContactId[" + localContactId + "] groupId[" + groupId + "]"); boolean syncToServer = true; boolean meProfile = false; if (SyncMeDbUtils.getMeProfileLocalContactId(this) != null && SyncMeDbUtils.getMeProfileLocalContactId(this).longValue() == localContactId) { meProfile = true; syncToServer = false; } Contact mContact = new Contact(); ServiceStatus mStatus = fetchContact(localContactId, mContact); if (ServiceStatus.SUCCESS != mStatus) { return mStatus; } if (mContact.contactID == null) { return ServiceStatus.ERROR_NOT_READY; } SQLiteDatabase mDb = getWritableDatabase(); try { mDb.beginTransaction(); boolean mResult = ContactGroupsTable.deleteContactFromGroup(localContactId, groupId, mDb); if (mResult && syncToServer) { if (!ContactChangeLogTable.deleteGroupRel(localContactId, mContact.contactID, groupId, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } if (syncToServer && !meProfile) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); } return ServiceStatus.SUCCESS; } /*** * Removes all the status or timeline activities from the database. Note: * Only called from tests. * * @param flag The type of activity to delete or null to delete all * @return SUCCESS or a suitable error code * @see #addActivities(List) * @see #fetchActivitiesIds(List, Long) */ public ServiceStatus deleteActivities(Integer flag) { if (Settings.ENABLED_DATABASE_TRACE) trace(false, "DatabaseHelper.deleteActivities() flag[" + flag + "]"); ServiceStatus mStatus = ActivitiesTable.deleteActivities(flag, getWritableDatabase()); if (ServiceStatus.SUCCESS == mStatus) { if (flag == null || flag.intValue() == ActivityItem.TIMELINE_ITEM) { StateTable.modifyLatestPhoneCallTime(System.currentTimeMillis(), getWritableDatabase()); } } fireDatabaseChangedEvent(DatabaseChangeType.ACTIVITIES, true); return mStatus; } /*** * Removes the selected timeline activity from the database. * * @param mApplication The MainApplication * @param timelineItem TimelineSummaryItem to be deleted * @return SUCCESS or a suitable error code */ public ServiceStatus deleteTimelineActivity(MainApplication mApplication, TimelineSummaryItem timelineItem, boolean isTimelineAll) { if (Settings.ENABLED_DATABASE_TRACE) trace(false, "DatabaseHelper.deleteTimelineActivity()"); ServiceStatus mStatus = ServiceStatus.SUCCESS; if (isTimelineAll) { mStatus = ActivitiesTable.deleteTimelineActivities(mContext, timelineItem, getWritableDatabase(), getReadableDatabase()); } else { mStatus = ActivitiesTable.deleteTimelineActivity(mContext, timelineItem, getWritableDatabase(), getReadableDatabase()); } if (mStatus == ServiceStatus.SUCCESS) { // Update Notifications in the Notification Bar IPeopleService peopleService = mApplication.getServiceInterface(); long localContactId = 0L; if (timelineItem.mLocalContactId != null) { localContactId = timelineItem.mLocalContactId; } peopleService.updateChatNotification(localContactId); } fireDatabaseChangedEvent(DatabaseChangeType.ACTIVITIES, true); return mStatus; } /** * Add a list of new activities to the Activities table. * * @param activityList contains the list of activity item * @return SUCCESS or a suitable error code * @see #deleteActivities(Integer) */ public ServiceStatus addActivities(List<ActivityItem> activityList) { SQLiteDatabase writableDb = getWritableDatabase(); ServiceStatus mStatus = ActivitiesTable.addActivities(activityList, writableDb, mContext); ActivitiesTable.cleanupActivityTable(writableDb); fireDatabaseChangedEvent(DatabaseChangeType.ACTIVITIES, true); return mStatus; } /*** * Fetches a list of activity IDs from a given time. * * @param activityIdList an empty list to be populated * @param timeStamp The oldest time that should be included in the list * @return SUCCESS or a suitable error code */ public synchronized ServiceStatus fetchActivitiesIds(List<Long> activityIdList, Long timeStamp) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.fetchActivitiesIds() timeStamp[" + timeStamp + "]"); } activityIdList.clear(); ActivitiesTable.fetchActivitiesIds(activityIdList, timeStamp, getReadableDatabase()); return ServiceStatus.SUCCESS; } /*** * Fetches fires a database change event to the listeners. * * @param type The type of database change (contacts, activity, etc) * @param isExternal true if this change came from the server, false if the * change is from the client * @see #addEventCallback(Handler) * @see #removeEventCallback(Handler) * @see #fireSettingChangedEvent(PersistSettings) */ public void fireDatabaseChangedEvent(DatabaseHelper.DatabaseChangeType type, boolean isExternal) { DbEventType event = new DbEventType(); event.ordinal = type.ordinal(); event.isExternal = isExternal; synchronized (mDbEvents) { if (mDbEvents.size() == 0) { // Creating a DbEventTimerTask every time because of preemptive-ness DbEventTimerTask dbEventTask = new DbEventTimerTask(); mDbEventTimer.schedule(dbEventTask, DATABASE_EVENT_DELAY); } if (!mDbEvents.contains(event)) { mDbEvents.add(event); } } } /*** * Add a database change listener. The listener will be notified each time * the database is changed. * * @param uiHandler The handler which will be notified * @see #fireDatabaseChangedEvent(DatabaseChangeType, boolean) * @see #fireSettingChangedEvent(PersistSettings) */ public synchronized void addEventCallback(Handler uiHandler) { if (!mUiEventCallbackList.contains(uiHandler)) { mUiEventCallbackList.add(uiHandler); } } /*** * Removes a database change listener. This must be called before UI * activities are destroyed. * * @param uiHandler The handler which will be notified * @see #addEventCallback(Handler) */ public synchronized void removeEventCallback(Handler uiHandler) { if (mUiEventCallbackList != null) { mUiEventCallbackList.remove(uiHandler); } } /*** * Internal function to fire a setting changed event to listeners. * * @param setting The setting that has changed with the new data * @see #addEventCallback(Handler) * @see #removeEventCallback(Handler) * @see #fireDatabaseChangedEvent(DatabaseChangeType, boolean) */ private synchronized void fireSettingChangedEvent(PersistSettings setting) { fireEventToUi(ServiceUiRequest.SETTING_CHANGED_EVENT, 0, 0, setting); } /*** * Internal function to send an event to all the listeners. * * @param event The type of event * @param arg1 This value depends on the type of event * @param arg2 This value depends on the type of event * @param data This value depends on the type of event * @see #fireDatabaseChangedEvent(DatabaseChangeType, boolean) * @see #fireSettingChangedEvent(PersistSettings) */ private void fireEventToUi(ServiceUiRequest event, int arg1, int arg2, Object data) { for (Handler mHandler : mUiEventCallbackList) { Message mMessage = mHandler.obtainMessage(event.ordinal(), data); mMessage.arg1 = arg1; mMessage.arg2 = arg2; mHandler.sendMessage(mMessage); } } /*** * Function used by the contact sync engine to add a list of contacts to the * database. * * @param contactList The list of contacts received from the server * @param syncToServer true if the contacts need to be sent to the server * @param syncToNative true if the contacts need to be added to the native * phonebook * @return SUCCESS or a suitable error code * @see #addContact(Contact) */ public ServiceStatus syncAddContactList(List<Contact> contactList, boolean syncToServer, boolean syncToNative) { if (Settings.ENABLED_DATABASE_TRACE) trace(false, "DatabaseHelper.syncAddContactList() syncToServer[" + syncToServer + "] syncToNative[" + syncToNative + "]"); if (!Settings.ENABLE_SERVER_CONTACT_SYNC) { diff --git a/src/com/vodafone360/people/datatypes/ContactDetail.java b/src/com/vodafone360/people/datatypes/ContactDetail.java index 05fd154..cdada85 100644 --- a/src/com/vodafone360/people/datatypes/ContactDetail.java +++ b/src/com/vodafone360/people/datatypes/ContactDetail.java @@ -1,951 +1,959 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.datatypes; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Bitmap.CompressFormat; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; import android.text.format.Time; import com.vodafone360.people.utils.LogUtils; /** * BaseDataType representing ContactDetails retrieved from, or issued to, * server. * <p> * Contains a specific contact detail such as name, address, phone number, etc. */ public class ContactDetail extends BaseDataType implements Parcelable { private static final String LOCATION_PROVIDER = "Now+ Sevice"; private static final String LOCATION_DELIMITER = ":"; public static final String UNKNOWN_NAME = "Unknown"; private static final String TYPE_PREFERRED = "preferred"; public static final int ORDER_PREFERRED = 0; public static final int ORDER_NORMAL = 50; /** * Definitions of KEY types for Contact-Details. */ public enum DetailKeyTypes { HOME("home"), WORK("work"), MOBILE("mobile"), // Type not recognised by NOW+ server - use CELL // instead BIRTHDAY("birthday"), CELL("cell"), FAX("fax"), UNKNOWN("unknown"); private final String typeName; /** * Constructor for detailKeyTypes item. * * @param n String value associated with detailKeyTypes item. */ private DetailKeyTypes(String n) { typeName = n; } /** * String value associated with detailKeyTypes item. * * @return String value for detailKeyTypes item. */ public String tag() { return typeName; } /** * Find detailKeyTypes item for specified String * * @param tag String value to find detailKeyTypes item for * @return detailKeyTypes item for specified String, null otherwise */ - protected static DetailKeyTypes findKey(String k) { + public static DetailKeyTypes findKey(String k) { for (DetailKeyTypes type : DetailKeyTypes.values()) { if (k.compareTo(type.tag()) == 0) { return type; } } return null; } } /** * Contact Detail KEY definitions */ public enum DetailKeys { VCARD_NAME("vcard.name"), // 0 VCARD_NICKNAME("vcard.nickname"), // 1 VCARD_DATE("vcard.date"), // 2 VCARD_EMAIL("vcard.email"), // 3 VCARD_PHONE("vcard.phone"), // 4 VCARD_ADDRESS("vcard.address"), // 5 VCARD_URL("vcard.url"), // 6 VCARD_INTERNET_ADDRESS("vcard.internetaddress"), // 7 VCARD_IMADDRESS("vcard.imaddress"), // 8 VCARD_ROLE("vcard.role"), // 9haven't found short name for it VCARD_ORG("vcard.org"), // 10haven't found short name for it VCARD_TITLE("vcard.title"), // 11haven't found short name for it VCARD_NOTE("vcard.note"), // 12 VCARD_BUSINESS("vcard.business"), // 13only in API doc PRESENCE_TEXT("presence.text"), // 14 PHOTO("photo"), // 15 LOCATION("location"), // 16 GENDER("gender"), // 17only in API doc RELATION("relation"), // 18only in API doc BOOKMARK("bookmark"), // 19only in API doc INTEREST("interest"), // 20only in API doc FOLDER("folder"), // 21only in API doc GROUP("group"), // 22only in API doc LINK("link"), // 23only in API doc EXTERNAL("external"), // 24only in API doc UNKNOWN("unknown"); // 25only in API doc private final String keyName; /** * Constructor for detailKeys item. * * @param n String value for DetailKeys item. */ private DetailKeys(String n) { keyName = n; } /** * Return String value associated with detailKeys item. * * @return String value associated with detailKeys item. */ private String tag() { return keyName; } } /** * Tags associated with ContactDetail item. */ private enum Tags { KEY("key"), VALUE("val"), DELETED("deleted"), ALT("alt"), UNIQUE_ID("detailid"), // previously rid ORDER("order"), UPDATED("updated"), TYPE("type"), BYTES("bytes"), // docs are inconsistent about those BYTES_MIME_TYPE("bytesmime"), // might be those 3 last tags BYTES_URL("bytesurl"), // are not possible in contact details // but they are inside Content structure. METADATA("metadata"); // Added to add some more extra information // about the contact details. private final String tag; /** * Construct Tags item from supplied String * * @param s String value for Tags item. */ private Tags(String s) { tag = s; } /** * Return String value associated with Tags item. * * @return String value associated with Tags item. */ private String tag() { return tag; } + /** + * Find Tags item for specified String + * + * @param tag String value to find Tags item for + * @return Tags item for specified String, null otherwise + */ + public static Tags findTag(String tag) { + for (Tags tags : Tags.values()) { + if (tag.compareTo(tags.tag()) == 0) { + return tags; + } + } + return null; + } } /** * Primary key in the ContactDetails table */ public Long localDetailID = null; // Primary key in database /** * Secondary key which links the contact detail with a contact */ public Long localContactID = null; /** * Determines which kind of contact detail this object refers to (name, * address, phone number, etc) */ public DetailKeys key = DetailKeys.UNKNOWN; /** * Type of detail (home, business, work, etc.) */ public DetailKeyTypes keyType = null; /** * Current value of the detail */ public String value = null; /** * True if the contact detail has been deleted on the server */ public Boolean deleted = null; /** * Contains the last time the contact detail was updated on the server */ public Long updated = 0L; /** * Contains the server ID if the contact detail has been synchronised with * the server, null otherwise. */ public Long unique_id = null; /** * Contains the order in which the contact detail should be displayed. The * lower the value, the higher in the list the contact detail should be. */ public Integer order = 0; /** * An alternative value to display for the contact detail */ public String alt = null; /** * The location associated with the contact detail obtained from the server */ public Location location = null; /** * A photo associated with the detail. It is preferred that large objects * such as photos are stored in the file system rather than the database. * Hence this may never be used. */ public Bitmap photo = null; /** * The mime type of the image pointed to in the {@link #photo_url} field. * * @see photo_url */ public String photo_mime_type = ""; /** * Contains the remote URL on the server where the image is located. * * @see #photo_mime_type */ public String photo_url = ""; /** * Internal field which is used to cache the contact server ID. This is not * stored in the database table. */ public Long serverContactId; /** * Internal field which is used to cache the sync native contact ID. This is * not stored in the database table. */ public Integer syncNativeContactId; /** * Internal field which is a secondary key linking the detail with a contact * in the native address book. Is null if this detail is not linked with the * native address book. */ public Integer nativeContactId = null; /** * Internal field which is a secondary key linking the detail with a contact * detail in the native address book. Is null if this detail is not linked * with the native address book. */ public Integer nativeDetailId = null; /** * Internal field which is a secondary key to link the detail with a change * in the change log table. The field is a temporary field used only during * contact sync and is not stored or parcelled. */ public Long changeID = null; /** * A string copied from the native address book which can be used to * determine if this contact has changed. * * @see #nativeVal2 * @see #nativeVal3 */ public String nativeVal1 = null; /** * A string copied from the native address book which can be used to * determine if this contact has changed. * * @see #nativeVal1 * @see #nativeVal3 */ public String nativeVal2 = null; /** * A string copied from the native address book which can be used to * determine if this contact has changed. * * @see #nativeVal1 * @see #nativeVal2 */ public String nativeVal3 = null; /** * Integer Field to store additional information. */ public Integer metadata = -1; - /** - * Find Tags item for specified String - * - * @param tag String value to find Tags item for - * @return Tags item for specified String, null otherwise - */ - private Tags findTag(String tag) { - for (Tags tags : Tags.values()) { - if (tag.compareTo(tags.tag()) == 0) { - return tags; - } - } - return null; - } - - /** {@inheritDoc} */ + + /** {@inheritDoc} */ @Override public int getType() { return CONTACT_DETAIL_DATA_TYPE; } /** * Create Hashtable containing ContactDetail parameters * * @return Hashtable containing Contact detail parameters */ public Hashtable<String, Object> createHashtable() { Hashtable<String, Object> htab = new Hashtable<String, Object>(); if (key != null) { htab.put("key", key.tag()); } if (unique_id != null) { htab.put("detailid", unique_id); } if ((deleted != null) && (deleted.booleanValue())) { // if the detail is marked as deleted we return a detail with detail // id and key and // it will be deleted return htab; } if (keyType != null && keyType != DetailKeyTypes.UNKNOWN) { htab.put("type", keyType.tag()); } if (value != null) { htab.put("val", value); } if (updated != null && updated != 0) { htab.put("updated", updated); } if (order != null) { htab.put("order", order); } if (location != null) { htab.put("location", location.getLatitude() + LOCATION_DELIMITER + location.getLongitude()); } if (photo_url != null && photo_url.length() > 0) { htab.put("photo_url", photo_url); } if (photo != null) { ByteArrayOutputStream os = new ByteArrayOutputStream(); photo.compress(CompressFormat.PNG, 100, os); byte[] bytes = os.toByteArray(); htab.put(Tags.BYTES.tag(), bytes); } if (photo_mime_type != null && photo_mime_type.length() > 0) { htab.put(Tags.BYTES_MIME_TYPE.tag(), photo_mime_type); } return htab; } /** * Create ContactDetail from Hashtable generated by Hessian-decoder * * @param hash Hashtable containing ContactDetail parameters * @return ContactDetail created from Hashtable */ protected ContactDetail createFromHashtable(Hashtable<String, Object> hash) { Enumeration<String> e = hash.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); Object value = hash.get(key); - Tags tag = findTag(key); + Tags tag = Tags.findTag(key); setValue(tag, value); } - + + // FIX for PAND-2379 + // TODO: remove, when BE does not send invalid photo urls + if (key == DetailKeys.PHOTO) { + value = value.replaceAll("\r", ""); + value = value.replaceAll("\n", ""); + value = value.replaceAll(" ", ""); + } + return this; } /** * Sets the value of the member data item associated with the specified tag. * * @param tag Current tag * @param val Value associated with the tag */ private void setValue(Tags tag, Object obValue) { if (tag == null) { LogUtils.logE("ContactDetail setValue tag is null"); return; } switch (tag) { case KEY: for (DetailKeys keys : DetailKeys.values()) { if (((String)obValue).compareTo(keys.tag()) == 0) { key = keys; break; } } break; case DELETED: deleted = (Boolean)obValue; break; case ALT: if (alt == null) { final String valStr = (String)obValue; final int delim = valStr.indexOf(LOCATION_DELIMITER); if (delim > 0 && valStr.length() > delim + 1) { try { // extract the latitude and longitude final String extractedLatitude = valStr.substring(0, delim - 1); final String extractedLongitude = valStr.substring(delim + 1); final Double latitude = Double.valueOf(extractedLatitude); final Double longitude = Double.valueOf(extractedLongitude); // create a Location object that will contain the latitude and longitude location = new Location(LOCATION_PROVIDER); location.setLatitude(Double.valueOf(latitude)); location.setLongitude(Double.valueOf(longitude)); if (updated != null) { location.setTime(updated); } } catch(Exception e) { LogUtils.logE("ContactDetail.setValue(), Location string can't be parsed: " + valStr + ", error: "+e); alt = valStr; } } else { LogUtils.logE("Location string has wrong format: " + valStr); alt = valStr; } } break; case BYTES: byte[] data = (byte[])obValue; if (data != null) { photo = BitmapFactory.decodeByteArray(data, 0, data.length); } else { LogUtils.logE("ContactDetail.setValue(), data shall be provided with the BYTES tag!"); } break; case BYTES_MIME_TYPE: photo_mime_type = (String)obValue; break; case BYTES_URL: photo_url = (String)obValue; break; case ORDER: order = (Integer)obValue; break; case TYPE: processTypeData((String)obValue); break; case UNIQUE_ID: unique_id = (Long)obValue; break; case UPDATED: updated = (Long)obValue; if ((location != null) && (updated != null)) { location.setTime(updated); } break; case VALUE: value = (String)obValue; default: } } /** {@inheritDoc} */ @Override public String toString() { Date time = null; if (updated != null) { time = new Date(updated * 1000); } else { time = new Date(0); } final StringBuilder sb = new StringBuilder("\tContact detail:\n\t\tLocal Detail ID: "); sb.append(localDetailID); sb.append("\n\t\tLocal Contact ID: "); sb.append(localContactID); sb.append("\n\t\tKey: "); sb.append(key); sb.append("\n\t\tKey type: "); sb.append(keyType); sb.append("\n\t\tValue: "); sb.append(value); sb.append("\n\t\tDeleted: "); sb.append(deleted); sb.append("\n\t\tOrder: "); sb.append(order); sb.append("\n\t\tLocation: "); sb.append(location); sb.append("\n\t\tAlt: "); sb.append(alt); sb.append("\n\t\tContact ID: "); sb.append(serverContactId); sb.append("\n\t\tNative Contact ID: "); sb.append(nativeContactId); sb.append("\n\t\tNative Detail ID: "); sb.append(nativeDetailId); sb.append("\n\t\tNative Val 1: "); sb.append(nativeVal1); sb.append("\n\t\tNative Val 2: "); sb.append(nativeVal2); sb.append("\n\t\tNative Val 3: "); sb.append(nativeVal3); sb.append("\n\t\tPhoto Mime Type: "); sb.append(photo_mime_type); sb.append("\n\t\tPhoto URL: "); sb.append(photo_url); sb.append("\n\t\tUpdated: "); sb.append(updated); sb.append(" Date: "); sb.append(time.toGMTString()); sb.append("\n\t\tUnique ID: "); sb.append(unique_id); sb.append("\n\t\tserverContactId: "); sb.append(serverContactId); sb.append("\n\t\tsyncNativeContactId: "); sb.append(syncNativeContactId); if (location != null) { sb.append("\n\t\tLocation: "); sb.append(location.toString()); } if (photo != null) { sb.append("\n\t\tPhoto BYTE[] is present"); } sb.append("\n\t\tPhoto MIME type: "); sb.append(photo_mime_type); sb.append("\n\t\tPhoto URL: "); sb.append(photo_url); sb.append("\n"); return sb.toString(); } /** * Copy ContactDetail parameters from supplied ContactDetail item. * * @param source ContactDetail to copy from. */ public void copy(ContactDetail source) { android.os.Parcel _data = android.os.Parcel.obtain(); source.writeToParcel(_data, 0); _data.setDataPosition(0); readFromParcel(_data); } /** * Default constructor for ContactDetail. */ public ContactDetail() { } /** * Construct ContactDetail from supplied Parcel. * * @param in Parcel containing ContactDetails. */ private ContactDetail(Parcel in) { readFromParcel(in); } /** * @param rawVal * @param inKey * @param inType */ public void setValue(String rawVal, DetailKeys inKey, DetailKeyTypes inType) { key = inKey; keyType = inType; value = VCardHelper.makeSingleTextValue(rawVal); } /** * Fetches single value from a VCard entry using VCardHelper class. * * @return value as String. */ public String getValue() { return VCardHelper.getSingleTextValue(value); } /** * Set VCard name field using VCardHelper. * * @param name VCardHelper name item. */ public void setName(VCardHelper.Name name) { key = DetailKeys.VCARD_NAME; keyType = null; value = VCardHelper.makeName(name); } /** * Return VCard name field * * @return VCardHelper.Name containing name. */ public VCardHelper.Name getName() { if (value != null && !value.equals(UNKNOWN_NAME)) { return VCardHelper.getName(value); } return null; } /** * Set VCard organisation field. * * @param org VCardHelper.Organisation containing representation of * organisation fields. * @param type detailKeyTypes (i.e. HOME/WORK). */ public void setOrg(VCardHelper.Organisation org, DetailKeyTypes type) { key = DetailKeys.VCARD_ORG; keyType = type; value = VCardHelper.makeOrg(org); } /** * Return organisation field value. * * @return VCardHelper.Organisation containing organisation. */ public VCardHelper.Organisation getOrg() { return VCardHelper.getOrg(value); } /** * Set VCard date field. * * @param time Time to set. * @param inType detailKeyTypes for item (i.e BIRTHDAY). */ public void setDate(Time time, DetailKeyTypes inType) { key = DetailKeys.VCARD_DATE; keyType = inType; value = VCardHelper.makeDate(time); } /** * Get date value. * * @return Time containing date value. */ public Time getDate() { return VCardHelper.getDate(value); } /** * Set email address * * @param emailAddress String containing email address * @param inType detailKeyTypes vale specifying address type. */ public void setEmail(String emailAddress, DetailKeyTypes inType) { key = DetailKeys.VCARD_EMAIL; keyType = inType; value = VCardHelper.makeEmail(emailAddress); } /* * Get email address value with assistance of VCardHelper. * @return String containing email address. */ public String getEmail() { return VCardHelper.getEmail(value); } /** * Set postal address. * * @param address VCardHelper.PostalAddress containing postal address * fields. * @param inType detailKeyTypes specifying address type. */ public void setPostalAddress(VCardHelper.PostalAddress address, DetailKeyTypes inType) { key = DetailKeys.VCARD_ADDRESS; keyType = inType; value = VCardHelper.makePostalAddress(address); } /** * Get postal address * * @return postal address placed in VCardHelper.PostalAddress. */ public VCardHelper.PostalAddress getPostalAddress() { return VCardHelper.getPostalAddress(value); } /** * Set telephone number. * * @param tel String containing telephone number. * @param inType detailKeyTypes identifying number type. */ public void setTel(String tel, DetailKeyTypes inType) { key = DetailKeys.VCARD_PHONE; keyType = inType; value = VCardHelper.makeTel(tel); } /** * Return telephone number as String * * @return String containing telephone number. */ public String getTel() { return VCardHelper.getTel(value); } /** * Attempt to set type based on supplied data. If type can not be determined * the suppled data is used to populate 'alt;' field. * * @param typeData String containing type information. */ private void processTypeData(String typeData) { final int posIdx = typeData.indexOf(';'); if (posIdx >= 0) { List<String> list = new ArrayList<String>(); VCardHelper.getStringList(list, typeData); for (String type : list) { if (processType(type)) { break; } } } else { processType(typeData); } if (keyType == null && ((String)typeData).trim().length() > 0) { alt = ((String)typeData); } } /** * Set key-type based on supplied key String. * * @param typeString String containing type. * @return true if the type is supported, false otherwise. */ private boolean processType(String typeString) { if (typeString.equals(TYPE_PREFERRED)) { return false; } for (DetailKeyTypes type : DetailKeyTypes.values()) { if (typeString.equals(type.tag())) { keyType = type; return true; } } return false; } /** * Enumeration consisting of fields written to/from Parcel containing * ContactDetail item. */ private enum MemberData { LOCAL_DETAIL_ID, LOCAL_CONTACT_ID, KEY, KEY_TYPE, VALUE, DELETED, UPDATED, UNIQUE_ID, ORDER, LOCATION, ALT, PHOTO, PHOTO_MIME_TYPE, PHOTO_URL, SERVER_CONTACT_ID, NATIVE_CONTACT_ID, NATIVE_DETAIL_ID, NATIVE_VAL1, NATIVE_VAL2, NATIVE_VAL3; } /** * Read ContactDetail item from supplied Parcel. * * @param in PArcel containing ContactDetail. */ private void readFromParcel(Parcel in) { localDetailID = null; // Primary key in database localContactID = null; key = null; keyType = null; value = null; updated = null; unique_id = null; order = null; location = null; photo = null; photo_mime_type = null; photo_url = null; serverContactId = null; nativeContactId = null; nativeVal1 = null; nativeVal2 = null; nativeVal3 = null; boolean[] validDataList = new boolean[MemberData.values().length]; in.readBooleanArray(validDataList); if (validDataList[MemberData.LOCAL_DETAIL_ID.ordinal()]) { localDetailID = in.readLong(); // Primary key in database } if (validDataList[MemberData.LOCAL_CONTACT_ID.ordinal()]) { localContactID = in.readLong(); } if (validDataList[MemberData.KEY.ordinal()]) { key = DetailKeys.values()[in.readInt()]; } if (validDataList[MemberData.KEY_TYPE.ordinal()]) { keyType = DetailKeyTypes.values()[in.readInt()]; } if (validDataList[MemberData.VALUE.ordinal()]) { value = in.readString(); } if (validDataList[MemberData.DELETED.ordinal()]) { deleted = (in.readByte() == 0 ? false : true); } if (validDataList[MemberData.UPDATED.ordinal()]) { updated = in.readLong(); } if (validDataList[MemberData.UNIQUE_ID.ordinal()]) { unique_id = in.readLong(); } if (validDataList[MemberData.ORDER.ordinal()]) { order = in.readInt(); } if (validDataList[MemberData.LOCATION.ordinal()]) { location = Location.CREATOR.createFromParcel(in); } if (validDataList[MemberData.ALT.ordinal()]) { alt = in.readString(); } if (validDataList[MemberData.PHOTO.ordinal()]) { photo = Bitmap.CREATOR.createFromParcel(in); } if (validDataList[MemberData.PHOTO_MIME_TYPE.ordinal()]) { photo_mime_type = in.readString(); } if (validDataList[MemberData.PHOTO_URL.ordinal()]) { photo_url = in.readString(); } if (validDataList[MemberData.SERVER_CONTACT_ID.ordinal()]) { serverContactId = in.readLong(); } if (validDataList[MemberData.NATIVE_CONTACT_ID.ordinal()]) { nativeContactId = in.readInt(); } if (validDataList[MemberData.NATIVE_DETAIL_ID.ordinal()]) { nativeDetailId = in.readInt(); } if (validDataList[MemberData.NATIVE_VAL1.ordinal()]) { nativeVal1 = in.readString(); } if (validDataList[MemberData.NATIVE_VAL2.ordinal()]) { nativeVal2 = in.readString(); } if (validDataList[MemberData.NATIVE_VAL3.ordinal()]) { nativeVal3 = in.readString(); } } /** {@inheritDoc} */ @Override public int describeContents() { return 1; } /** {@inheritDoc} */ @Override public void writeToParcel(Parcel dest, int flags) { boolean[] validDataList = new boolean[MemberData.values().length]; diff --git a/src/com/vodafone360/people/engine/content/ThumbnailHandler.java b/src/com/vodafone360/people/engine/content/ThumbnailHandler.java index 0754b4c..981450c 100644 --- a/src/com/vodafone360/people/engine/content/ThumbnailHandler.java +++ b/src/com/vodafone360/people/engine/content/ThumbnailHandler.java @@ -1,274 +1,249 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.content; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.vodafone360.people.database.DatabaseHelper.ThumbnailInfo; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.content.ContentObject.TransferStatus; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.ThumbnailUtils; /** * ThumbnailHandler is a handler for contents. The ContentEngine uses handlers * to handle transfers of ContentObjects. The handler implements the * TransferListener interface and registers itself in the ContentObjects before * sending them to the ContentEngine. The ContentEngine calls the * TransferListener on a ContentObject after a transfer completes. The * ThumbnailHandler handles the fetching of thumbnails for contacts, saving them * and refreshing the list. */ public class ThumbnailHandler implements TransferListener { /** * instance of ThumbnailHandler. Used for singleton. */ private static ThumbnailHandler mThumbnailHandlerInstance; /** * Number of thumbnails to fetch in a single RPG request batch. */ private static final int MAX_THUMBS_FETCHED_PER_PAGE = 5; /** * Queue with contact IDs to fetch thumbnails for. The contact IDs are queued here * when the downloadContactThumbnails is called and are then fetched batch * for batch. The variable MAX_THUMBS_FETCHED_PER_PAGE defines how much are * processed at one time */ private List<Long> mContactsQueue = new LinkedList<Long>(); /** * List with ContentObjects. Every time a ContentObjects is created for * downloading it is puted in this list. Every time it is processed, it will * be removed. When the list is empty, the next batch of Contacts is * processed. */ private List<ContentObject> mContentObjects = new ArrayList<ContentObject>(); /** * Factory method for creating and getting singleton instance of this * handler. * * @return Instance of Thumbnailhandler */ public static synchronized ThumbnailHandler getInstance() { if (mThumbnailHandlerInstance == null) { mThumbnailHandlerInstance = new ThumbnailHandler(); } return mThumbnailHandlerInstance; } /** * Private constructor. The singleton method has to be used to obtain an * instance. */ private ThumbnailHandler() { } /** * Called by ContentEngine when a Transfer is done. It saves the thumbnail * to file, links it to the contact and refreshes the view. * * @param content Transfered ContentObject containing the Thumbnail */ @Override public final void transferComplete(final ContentObject content) { mContentObjects.remove(content); Long contactId = (Long) content.getLink(); try { ThumbnailUtils.saveExternalResponseObjectToFile(contactId, content .getExternalResponseObject()); ContentEngine contentEngine = EngineManager.getInstance().getContentEngine(); contentEngine.getDatabaseHelper().modifyPictureLoadedFlag(contactId, true); } catch (IOException e) { LogUtils.logE("ThumbnailHandler.TransferComplete", e); } if (mContentObjects.size() == 0) { downloadThumbnails(MAX_THUMBS_FETCHED_PER_PAGE); } } /** * Called when there was an error transfering a ContentObject. It can happen * when a timeout occurs, the URL is not valid, the server is not responding * and so on. * * @param content The failing ContentObject * @param exc RuntimeException explaining what happened */ @Override public final void transferError(final ContentObject content, final RuntimeException exc) { mContentObjects.remove(content); if (mContentObjects.size() == 0) { downloadThumbnails(MAX_THUMBS_FETCHED_PER_PAGE); } } - /** - * Returns a ThumbanailInfo for a given Contact ID from a list of - * ThumbnailInfos. When we fetch ThumbnailInfos for a big group of Contacts - * we will get an List with available ThumbnailInfos. Because not every - * Contact has a thumbnail mostly this List will be smaller then the given - * list of contacts. This method is then called to determine matching - * ThumbnailInfo for a Contact. - * - * @param thumbnailInfoList List with all available Thumbnails - * @param contactId The contact ID for which the ThumbnailInfo is to be - * searched for - * @return Matching ThumbnailInfo for the given Contact - */ - private ThumbnailInfo getThumbnailForContact(final List<ThumbnailInfo> thumbnailInfoList, - final Long contactId) { - for (ThumbnailInfo thumbnailInfo : thumbnailInfoList) { - if (thumbnailInfo.localContactId.equals(contactId)) { - return thumbnailInfo; - } - } - return null; - } - /** * Puts the contactlist in to a queue and starts downloading the thumbnails * for them. */ public final void downloadContactThumbnails() { List<Long> contactIdList = new ArrayList<Long>(); ContentEngine contentEngine = EngineManager.getInstance().getContentEngine(); contentEngine.getDatabaseHelper().fetchContactIdsWithThumbnails(contactIdList); for (Long contactId : contactIdList) { if (!mContactsQueue.contains(contactId)) { mContactsQueue.add(contactId); } } LogUtils.logI("Downloading " + mContactsQueue.size() + " thumbnails"); downloadThumbnails(MAX_THUMBS_FETCHED_PER_PAGE); } /** * Download the next bunch of contacts from the queue. The method uses the * ContentEngine to download the thumbnails and sets this class as a handler * * @param thumbsPerPage Indicates the number of thumbnails to be downloaded * in this page */ private void downloadThumbnails(final int thumbsPerPage) { List<Long> contactList = new ArrayList<Long>(); for (int i = 0; i < thumbsPerPage; i++) { if (mContactsQueue.size() == 0) { break; } contactList.add((Long) mContactsQueue.remove(0)); } // nothing to do? exit! if (contactList.size() == 0) { LogUtils.logI("Thumbnail download finished"); return; } // get the contentengine, so we can access the database ContentEngine contentEngine = EngineManager.getInstance().getContentEngine(); // list for holding the fetched ThumbnailURLs ArrayList<ThumbnailInfo> thumbnailInfoList = new ArrayList<ThumbnailInfo>(); // fetches the URLs of all thumbnails that are not downloaded by now contentEngine.getDatabaseHelper().fetchThumbnailUrlsForContacts(thumbnailInfoList, contactList); // This list is needed because of following usecase: We have started the // thumbnail sync. 5 thumbnails are requested and we have got the // response for 3 of them. At this point, the thumbnail sync starts // again(maybe because somethign got changed in the server). This // function gets called again. And if we don't use this temporary // contentList, those contentObjects for which we haven't got the // response yet are also added into the queue of the COntent Engine. List<ContentObject> contentList = new ArrayList<ContentObject>(); - // iterate over the given contactList - for (Long contactId : contactList) { + // iterate over the given thumbnailInfoList + for (ThumbnailInfo thumbnailInfo : thumbnailInfoList) { - // find an ThumbnailUrl for a contact - ThumbnailInfo thumbnailInfo = getThumbnailForContact(thumbnailInfoList, contactId); // not every contact has a thumbnail, so continue in this case if (thumbnailInfo == null) { continue; } try { // create a ContentObject for downloading the particular // Thumbnail... - ContentObject contentObject = new ContentObject(null, contactId, this, + ContentObject contentObject = new ContentObject(null, thumbnailInfo.localContactId, this, ContentObject.TransferDirection.DOWNLOAD, ContentObject.Protocol.RPG); // ... set the right URL and params... contentObject.setUrl(new URL(thumbnailInfo.photoServerUrl)); contentObject.setUrlParams(ThumbnailUtils.REQUEST_THUMBNAIL_URI); contentObject.setTransferStatus(TransferStatus.INIT); contentList.add(contentObject); // ... and put it to the list mContentObjects.add(contentObject); } catch (MalformedURLException e) { LogUtils.logE("ThumbanailHandler.downloadContactThumbnails: " + thumbnailInfo.photoServerUrl + " is not a valid URL"); } } // if the list is not empty, let the ContentEngine process them if (mContentObjects.size() > 0) { contentEngine.processContentObjects(contentList); } } /** * Dummy method to replace the dummy processor. */ public void uploadServerThumbnails() { } /** * Performs a reset. */ public void reset() { mContactsQueue.clear(); mContentObjects.clear(); } } diff --git a/src/com/vodafone360/people/utils/LogUtils.java b/src/com/vodafone360/people/utils/LogUtils.java index fa402c7..ee9e34e 100644 --- a/src/com/vodafone360/people/utils/LogUtils.java +++ b/src/com/vodafone360/people/utils/LogUtils.java @@ -1,302 +1,302 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import android.os.Environment; import android.util.Log; import com.vodafone360.people.Settings; /** * Logging utility functions: Allows logging to be enabled, Logs application * name and current thread name prepended to logged data. */ public final class LogUtils { /** Application tag prefix for LogCat. **/ private static final String APP_NAME_PREFIX = "People_"; /** Simple date format for Logging. **/ private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); /** SD Card filename. **/ private static final String APP_FILE_NAME = "/sdcard/people.log"; /** SD Card log file size limit (in bytes). **/ private static final int LOG_FILE_LIMIT = 100000; /** Maximum number of SD Card log files. **/ private static final int LOG_FILE_COUNT = 50; /** Stores the enabled state of the LogUtils function. **/ private static Boolean mEnabled = false; /** SD Card data logger. **/ private static Logger sLogger; /** SD Card data profile logger. **/ private static Logger sProfileLogger; /*** * Private constructor makes it impossible to create an instance of this * utility class. */ private LogUtils() { // Do nothing. } /** * Enable logging. */ public static void enableLogcat() { mEnabled = true; /** Enable the SD Card logger **/ sLogger = Logger.getLogger(APP_NAME_PREFIX); try { FileHandler fileHandler = new FileHandler(APP_FILE_NAME, LOG_FILE_LIMIT, LOG_FILE_COUNT); fileHandler.setFormatter(new Formatter() { @Override public String format(final LogRecord logRecord) { StringBuilder sb = new StringBuilder(); sb.append(DATE_FORMAT.format( new Date(logRecord.getMillis()))); sb.append(" "); sb.append(logRecord.getMessage()); sb.append("\n"); return sb.toString(); } }); sLogger.addHandler(fileHandler); } catch (IOException e) { logE("LogUtils.logToFile() IOException, data will not be logged " + "to file", e); sLogger = null; } if (Settings.ENABLED_PROFILE_ENGINES) { /** Enable the SD Card profiler **/ sProfileLogger = Logger.getLogger("profiler"); try { FileHandler fileHandler = new FileHandler("/sdcard/engineprofiler.log", LOG_FILE_LIMIT, LOG_FILE_COUNT); fileHandler.setFormatter(new Formatter() { @Override public String format(final LogRecord logRecord) { StringBuilder sb = new StringBuilder(); sb.append(DATE_FORMAT.format( new Date(logRecord.getMillis()))); sb.append("|"); sb.append(logRecord.getMessage()); sb.append("\n"); return sb.toString(); } }); sProfileLogger.addHandler(fileHandler); } catch (IOException e) { logE("LogUtils.logToFile() IOException, data will not be logged " + "to file", e); sProfileLogger = null; } } } /** * Write info log string. * * @param data String containing data to be logged. */ public static void logI(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.i(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write debug log string. * * @param data String containing data to be logged. */ public static void logD(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.d(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write warning log string. * * @param data String containing data to be logged. */ public static void logW(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.w(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write error log string. * * @param data String containing data to be logged. */ public static void logE(final String data) { // FlurryAgent.onError("Generic", data, "Unknown"); if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.e(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write verbose log string. * * @param data String containing data to be logged. */ public static void logV(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.v(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write info log string with specific component name. * * @param name String name string to prepend to log data. * @param data String containing data to be logged. */ public static void logWithName(final String name, final String data) { if (mEnabled) { Log.v(APP_NAME_PREFIX + name, data); } } /** * Write error log string with Exception thrown. * * @param data String containing data to be logged. * @param exception Exception associated with error. */ public static void logE(final String data, final Throwable exception) { // FlurryAgent.onError("Generic", data, // exception.getClass().toString()); if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.e(APP_NAME_PREFIX + currentThread.getName(), data, exception); } } /*** * Write a line to the SD Card log file (e.g. "Deleted contact name from * NAB because...."). * * @param data String containing data to be logged. */ public static void logToFile(final String data) { if (mEnabled && sLogger != null) { sLogger.log(new LogRecord(Level.INFO, data)); } } /*** * Write a line to the SD Card log file (e.g. "Deleted contact name from * NAB because...."). * * @param data String containing data to be logged. */ public static void profileToFile(final String data) { if (mEnabled && sProfileLogger != null) { sProfileLogger.log(new LogRecord(Level.INFO, data)); } } /** * * Writes a given byte-array to the SD card under the given file name. * * @param data The data to write to the SD card. * @param fileName The file name to write the data under. * */ public static void logToFile(final byte[] data, final String fileName) { if (Settings.sEnableSuperExpensiveResponseFileLogging) { FileOutputStream fos = null; try { File root = Environment.getExternalStorageDirectory(); - if (root.canWrite()){ + if (root.canWrite()) { File binaryFile = new File(root, fileName); fos = new FileOutputStream(binaryFile); fos.write(data); fos.flush(); } else { logE("LogUtils.logToFile() Could not write to SD card. Missing a permission? " + "SC Card is currently "+ Environment.getExternalStorageState()); } } catch (IOException e) { logE("LogUtils.logToFile() Could not write " + fileName + " to SD card! Exception: "+e); } finally { if (null != fos) { try { fos.close(); } catch (IOException ioe) { logE("LogUtils.logToFile() Could not close file output stream!"); } } } } } /*** * Returns if the logging feature is currently enabled. * * @return TRUE if logging is enabled, FALSE otherwise. */ public static Boolean isEnabled() { return mEnabled; } } \ No newline at end of file
360/360-Engine-for-Android
568a024fd03038ad951fa019d23885b61b71852b
Fix for PAND-2400: NullPointerException when file logging if switched on and SD Card is PC mounted
diff --git a/src/com/vodafone360/people/service/RemoteService.java b/src/com/vodafone360/people/service/RemoteService.java index c2b15ef..e2a4a6a 100644 --- a/src/com/vodafone360/people/service/RemoteService.java +++ b/src/com/vodafone360/people/service/RemoteService.java @@ -1,330 +1,334 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import java.security.InvalidParameterException; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import com.vodafone360.people.MainApplication; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.interfaces.IConnectionManagerInterface; import com.vodafone360.people.service.interfaces.IPeopleServiceImpl; import com.vodafone360.people.service.interfaces.IWorkerThreadControl; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.IWakeupListener; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * Implementation of People client's Service class. Loads properties from * SettingsManager. Creates NetworkAgent. Connects to ConnectionManager enabling * transport layer. Activates service's worker thread when required. */ public class RemoteService extends Service implements IWorkerThreadControl, IConnectionManagerInterface { /** * Intent received when service is started is tested against the value * stored in this key to determine if the service has been started because * of an alarm. */ public static final String ALARM_KEY = "alarm_key"; /** * Action for an Authenticator. * Straight copy from AccountManager.ACTION_AUTHENTICATOR_INTENT in 2.X platform */ public static final String ACTION_AUTHENTICATOR_INTENT = "android.accounts.AccountAuthenticator"; /** * Sync Adapter System intent action received on Bind. */ public static final String ACTION_SYNC_ADAPTER_INTENT = "android.content.SyncAdapter"; /** * Main reference to network agent * * @see NetworkAgent */ private NetworkAgent mNetworkAgent; /** * Worker thread reference * * @see WorkerThread */ private WorkerThread mWorkerThread; /** * The following object contains the implementation of the * {@link com.vodafone360.people.service.interfaces.IPeopleService} * interface. */ private IPeopleServiceImpl mIPeopleServiceImpl; /** * Used by comms when waking up the CPI at regular intervals and sending a * heartbeat is necessary */ private IWakeupListener mWakeListener; /** * true when the service has been fully initialised */ private boolean mIsStarted = false; /** * Stores the previous network connection state (true = connected) */ private boolean mIsConnected = true; private NativeAccountObjectsHolder mAccountsObjectsHolder = null; /** * Creation of RemoteService. Loads properties (i.e. supported features, * server URLs etc) from SettingsManager. Creates IPeopleServiceImpl, * NetworkAgent. Connects ConnectionManager creating Connection thread(s) * and DecoderThread 'Kicks' worker thread. */ @Override public void onCreate() { LogUtils.logV("RemoteService.onCreate()"); SettingsManager.loadProperties(this); mIPeopleServiceImpl = new IPeopleServiceImpl(this, this); mNetworkAgent = new NetworkAgent(this, this, this); // Create NativeContactsApi here to access Application Context NativeContactsApi.createInstance(getApplicationContext()); EngineManager.createEngineManager(this, mIPeopleServiceImpl); mNetworkAgent.onCreate(); mIPeopleServiceImpl.setNetworkAgent(mNetworkAgent); ConnectionManager.getInstance().connect(this); /** The service has now been fully initialised. **/ mIsStarted = true; kickWorkerThread(); ((MainApplication)getApplication()).setServiceInterface(mIPeopleServiceImpl); if(VersionUtils.is2XPlatform()) { mAccountsObjectsHolder = new NativeAccountObjectsHolder(((MainApplication)getApplication())); } } /** * Called on start of RemoteService. Check if we need to kick the worker * thread or 'wake' the TCP connection thread. */ @Override public void onStart(Intent intent, int startId) { + if(intent == null) { + LogUtils.logV("RemoteService.onStart() intent is null. Returning."); + return; + } Bundle mBundle = intent.getExtras(); LogUtils.logI("RemoteService.onStart() Intent action[" + intent.getAction() + "] data[" + mBundle + "]"); if ((null == mBundle) || (null == mBundle.getString(ALARM_KEY))) { LogUtils.logV("RemoteService.onStart() mBundle is null. Returning."); return; } if (mBundle.getString(ALARM_KEY).equals(WorkerThread.ALARM_WORKER_THREAD)) { LogUtils.logV("RemoteService.onStart() ALARM_WORKER_THREAD Alarm thrown"); kickWorkerThread(); } else if (mBundle.getString(ALARM_KEY).equals(IWakeupListener.ALARM_HB_THREAD)) { LogUtils.logV("RemoteService.onStart() ALARM_HB_THREAD Alarm thrown"); if (null != mWakeListener) { mWakeListener.notifyOfWakeupAlarm(); } } } /** * Destroy RemoteService Close WorkerThread, destroy EngineManger and * NetworkAgent. */ @Override public void onDestroy() { LogUtils.logV("RemoteService.onDestroy()"); ((MainApplication)getApplication()).setServiceInterface(null); mIsStarted = false; synchronized (this) { if (mWorkerThread != null) { mWorkerThread.close(); } } EngineManager.destroyEngineManager(); // No longer need NativeContactsApi NativeContactsApi.destroyInstance(); mNetworkAgent.onDestroy(); } /** * Service binding is not used internally by this Application, but called * externally by the system when it needs an Authenticator or Sync * Adapter. This method will throw an InvalidParameterException if it is * not called with the expected intent (or called on a 1.x platform). */ @Override public IBinder onBind(Intent intent) { final String action = intent.getAction(); if (VersionUtils.is2XPlatform() && action != null) { if (action.equals(ACTION_AUTHENTICATOR_INTENT)) { return mAccountsObjectsHolder.getAuthenticatorBinder(); } else if (action.equals(ACTION_SYNC_ADAPTER_INTENT)) { return mAccountsObjectsHolder.getSyncAdapterBinder(); } } throw new InvalidParameterException("RemoteService.action() " + "There are no Binders for the given Intent"); } /*** * Ensures that the WorkerThread runs at least once. */ @Override public void kickWorkerThread() { synchronized (this) { if (!mIsStarted) { // Thread will be kicked anyway once we have finished // initialisation. return; } if (mWorkerThread == null || !mWorkerThread.wakeUp()) { LogUtils.logV("RemoteService.kickWorkerThread() Start thread"); mWorkerThread = new WorkerThread(mHandler); mWorkerThread.start(); } } } /*** * Handler for remotely calling the kickWorkerThread() method. */ private final Handler mHandler = new Handler() { /** * Process kick worker thread message */ @Override public void handleMessage(Message msg) { kickWorkerThread(); } }; /** * Called by NetworkAgent to notify whether device has become connected or * disconnected. The ConnectionManager connects or disconnects * appropriately. We kick the worker thread if our internal connection state * is changed. * * @param connected true if device has become connected, false if device is * disconnected. */ @Override public void signalConnectionManager(boolean connected) { // if service agent becomes connected start conn mgr thread LogUtils.logI("RemoteService.signalConnectionManager()" + "Signalling Connection Manager to " + (connected ? "connect." : "disconnect.")); if (connected) { ConnectionManager.getInstance().connect(this); } else {// SA is disconnected stop conn thread (and close connections?) ConnectionManager.getInstance().disconnect(); } // kick EngineManager to run() and apply CONNECTED/DISCONNECTED changes if (connected != mIsConnected) { if (mIPeopleServiceImpl != null) { mIPeopleServiceImpl.kickWorkerThread(); } } mIsConnected = connected; } /** * <p> * Registers a listener (e.g. the HeartbeatSender for TCP) that will be * notified whenever an intent for a new alarm is received. * </p> * <p> * This is desperately needed as the CPU of Android devices will halt when * the user turns off the screen and all CPU related activity is suspended * for that time. The wake up alarm is one simple way of achieving the CPU * to wake up and send out data (e.g. the heartbeat sender). * </p> */ public void registerCpuWakeupListener(IWakeupListener wakeListener) { mWakeListener = wakeListener; } /** * Return handle to {@link NetworkAgent} * * @return handle to {@link NetworkAgent} */ public NetworkAgent getNetworkAgent() { return mNetworkAgent; } /** * Set an Alarm with the AlarmManager to trigger the next update check. * * @param set Set or cancel the Alarm * @param realTime Time when the Alarm should be triggered */ public void setAlarm(boolean set, long realTime) { Intent mRemoteServiceIntent = new Intent(this, this.getClass()); mRemoteServiceIntent.putExtra(RemoteService.ALARM_KEY, IWakeupListener.ALARM_HB_THREAD); PendingIntent mAlarmSender = PendingIntent.getService(this, 0, mRemoteServiceIntent, 0); AlarmManager mAlarmManager = (AlarmManager)getSystemService(RemoteService.ALARM_SERVICE); if (set) { if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logV("WorkerThread.setAlarm() Check for the next update at [" + realTime + "] or in [" + (realTime - System.currentTimeMillis()) + "ms]"); } mAlarmManager.set(AlarmManager.RTC_WAKEUP, realTime, mAlarmSender); /* * mAlarmManager.set(AlarmManager.RTC, realTime, mAlarmSender); * TODO: Optimisation suggestion - Consider only doing work when the * device is already awake */ } else { mAlarmManager.cancel(mAlarmSender); } } } diff --git a/src/com/vodafone360/people/utils/LogUtils.java b/src/com/vodafone360/people/utils/LogUtils.java index f00d894..fa402c7 100644 --- a/src/com/vodafone360/people/utils/LogUtils.java +++ b/src/com/vodafone360/people/utils/LogUtils.java @@ -1,297 +1,302 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import android.os.Environment; import android.util.Log; import com.vodafone360.people.Settings; /** * Logging utility functions: Allows logging to be enabled, Logs application * name and current thread name prepended to logged data. */ public final class LogUtils { /** Application tag prefix for LogCat. **/ private static final String APP_NAME_PREFIX = "People_"; /** Simple date format for Logging. **/ private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); /** SD Card filename. **/ private static final String APP_FILE_NAME = "/sdcard/people.log"; /** SD Card log file size limit (in bytes). **/ private static final int LOG_FILE_LIMIT = 100000; /** Maximum number of SD Card log files. **/ private static final int LOG_FILE_COUNT = 50; /** Stores the enabled state of the LogUtils function. **/ private static Boolean mEnabled = false; /** SD Card data logger. **/ private static Logger sLogger; /** SD Card data profile logger. **/ private static Logger sProfileLogger; /*** * Private constructor makes it impossible to create an instance of this * utility class. */ private LogUtils() { // Do nothing. } /** * Enable logging. */ public static void enableLogcat() { mEnabled = true; /** Enable the SD Card logger **/ sLogger = Logger.getLogger(APP_NAME_PREFIX); try { FileHandler fileHandler = new FileHandler(APP_FILE_NAME, LOG_FILE_LIMIT, LOG_FILE_COUNT); fileHandler.setFormatter(new Formatter() { @Override public String format(final LogRecord logRecord) { StringBuilder sb = new StringBuilder(); sb.append(DATE_FORMAT.format( new Date(logRecord.getMillis()))); sb.append(" "); sb.append(logRecord.getMessage()); sb.append("\n"); return sb.toString(); } }); sLogger.addHandler(fileHandler); } catch (IOException e) { logE("LogUtils.logToFile() IOException, data will not be logged " + "to file", e); sLogger = null; } if (Settings.ENABLED_PROFILE_ENGINES) { /** Enable the SD Card profiler **/ sProfileLogger = Logger.getLogger("profiler"); try { FileHandler fileHandler = new FileHandler("/sdcard/engineprofiler.log", LOG_FILE_LIMIT, LOG_FILE_COUNT); fileHandler.setFormatter(new Formatter() { @Override public String format(final LogRecord logRecord) { StringBuilder sb = new StringBuilder(); sb.append(DATE_FORMAT.format( new Date(logRecord.getMillis()))); sb.append("|"); sb.append(logRecord.getMessage()); sb.append("\n"); return sb.toString(); } }); sProfileLogger.addHandler(fileHandler); } catch (IOException e) { logE("LogUtils.logToFile() IOException, data will not be logged " + "to file", e); sProfileLogger = null; } } } /** * Write info log string. * * @param data String containing data to be logged. */ public static void logI(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.i(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write debug log string. * * @param data String containing data to be logged. */ public static void logD(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.d(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write warning log string. * * @param data String containing data to be logged. */ public static void logW(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.w(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write error log string. * * @param data String containing data to be logged. */ public static void logE(final String data) { // FlurryAgent.onError("Generic", data, "Unknown"); if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.e(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write verbose log string. * * @param data String containing data to be logged. */ public static void logV(final String data) { if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.v(APP_NAME_PREFIX + currentThread.getName(), data); } } /** * Write info log string with specific component name. * * @param name String name string to prepend to log data. * @param data String containing data to be logged. */ public static void logWithName(final String name, final String data) { if (mEnabled) { Log.v(APP_NAME_PREFIX + name, data); } } /** * Write error log string with Exception thrown. * * @param data String containing data to be logged. * @param exception Exception associated with error. */ public static void logE(final String data, final Throwable exception) { // FlurryAgent.onError("Generic", data, // exception.getClass().toString()); if (mEnabled) { Thread currentThread = Thread.currentThread(); Log.e(APP_NAME_PREFIX + currentThread.getName(), data, exception); } } /*** * Write a line to the SD Card log file (e.g. "Deleted contact name from * NAB because...."). * * @param data String containing data to be logged. */ public static void logToFile(final String data) { if (mEnabled && sLogger != null) { sLogger.log(new LogRecord(Level.INFO, data)); } } /*** * Write a line to the SD Card log file (e.g. "Deleted contact name from * NAB because...."). * * @param data String containing data to be logged. */ public static void profileToFile(final String data) { if (mEnabled && sProfileLogger != null) { sProfileLogger.log(new LogRecord(Level.INFO, data)); } } /** * * Writes a given byte-array to the SD card under the given file name. * * @param data The data to write to the SD card. * @param fileName The file name to write the data under. * */ public static void logToFile(final byte[] data, final String fileName) { if (Settings.sEnableSuperExpensiveResponseFileLogging) { FileOutputStream fos = null; try { File root = Environment.getExternalStorageDirectory(); if (root.canWrite()){ File binaryFile = new File(root, fileName); fos = new FileOutputStream(binaryFile); fos.write(data); fos.flush(); + } else { + logE("LogUtils.logToFile() Could not write to SD card. Missing a permission? " + + "SC Card is currently "+ + Environment.getExternalStorageState()); } } catch (IOException e) { - logE("LogUtils.logToFile() Could not write " + fileName + " to SD card!"); + logE("LogUtils.logToFile() Could not write " + fileName + + " to SD card! Exception: "+e); } finally { if (null != fos) { try { fos.close(); } catch (IOException ioe) { logE("LogUtils.logToFile() Could not close file output stream!"); } } } } } /*** * Returns if the logging feature is currently enabled. * * @return TRUE if logging is enabled, FALSE otherwise. */ public static Boolean isEnabled() { return mEnabled; } } \ No newline at end of file
360/360-Engine-for-Android
e88ec10c82186169a7f416f26ac7a06684f27751
PAND-2170. review fix
diff --git a/src/com/vodafone360/people/service/agent/NetworkAgent.java b/src/com/vodafone360/people/service/agent/NetworkAgent.java index 07b74f4..8a77804 100644 --- a/src/com/vodafone360/people/service/agent/NetworkAgent.java +++ b/src/com/vodafone360/people/service/agent/NetworkAgent.java @@ -1,714 +1,714 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.agent; import java.security.InvalidParameterException; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.ContentObserver; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.telephony.TelephonyManager; import android.text.format.DateUtils; import com.vodafone360.people.Intents; import com.vodafone360.people.MainApplication; import com.vodafone360.people.service.PersistSettings; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.interfaces.IConnectionManagerInterface; import com.vodafone360.people.service.interfaces.IWorkerThreadControl; import com.vodafone360.people.utils.LogUtils; /** * The network Agent monitors the connectivity status of the device and makes * decisions about the communication strategy. The Agent has the following * states {connected | disconnected}, with changes reported to various listeners * in the service. */ public class NetworkAgent { /** Roaming notification is on */ public static final int ROAMING_DIALOG_GLOBAL_ON = 0; /** Roaming notification is off */ public static final int ROAMING_DIALOG_GLOBAL_OFF = 1; private static final int TYPE_WIFI = 1; private static AgentState mAgentState = AgentState.UNKNOWN; private ConnectivityManager mConnectivityManager; private ContentResolver mContentResolver; - private static AgentDisconnectReason mDisconnectReason = AgentDisconnectReason.UNKNOWN; + private static AgentDisconnectReason sDisconnectReason = AgentDisconnectReason.UNKNOWN; private SettingsContentObserver mDataRoamingSettingObserver; private boolean mInternetConnected; private boolean mDataRoaming; private boolean mBackgroundData; private boolean mIsRoaming; private boolean mIsInBackground; private boolean mNetworkWorking = true; // dateTime value in milliseconds private Long mDisableRoamingNotificationUntil = null; private IWorkerThreadControl mWorkerThreadControl; private IConnectionManagerInterface mConnectionMgrIf; private Context mContext; public enum AgentState { CONNECTED, DISCONNECTED, UNKNOWN }; private boolean mWifiNetworkAvailable; private boolean mMobileNetworkAvailable; /** * Reasons for Service Agent changing state to disconnected */ public enum AgentDisconnectReason { AGENT_IS_CONNECTED, // Sanity check NO_INTERNET_CONNECTION, NO_WORKING_NETWORK, DATA_SETTING_SET_TO_MANUAL_CONNECTION, DATA_ROAMING_DISABLED, BACKGROUND_CONNECTION_DISABLED, // WIFI_INACTIVE, UNKNOWN } public enum StatesOfService { IS_CONNECTED_TO_INTERNET, IS_NETWORK_WORKING, IS_ROAMING, IS_ROAMING_ALLOWED, IS_INBACKGROUND, IS_BG_CONNECTION_ALLOWED, IS_WIFI_ACTIVE }; /** * Listens for changes made to People client's status. The NetworkAgent is * specifically interested in changes to the data settings (e.g. data * disabled, only in home network or roaming). */ private class SettingsContentObserver extends ContentObserver { private String mSettingName; private SettingsContentObserver(String settingName) { super(new Handler()); mSettingName = settingName; } /** * Start content observer. */ private void start() { if (mContentResolver != null) { mContentResolver.registerContentObserver(Settings.Secure.getUriFor(mSettingName), true, this); } } /** * De-activate content observer. */ private void close() { if (mContentResolver != null) { mContentResolver.unregisterContentObserver(this); } } @Override public void onChange(boolean selfChange) { onDataSettingChanged(mSettingName); } public boolean getBooleanValue() { if (mContentResolver != null) { try { return (Settings.Secure.getInt(mContentResolver, mSettingName) != 0); } catch (SettingNotFoundException e) { LogUtils.logE("NetworkAgent.SettingsContentObserver.getBooleanValue() " + "SettingNotFoundException", e); return false; } } return false; } } /** * The constructor. * * @param context Android context. * @param workerThreadControl Handle to kick the worker thread. * @param connMgrIf Handler to signal the connection manager. * @throws InvalidParameterException Context is NULL. * @throws InvalidParameterException IWorkerThreadControl is NULL. * @throws InvalidParameterException IConnectionManagerInterface is NULL. */ public NetworkAgent(Context context, IWorkerThreadControl workerThreadControl, IConnectionManagerInterface connMgrIf) { if (context == null) { throw new InvalidParameterException("NetworkAgent() Context canot be NULL"); } if (workerThreadControl == null) { throw new InvalidParameterException("NetworkAgent() IWorkerThreadControl canot be NULL"); } if (connMgrIf == null) { throw new InvalidParameterException( "NetworkAgent() IConnectionManagerInterface canot be NULL"); } mContext = context; mWorkerThreadControl = workerThreadControl; mConnectionMgrIf = connMgrIf; mContentResolver = context.getContentResolver(); mConnectivityManager = (ConnectivityManager)context .getSystemService(Context.CONNECTIVITY_SERVICE); mDataRoamingSettingObserver = new SettingsContentObserver(Settings.Secure.DATA_ROAMING); } /** * Create NetworkAgent and start observers of device connectivity state. * * @throws InvalidParameterException DataRoamingSettingObserver is NULL. * @throws InvalidParameterException Context is NULL. * @throws InvalidParameterException ConnectivityManager is NULL. */ public void onCreate() { if (mDataRoamingSettingObserver == null) { throw new InvalidParameterException( "NetworkAgent.onCreate() DataRoamingSettingObserver canot be NULL"); } if (mContext == null) { throw new InvalidParameterException("NetworkAgent.onCreate() Context canot be NULL"); } if (mConnectivityManager == null) { throw new InvalidParameterException( "NetworkAgent.onCreate() ConnectivityManager canot be NULL"); } mDataRoamingSettingObserver.start(); mDataRoaming = mDataRoamingSettingObserver.getBooleanValue(); mContext.registerReceiver(mBackgroundDataBroadcastReceiver, new IntentFilter( ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED)); mContext.registerReceiver(mInternetConnectivityReceiver, new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION)); mContext.registerReceiver(mServiceStateRoamingReceiver, new IntentFilter( "android.intent.action.SERVICE_STATE")); NetworkInfo info = mConnectivityManager.getActiveNetworkInfo(); if (info != null) { mInternetConnected = (info.getState() == NetworkInfo.State.CONNECTED); mWifiNetworkAvailable = (info.getType() == TYPE_WIFI); mIsRoaming = info.isRoaming(); } mBackgroundData = mConnectivityManager.getBackgroundDataSetting(); onConnectionStateChanged(); } /** * Destroy NetworkAgent and un-register observers. * * @throws InvalidParameterException Context is NULL. * @throws InvalidParameterException DataRoamingSettingObserver is NULL. */ public void onDestroy() { if (mContext == null) { throw new InvalidParameterException("NetworkAgent.onCreate() Context canot be NULL"); } if (mDataRoamingSettingObserver == null) { throw new InvalidParameterException( "NetworkAgent.onDestroy() DataRoamingSettingObserver canot be NULL"); } mContext.unregisterReceiver(mInternetConnectivityReceiver); mContext.unregisterReceiver(mBackgroundDataBroadcastReceiver); mContext.unregisterReceiver(mServiceStateRoamingReceiver); mDataRoamingSettingObserver.close(); mDataRoamingSettingObserver = null; } /** * Receive notification from * ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED */ private final BroadcastReceiver mBackgroundDataBroadcastReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogUtils .logV("NetworkAgent.broadcastReceiver.onReceive() ACTION_BACKGROUND_DATA_SETTING_CHANGED"); synchronized (NetworkAgent.this) { if (mConnectivityManager != null) { mBackgroundData = mConnectivityManager.getBackgroundDataSetting(); onConnectionStateChanged(); } } } }; /** * Receive notification from ConnectivityManager.CONNECTIVITY_ACTION */ private final BroadcastReceiver mInternetConnectivityReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() CONNECTIVITY_ACTION"); synchronized (NetworkAgent.this) { NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); if (info == null) { LogUtils.logW("NetworkAgent.broadcastReceiver.onReceive() EXTRA_NETWORK_INFO not found."); } else { if (info.getType() == TYPE_WIFI) { mWifiNetworkAvailable = (info.getState() == NetworkInfo.State.CONNECTED); } else { mMobileNetworkAvailable = (info.getState() == NetworkInfo.State.CONNECTED); } } if (noConnectivity) { LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() EXTRA_NO_CONNECTIVITY found!"); mInternetConnected = false; } else { mInternetConnected = mWifiNetworkAvailable || mMobileNetworkAvailable; } LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() mInternetConnected = " + mInternetConnected + ", mWifiNetworkAvailable = " + mWifiNetworkAvailable + ", mMobileNetworkAvailable = " + mMobileNetworkAvailable); onConnectionStateChanged(); } } }; /** * Receive notification from android.intent.action.SERVICE_STATE */ private final BroadcastReceiver mServiceStateRoamingReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() SERVICE_STATE"); synchronized (NetworkAgent.this) { // //ConnectivityManager provides wrong information about // roaming // NetworkInfo info = // mConnectivityManager.getActiveNetworkInfo(); // if (info != null) { // mIsRoaming = info.isRoaming(); // } LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() Extras are: " + intent.getExtras()); Bundle bu = intent.getExtras(); // int state = bu.getInt("state"); boolean roam = bu.getBoolean("roaming"); mIsRoaming = roam; onConnectionStateChanged(); LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() Network Roaming = " + mIsRoaming); LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() WiFi active = " + mWifiNetworkAvailable); } processRoaming(null); } }; /** * Notify interested parties of changes in Internet setting. * * @param val updated InternetAvail value. */ public void notifyDataSettingChanged(InternetAvail val) { processRoaming(val); onConnectionStateChanged(); } /** * Displaying notification to the user about roaming * * @param InternetAvail value. */ private void processRoaming(InternetAvail val) { InternetAvail internetAvail; if (val != null) { internetAvail = val; } else { internetAvail = getInternetAvailSetting(); } Intent intent = new Intent(); if (mContext != null && mIsRoaming && (internetAvail == InternetAvail.ALWAYS_CONNECT) && (mDisableRoamingNotificationUntil == null || mDisableRoamingNotificationUntil < System .currentTimeMillis())) { LogUtils.logV("NetworkAgent.processRoaming() " + "Displaying notification - DisplayRoaming[" + mIsRoaming + "]"); intent.setAction(Intents.ROAMING_ON); } else { /* * We are not roaming then we should remove notification, if no * notification were before nothing happens */ LogUtils.logV("NetworkAgent.processRoaming() Removing notification - " + " DisplayRoaming[" + mIsRoaming + "]"); intent.setAction(Intents.ROAMING_OFF); } mContext.sendBroadcast(intent); } private InternetAvail getInternetAvailSetting() { if (mContext != null) { PersistSettings setting = ((MainApplication)((RemoteService)mContext).getApplication()) .getDatabase().fetchOption(PersistSettings.Option.INTERNETAVAIL); if (setting != null) { return setting.getInternetAvail(); } } return null; } public int getRoamingNotificationType() { int type; if (mDataRoaming) { type = ROAMING_DIALOG_GLOBAL_ON; } else { type = ROAMING_DIALOG_GLOBAL_OFF; } return type; } /** * Get current device roaming setting. * * @return current device roaming setting. */ public boolean getRoamingDeviceSetting() { return mDataRoaming; } public void setShowRoamingNotificationAgain(boolean showAgain) { LogUtils.logV("NetworkAgent.setShowRoamingNotificationAgain() " + "showAgain[" + showAgain + "]"); if (showAgain) { mDisableRoamingNotificationUntil = null; } else { mDisableRoamingNotificationUntil = System.currentTimeMillis() + DateUtils.DAY_IN_MILLIS; if (mContext != null) { LogUtils.logV("NetworkAgent.setShowRoamingNotificationAgain() " + "Next notification on [" + DateUtils.formatDateTime(mContext, mDisableRoamingNotificationUntil, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_YEAR) + "]"); } } processRoaming(null); } /** * Received when user modifies one of the system settings */ private synchronized void onDataSettingChanged(String settingName) { LogUtils.logV("NetworkAgent.onDataSettingChanged() settingName[" + settingName + "]" + " has changed"); if (settingName.equals(Settings.Secure.DATA_ROAMING)) { if (mDataRoamingSettingObserver != null) { mDataRoaming = mDataRoamingSettingObserver.getBooleanValue(); onConnectionStateChanged(); } } } /** * Contains the main logic that determines the agent state for network * access */ private void onConnectionStateChanged() { if (mContext != null) { MainApplication app = (MainApplication)((RemoteService)mContext).getApplication(); if ((app.getInternetAvail() == InternetAvail.MANUAL_CONNECT)/* * AA: I * commented * it - * TBD * &&! * mWifiNetworkAvailable */) { LogUtils.logV("NetworkAgent.onConnectionStateChanged()" + " Internet allowed only in manual mode"); - mDisconnectReason = AgentDisconnectReason.DATA_SETTING_SET_TO_MANUAL_CONNECTION; + sDisconnectReason = AgentDisconnectReason.DATA_SETTING_SET_TO_MANUAL_CONNECTION; setNewState(AgentState.DISCONNECTED); return; } } if (!mNetworkWorking) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() Network is not working"); - mDisconnectReason = AgentDisconnectReason.NO_WORKING_NETWORK; + sDisconnectReason = AgentDisconnectReason.NO_WORKING_NETWORK; setNewState(AgentState.DISCONNECTED); return; } if (mIsRoaming && !mDataRoaming && !mWifiNetworkAvailable) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() " + "Connect while roaming not allowed"); - mDisconnectReason = AgentDisconnectReason.DATA_ROAMING_DISABLED; + sDisconnectReason = AgentDisconnectReason.DATA_ROAMING_DISABLED; setNewState(AgentState.DISCONNECTED); return; } if (mIsInBackground && !mBackgroundData) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() Background connection not allowed"); - mDisconnectReason = AgentDisconnectReason.BACKGROUND_CONNECTION_DISABLED; + sDisconnectReason = AgentDisconnectReason.BACKGROUND_CONNECTION_DISABLED; setNewState(AgentState.DISCONNECTED); return; } if (!mInternetConnected) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() No internet connection"); - mDisconnectReason = AgentDisconnectReason.NO_INTERNET_CONNECTION; + sDisconnectReason = AgentDisconnectReason.NO_INTERNET_CONNECTION; setNewState(AgentState.DISCONNECTED); return; } if (mWifiNetworkAvailable) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() WIFI connected"); } else { LogUtils.logV("NetworkAgent.onConnectionStateChanged() Cellular connected"); } LogUtils.logV("NetworkAgent.onConnectionStateChanged() Connection available"); setNewState(AgentState.CONNECTED); } public static AgentState getAgentState() { LogUtils.logV("NetworkAgent.getAgentState() mAgentState[" + mAgentState.name() + "]"); return mAgentState; } public static ServiceStatus getServiceStatusfromDisconnectReason() { - if (mDisconnectReason != null) - switch (mDisconnectReason) + if (sDisconnectReason != null) + switch (sDisconnectReason) { case AGENT_IS_CONNECTED: return ServiceStatus.SUCCESS; case NO_WORKING_NETWORK: return ServiceStatus.ERROR_NO_INTERNET; case NO_INTERNET_CONNECTION: return ServiceStatus.ERROR_NO_INTERNET; case DATA_ROAMING_DISABLED: return ServiceStatus.ERROR_ROAMING_INTERNET_NOT_ALLOWED; case DATA_SETTING_SET_TO_MANUAL_CONNECTION: return ServiceStatus.ERROR_NO_AUTO_CONNECT; case BACKGROUND_CONNECTION_DISABLED: // TODO: define appropriate ServiceStatus return ServiceStatus.ERROR_COMMS; } return ServiceStatus.ERROR_COMMS; } private void setNewState(AgentState newState) { if (newState == mAgentState) { return; } LogUtils.logI("NetworkAgent.setNewState(): " + mAgentState + " -> " + newState); mAgentState = newState; if (newState == AgentState.CONNECTED) { - mDisconnectReason = AgentDisconnectReason.AGENT_IS_CONNECTED; + sDisconnectReason = AgentDisconnectReason.AGENT_IS_CONNECTED; onConnected(); } else if (newState == AgentState.DISCONNECTED) { onDisconnected(); } } private void onConnected() { checkActiveNetworkState(); if (mWorkerThreadControl != null) { mWorkerThreadControl.kickWorkerThread(); } if (mConnectionMgrIf != null) { mConnectionMgrIf.signalConnectionManager(true); } } private void onDisconnected() { // AA:need to kick it to make engines run and set the if (mWorkerThreadControl != null) { mWorkerThreadControl.kickWorkerThread(); } if (mConnectionMgrIf != null) { mConnectionMgrIf.signalConnectionManager(false); } } private void checkActiveNetworkState() { if (mConnectivityManager != null) { NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo == null) { LogUtils.logW("NetworkAgent.checkActiveNetworkInfoy() " + "mConnectivityManager.getActiveNetworkInfo() Returned null"); return; } else { if (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { LogUtils.logV("NetworkAgent.checkActiveNetworkInfoy() WIFI network"); // TODO: Do something } else if (mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { LogUtils.logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE and ROAMING"); // TODO: Do something // Only works when you are registering with network switch (mNetworkInfo.getSubtype()) { case TelephonyManager.NETWORK_TYPE_EDGE: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE EDGE network"); // TODO: Do something break; case TelephonyManager.NETWORK_TYPE_GPRS: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE GPRS network"); // TODO: Do something break; case TelephonyManager.NETWORK_TYPE_UMTS: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE UMTS network"); // TODO: Do something break; case TelephonyManager.NETWORK_TYPE_UNKNOWN: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE UNKNOWN network"); // TODO: Do something break; default: // Do nothing. break; } ; } } } else { LogUtils.logW("NetworkAgent.checkActiveNetworkInfoy() mConnectivityManager is null"); } } public void setNetworkAgentState(NetworkAgentState state) { LogUtils.logD("NetworkAgent.setNetworkAgentState() state[" + state + "]"); // TODO: make assignments if any changes boolean changes[] = state.getChanges(); if (changes[StatesOfService.IS_CONNECTED_TO_INTERNET.ordinal()]) mInternetConnected = state.isInternetConnected(); if (changes[StatesOfService.IS_NETWORK_WORKING.ordinal()]) mNetworkWorking = state.isNetworkWorking(); if (changes[StatesOfService.IS_ROAMING_ALLOWED.ordinal()]) mDataRoaming = state.isRoamingAllowed(); if (changes[StatesOfService.IS_INBACKGROUND.ordinal()]) mIsInBackground = state.isInBackGround(); if (changes[StatesOfService.IS_BG_CONNECTION_ALLOWED.ordinal()]) mBackgroundData = state.isBackDataAllowed(); if (changes[StatesOfService.IS_WIFI_ACTIVE.ordinal()]) mWifiNetworkAvailable = state.isWifiActive(); if (changes[StatesOfService.IS_ROAMING.ordinal()]) {// special case for // roaming mIsRoaming = state.isRoaming(); // This method sets the mAgentState, and mDisconnectReason as well // by calling setNewState(); onConnectionStateChanged(); processRoaming(null); } else // This method sets the mAgentState, and mDisconnectReason as well // by calling setNewState(); onConnectionStateChanged(); } public NetworkAgentState getNetworkAgentState() { NetworkAgentState state = new NetworkAgentState(); state.setRoaming(mIsRoaming); state.setRoamingAllowed(mDataRoaming); state.setBackgroundDataAllowed(mBackgroundData); state.setInBackGround(mIsInBackground); state.setInternetConnected(mInternetConnected); state.setNetworkWorking(mNetworkWorking); state.setWifiActive(mWifiNetworkAvailable); - state.setDisconnectReason(mDisconnectReason); + state.setDisconnectReason(sDisconnectReason); state.setAgentState(mAgentState); LogUtils.logD("NetworkAgent.getNetworkAgentState() state[" + state + "]"); return state; } // ///////////////////////////// // FOR TESTING PURPOSES ONLY // // ///////////////////////////// /** * Forces the AgentState to a specific value. * * @param newState the state to set Note: to be used only for test purposes */ public static void setAgentState(AgentState newState) { mAgentState = newState; } }
360/360-Engine-for-Android
39beaab4f95cb7c44a383768f84663be6f846338
Fix for PAND-2170. Error message depending on DisconnectReason
diff --git a/src/com/vodafone360/people/engine/contactsync/DownloadServerContacts.java b/src/com/vodafone360/people/engine/contactsync/DownloadServerContacts.java index d1c0a1f..d669bdb 100644 --- a/src/com/vodafone360/people/engine/contactsync/DownloadServerContacts.java +++ b/src/com/vodafone360/people/engine/contactsync/DownloadServerContacts.java @@ -1,831 +1,831 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import com.vodafone360.people.Settings; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ContactsTable; import com.vodafone360.people.database.tables.StateTable; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactChanges; import com.vodafone360.people.datatypes.ContactDetail; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.contactsync.SyncStatus.Task; import com.vodafone360.people.engine.contactsync.SyncStatus.TaskStatus; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Contacts; import com.vodafone360.people.utils.LogUtils; /** * Handles download of contacts from People server. */ public class DownloadServerContacts extends BaseSyncProcessor { /** * Helper constant for converting between milliseconds and nanoseconds. */ private static final long NANOSECONDS_IN_MS = 1000000L; /** * Enumeration which holds the various states for the download server * processor. */ public enum InternalState { INITIALISING, FETCHING_SERVER_ID_LIST, FETCHING_FIRST_PAGE, FETCHING_NEXT_BATCH } /** * The maximum number of contacts that should be sent by the server for each * page request. */ protected static final int MAX_DOWN_PAGE_SIZE = 25; /** * The number of pages that should be requested in a single RPG request * (using batching). */ private static final int MAX_PAGES_PER_BATCH = 1; /** * Maximum number of database updates for each engine run (to ensure the * processor doesn't block the worker thread for too long). */ private static final int MAX_CONTACT_CHANGES_PER_PAGE = 5; /** * Timeout between each run of the engine. Normally set to 0 to ensure the * engine will run as soon as possible. This is used to allow other engines * to be run between lengthy sync operations. */ private static final long TIMEOUT_BETWEEN_PAGES_MS = 0; /** * Set to true for extra logcat trace (debug only) */ private static final boolean EXTRA_DEBUG_TRACE = true; /** * This will be set to the current revision of the contacts in the NowPlus * database. For first time sync will be set to 0. The current revision * number is persisted in the database. */ private Integer mFromRevision = null; /** * The revision that we require from the server. For the first page this is * set to -1 to indicate we want the latest revision. For subsequent pages * will be set to the version anchor received from the server (to ensure all * pages fetched are for the same version). */ private Integer mToRevision = null; /** * Total number of pages we are expecting from the server. This is received * as part of the server response for the first page. */ private Integer mTotalNoOfPages = null; /** * First page number requested in the batch. The remaining page numbers will * follow from this sequentially. */ private int mBatchFirstPageNo; /** * Total number of pages requested by batch. */ private int mBatchNoOfPages; /** * Number of pages received so far from the batch */ private int mBatchPageReceivedCount; /** * Total number of pages done (used with {@link #mTotalNoOfPages} for * calculating progress) */ private int mNoOfPagesDone = 0; /*** * Number of contacts contained in the last page. This is only known once * the last page have been received and is a major flaw in the protocol as * it makes it difficult to calculate sync progress information. */ private int mLastPageSize = -1; /** * Set of contact server IDs from the NowPlus database. * Used to quickly determine if a contact received from the server is a new * or modified contact. */ private final HashSet<Long> mServerIdSet = new HashSet<Long>(); /** * List of all contacts received from server which are also present in the * local database. This is a list of all contacts received from the server * excluding new contacts. */ private final ArrayList<Contact> mContactsChangedList = new ArrayList<Contact>(); /** * List of all contacts received from the server that need to be added to * the database. */ private final ArrayList<Contact> mAddContactList = new ArrayList<Contact>(); /** * List of all contacts received from the server that need to be modified in * the database. */ private final ArrayList<Contact> mModifyContactList = new ArrayList<Contact>(); /** * List of all contacts received from the server that need to be deleted * from the database. */ private final ArrayList<ContactsTable.ContactIdInfo> mDeleteContactList = new ArrayList<ContactsTable.ContactIdInfo>(); /** * List of all contact details received from the server that need to be * added to the local database. */ private final ArrayList<ContactDetail> mAddDetailList = new ArrayList<ContactDetail>(); /** * List of all contact details received from the server that need to be * modified in the local database. */ private final ArrayList<ContactDetail> mModifyDetailList = new ArrayList<ContactDetail>(); /** * List of all contact details received from the server that need to be * deleted from the local database. */ private final ArrayList<ContactDetail> mDeleteDetailList = new ArrayList<ContactDetail>(); /** * Maintains all the request IDs when sending a batch of requests. */ protected final Map<Integer, Integer> mPageReqIds = new HashMap<Integer, Integer>(); /** * Flag indicating that there is some data in either the * {@link #mAddContactList}, {@link #mModifyContactList}, * {@link #mDeleteContactList}, {@link #mAddDetailList}, * {@link #mModifyDetailList} or {@link #mDeleteDetailList} list. */ private boolean mSyncDataPending = false; /** * Current internal state of the processor. */ protected InternalState mInternalState = InternalState.INITIALISING; /** * Used to monitor how much time is spent reading or writing to the NowPlus * database. This is for displaying logcat information which can be used * when profiling the contact sync engine. */ private long mDbSyncTime = 0; /** * Set to true when there are no more pages to fetch from the server. */ private boolean mIsComplete; /** * Counts the number of contacts added (for use when profiling) */ private long mTotalContactsAdded; /** * Processor constructor. * * @param callback Callback interface for accessing the contact sync engine. * @param db Database used for modifying contacts */ protected DownloadServerContacts(IContactSyncCallback callback, DatabaseHelper db) { super(callback, db); } /** * For debug only - to show when the garbage collector destroys the * processor */ @Override protected void finalize() { LogUtils.logD("DownloadServerContacts.finalize() - processor deleted"); } /** * Called by framework to start the processor running. Requests the first * page of contact changes from the server. */ @Override protected void doStart() { setSyncStatus(new SyncStatus(0, "", Task.DOWNLOAD_SERVER_CONTACTS)); mIsComplete = false; mSyncDataPending = false; mFromRevision = StateTable.fetchContactRevision(mDb.getReadableDatabase()); if (mFromRevision == null) { mFromRevision = 0; // Use base } mToRevision = -1; // Sync with head revision mTotalNoOfPages = null; mBatchNoOfPages = 1; mBatchFirstPageNo = 0; mBatchPageReceivedCount = 0; mDbSyncTime = 0; mNoOfPagesDone = 0; mTotalContactsAdded = 0; mInternalState = InternalState.FETCHING_SERVER_ID_LIST; long startTime = System.nanoTime(); ServiceStatus status = ContactsTable.fetchContactServerIdList(mServerIdSet, mDb.getReadableDatabase()); if (ServiceStatus.SUCCESS != status) { complete(status); } mDbSyncTime += (System.nanoTime() - startTime); setTimeout(TIMEOUT_BETWEEN_PAGES_MS); } /** * Requests first page of contact changes from the server. * * @return SUCCESS or a suitable error code. */ private ServiceStatus fetchFirstBatch() { if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - return ServiceStatus.ERROR_COMMS; + return NetworkAgent.getServiceStatusfromDisconnectReason(); } mInternalState = InternalState.FETCHING_FIRST_PAGE; LogUtils.logD("DownloadServerContacts.fetchFirstBatch - from rev " + mFromRevision + ", to rev " + mToRevision + ", page size " + MAX_DOWN_PAGE_SIZE); int reqId = Contacts.getContactsChanges(getEngine(), 0, MAX_DOWN_PAGE_SIZE, mFromRevision .longValue(), mToRevision.longValue(), false); setReqId(reqId); return ServiceStatus.SUCCESS; } /** * Requests the next batch of contact change pages from the server * * @return SUCCESS or a suitable error code */ private ServiceStatus fetchNextBatch() { mBatchNoOfPages = Math.min(mTotalNoOfPages - mBatchFirstPageNo, MAX_PAGES_PER_BATCH); if (mBatchNoOfPages == 0) { return ServiceStatus.SUCCESS; } mBatchPageReceivedCount = 0; if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - return ServiceStatus.ERROR_COMMS; + return NetworkAgent.getServiceStatusfromDisconnectReason(); } mPageReqIds.clear(); LogUtils.logD("DownloadServerContacts.fetchNextBatch - from rev " + mFromRevision + ", to rev " + mToRevision + ", page size " + MAX_DOWN_PAGE_SIZE); for (int i = 0; i < mBatchNoOfPages; i++) { int reqId = Contacts.getContactsChanges(getEngine(), i + mBatchFirstPageNo, MAX_DOWN_PAGE_SIZE, mFromRevision.longValue(), mToRevision.longValue(), true); mPageReqIds.put(reqId, i + mBatchFirstPageNo); } // AA: see if we can do that inside the Queue QueueManager.getInstance().fireQueueStateChanged(); return ServiceStatus.SUCCESS; } /** * Called by framework when contact sync is cancelled. Not used, the server * response will simply be ignored. */ @Override protected void doCancel() { LogUtils.logD("DownloadServerContacts.doCancel()"); } /** * Called by framework when a response is received from the server. In case * of the first page this will only be called if the request ID matches. * Processes the page and if the page is the last one in the batch, sends a * new batch of requests to the server. * * @param response from server */ @Override public void processCommsResponse(DecodedResponse resp) { Integer pageNo = 0; if (mInternalState == InternalState.FETCHING_NEXT_BATCH) { pageNo = mPageReqIds.remove(resp.mReqId); if (pageNo == null) { LogUtils.logD("DownloadServerContacts.processCommsResponse: Req ID not known"); return; } } LogUtils.logD("DownloadServerContacts.processCommsResponse() - Page " + pageNo); ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.CONTACT_CHANGES_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { ContactChanges contactChanges = (ContactChanges)resp.mDataTypes.get(0); LogUtils.logI("DownloadServerContacts.processCommsResponse - No of contacts = " + contactChanges.mContacts.size()); if (contactChanges.mContacts.size() == 0 && pageNo > 0) { LogUtils.logW("DownloadServerContacts.processCommsResponse - " + "Error a page with 0 contacts was received"); LogUtils.logW("DownloadServerContacts.processCommsResponse - Changes = " + contactChanges); } mBatchPageReceivedCount++; if (mBatchPageReceivedCount == mBatchNoOfPages) { mLastPageSize = contactChanges.mContacts.size(); // Page batch is now complete if (mInternalState == InternalState.FETCHING_FIRST_PAGE) { mTotalNoOfPages = contactChanges.mNumberOfPages; mToRevision = contactChanges.mVersionAnchor; mInternalState = InternalState.FETCHING_NEXT_BATCH; } mBatchFirstPageNo += mBatchNoOfPages; if (mTotalNoOfPages == null || mToRevision == null) { complete(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); return; } if (mBatchFirstPageNo < mTotalNoOfPages.intValue()) { status = fetchNextBatch(); if (ServiceStatus.SUCCESS != status) { complete(status); return; } } else { mIsComplete = true; } } status = syncContactChangesPage(contactChanges); mNoOfPagesDone++; LogUtils.logI("DownloadServerContacts.processCommsResponse() - Contact changes page " + mNoOfPagesDone + "/" + mTotalNoOfPages + " received, no of contacts = " + contactChanges.mContacts.size()); if (ServiceStatus.SUCCESS != status) { LogUtils.logE("DownloadServerContacts.processCommsResponse() - Error syncing page: " + status); complete(status); return; } if (mIsComplete && mContactsChangedList.size() == 0 && !mSyncDataPending) { downloadSyncSuccessful(); } return; } complete(status); } /*** * Check the given contact to see if it has a valid name, and if so send it * to be shown in the contacts sync progress UI. * * @param contact Contact which has been downloaded. * @param incOfCurrentPage Number of contacts that have so far been * downloaded for the current page. */ private void updateProgressUi(Contact contact, int incOfCurrentPage) { String name = ""; if (contact != null) { ContactDetail contactDetail = contact.getContactDetail(ContactDetail.DetailKeys.VCARD_NAME); if (contactDetail != null) { VCardHelper.Name vCardHelperName = contactDetail.getName(); if (vCardHelperName != null) { name = vCardHelperName.toString(); } } } int totalNumberOfContacts = ((mTotalNoOfPages*10)-1)*MAX_DOWN_PAGE_SIZE/10; if (mLastPageSize != -1) { totalNumberOfContacts = (mTotalNoOfPages-1) * MAX_DOWN_PAGE_SIZE + mLastPageSize; } int progress = (incOfCurrentPage + (mNoOfPagesDone * MAX_DOWN_PAGE_SIZE))*100 / totalNumberOfContacts; setSyncStatus(new SyncStatus(progress, name, Task.DOWNLOAD_SERVER_CONTACTS, TaskStatus.RECEIVED_CONTACTS, incOfCurrentPage + mNoOfPagesDone * MAX_DOWN_PAGE_SIZE, totalNumberOfContacts)); } /** * Processes the response from the server. First separates new contacts from * existing ones, this is to optimise adding new contacts during first time * sync. * * @param changes The contact change information received from the server * @return SUCCESS or a suitable error code */ private ServiceStatus syncContactChangesPage(ContactChanges changes) { mContactsChangedList.clear(); int i = 0; for (Contact contact : changes.mContacts) { i += 1; updateProgressUi(contact, i); if (Settings.ENABLED_CONTACTS_SYNC_TRACE) { if (contact.details.size() == 0 || contact.deleted != null) { LogUtils.logD("Contact In: " + contact.contactID + ", Del: " + contact.deleted + ", details: " + contact.details.size()); } for (ContactDetail detail : contact.details) { LogUtils.logD("Contact In: " + contact.contactID + ", Detail: " + detail.key + ", " + detail.unique_id + ", " + detail.keyType + " = " + detail.value + ", del = " + detail.deleted); } } if (mServerIdSet.contains(contact.contactID)) { mContactsChangedList.add(contact); } else { if (contact.deleted != null && contact.deleted.booleanValue()) { if (EXTRA_DEBUG_TRACE) { LogUtils.logD("DownloadServerContacts.syncDownContact() " + "Delete Contact (nothing to do) " + contact.contactID); } } else if (contact.details.size() > 0) { if (EXTRA_DEBUG_TRACE) { LogUtils.logD("DownloadServerContacts.syncDownContact() Adding " + contact.contactID); } mAddContactList.add(contact); mSyncDataPending = true; } else { if (EXTRA_DEBUG_TRACE) { LogUtils.logD("DownloadServerContacts.syncDownContact() Empty " + contact.contactID); } } } } if (mSyncDataPending || mContactsChangedList.size() > 0) { setTimeout(TIMEOUT_BETWEEN_PAGES_MS); } return ServiceStatus.SUCCESS; } /** * Processes next page of modified contacts in the * {@link #mContactsChangedList}. */ private void processContactChangesNextPage() { final int count = Math.min(mContactsChangedList.size(), MAX_CONTACT_CHANGES_PER_PAGE); for (int i = 0; i < count; i++) { final Contact srcContact = mContactsChangedList.get(0); mContactsChangedList.remove(0); final Contact destContact = new Contact(); long startTime = System.nanoTime(); ServiceStatus status = mDb.fetchContactByServerId(srcContact.contactID, destContact); if (ServiceStatus.SUCCESS != status) { LogUtils .logE("DownloadServerContacts.processContactChangesNextPage() - Error syncing page: " + status); complete(status); return; } mDbSyncTime += (System.nanoTime() - startTime); status = syncDownContact(srcContact, destContact); if (ServiceStatus.SUCCESS != status) { LogUtils .logE("DownloadServerContacts.processContactChangesNextPage() - Error syncing page: " + status); complete(status); return; } } if (mContactsChangedList.size() == 0 && !mSyncDataPending) { if (mIsComplete) { downloadSyncSuccessful(); } return; } setTimeout(TIMEOUT_BETWEEN_PAGES_MS); } /** * Modifies a contact from the NowPlus database to match the one received * from the server * * @param srcContact Contact received from the server * @param destContact Contact as stored in the database * @return SUCCESS or a suitable error code. */ private ServiceStatus syncDownContact(Contact srcContact, Contact destContact) { final long localContactId = destContact.localContactID; final Integer nativeContactId = destContact.nativeContactId; if (srcContact.deleted != null && srcContact.deleted.booleanValue()) { if (EXTRA_DEBUG_TRACE) { LogUtils.logD("DownloadServerContacts.syncDownContact - Deleting contact " + srcContact.contactID); } ContactsTable.ContactIdInfo idInfo = new ContactsTable.ContactIdInfo(); idInfo.localId = localContactId; idInfo.serverId = srcContact.contactID; idInfo.nativeId = nativeContactId; mDeleteContactList.add(idInfo); mSyncDataPending = true; return ServiceStatus.SUCCESS; } if (checkContactMods(srcContact, destContact)) { if (EXTRA_DEBUG_TRACE) { LogUtils.logD("DownloadServerContacts.syncDownContact - Modifying contact " + srcContact.contactID); } srcContact.localContactID = localContactId; srcContact.nativeContactId = nativeContactId; mModifyContactList.add(srcContact); mSyncDataPending = true; } if (srcContact.details == null) { if (EXTRA_DEBUG_TRACE) { LogUtils.logD("DownloadServerContacts.syncDownContact - No details changed " + srcContact.contactID); } return ServiceStatus.SUCCESS; } for (ContactDetail srcDetail : srcContact.details) { srcDetail.localContactID = localContactId; srcDetail.nativeContactId = nativeContactId; boolean detailFound = false; for (ContactDetail destDetail : destContact.details) { if (DatabaseHelper.doDetailsMatch(srcDetail, destDetail)) { detailFound = true; srcDetail.localDetailID = destDetail.localDetailID; srcDetail.nativeContactId = destDetail.nativeContactId; srcDetail.nativeDetailId = destDetail.nativeDetailId; srcDetail.serverContactId = srcContact.contactID; if (srcDetail.deleted != null && srcDetail.deleted.booleanValue()) { if (EXTRA_DEBUG_TRACE) { LogUtils .logD("DownloadServerContacts.syncDownContact - Deleting detail " + srcDetail.key + " contact ID = " + srcContact.contactID); } mDeleteDetailList.add(srcDetail); mSyncDataPending = true; } else if (DatabaseHelper.hasDetailChanged(destDetail, srcDetail)) { if (EXTRA_DEBUG_TRACE) { LogUtils .logD("DownloadServerContacts.syncDownContact - Modifying detail " + srcDetail.key + " local detail ID = " + srcDetail.localDetailID); } srcDetail.serverContactId = srcContact.contactID; mModifyDetailList.add(srcDetail); mSyncDataPending = true; } break; } } if (!detailFound) { if (srcDetail.deleted == null || !srcDetail.deleted.booleanValue()) { if (EXTRA_DEBUG_TRACE) { LogUtils .logD("DownloadServerContacts.syncDownContact - Adding detail " + srcDetail.key + " local contact ID = " + srcDetail.localContactID); } mAddDetailList.add(srcDetail); mSyncDataPending = true; } else { if (EXTRA_DEBUG_TRACE) { LogUtils .logD("DownloadServerContacts.syncDownContact - Detail already deleted (nothing to do) " + srcDetail.key + " local detail ID = " + srcDetail.localDetailID); } } } } return ServiceStatus.SUCCESS; } /** * Compares two contacts to check for any differences. Implemented to avoid * updating the database when nothing has changed (to improve performance). * * @param srcContact Contact received from the server * @param destContact Contact as it is in the database. * @return true if the contacts are different, false otherwise. */ private boolean checkContactMods(Contact srcContact, Contact destContact) { boolean contactModified = false; if (srcContact.friendOfMine != null && !srcContact.friendOfMine.equals(destContact.friendOfMine)) { destContact.friendOfMine = srcContact.friendOfMine; contactModified = true; } if (srcContact.gender != null && !srcContact.gender.equals(destContact.gender)) { destContact.gender = srcContact.gender; contactModified = true; } if (srcContact.sources != null) { boolean changed = false; if (srcContact.sources.size() != destContact.sources.size()) { changed = true; } else { for (int i = 0; i < srcContact.sources.size(); i++) { if (srcContact.sources.get(i) != null && !srcContact.sources.get(i).equals(destContact.sources.get(i))) { changed = true; } } } if (changed) { destContact.sources.clear(); destContact.sources.addAll(srcContact.sources); contactModified = true; } } if (srcContact.userID != null && !srcContact.userID.equals(destContact.userID)) { destContact.userID = srcContact.userID; contactModified = true; } if (srcContact.aboutMe != null && !srcContact.aboutMe.equals(destContact.aboutMe)) { destContact.aboutMe = srcContact.aboutMe; contactModified = true; } if (srcContact.groupList != null) { boolean changed = false; if (srcContact.groupList.size() != destContact.groupList.size()) { changed = true; } else { for (int i = 0; i < srcContact.groupList.size(); i++) { if (srcContact.groupList.get(i) != null && !srcContact.groupList.get(i).equals(destContact.groupList.get(i))) { changed = true; } } } if (changed) { destContact.groupList.clear(); destContact.groupList.addAll(srcContact.groupList); contactModified = true; } } if (srcContact.synctophone != null && !srcContact.synctophone.equals(destContact.synctophone)) { destContact.synctophone = srcContact.synctophone; contactModified = true; } return contactModified; } /** * Called by framework when a timeout expires. Timeouts are used by this * processor to break up lengthy database update tasks. A timeout of 0 is * normally used just to give other engines a chance to run. */ public void onTimeoutEvent() { switch (mInternalState) { case FETCHING_SERVER_ID_LIST: ServiceStatus status = fetchFirstBatch(); if (ServiceStatus.SUCCESS != status) { complete(status); return; } break; case FETCHING_FIRST_PAGE: case FETCHING_NEXT_BATCH: if (mContactsChangedList.size() > 0) { processContactChangesNextPage(); return; } if (mSyncDataPending) { if (addContactList()) { setTimeout(TIMEOUT_BETWEEN_PAGES_MS); return; } if (modifyContactList()) { setTimeout(TIMEOUT_BETWEEN_PAGES_MS); return; } if (deleteContactList()) { setTimeout(TIMEOUT_BETWEEN_PAGES_MS); return; } if (addDetailList()) { setTimeout(TIMEOUT_BETWEEN_PAGES_MS); return; } if (modifyDetailList()) { setTimeout(TIMEOUT_BETWEEN_PAGES_MS); return; } if (deleteDetailList()) { setTimeout(TIMEOUT_BETWEEN_PAGES_MS); return; } mSyncDataPending = false; if (mIsComplete) { downloadSyncSuccessful(); return; } } break; default: // do nothing. break; } } /** * Adds contacts received from the server (listed in the * {@link #mAddContactList} list) into the local database. * * @return true if > 0 contacts were added, false otherwise. */ private boolean addContactList() { if (mAddContactList.size() == 0) { return false; } LogUtils.logI("DownloadServerContacts.addContactList " + mAddContactList.size() + " contacts..."); long startTime = System.nanoTime(); ServiceStatus status = mDb.syncAddContactList(mAddContactList, false, true); if (ServiceStatus.SUCCESS != status) { complete(status); return true; } markDbChanged(); long timeDiff = System.nanoTime() - startTime; mDbSyncTime += timeDiff; LogUtils.logI("DownloadServerContacts.addContactList - time = " + (timeDiff / NANOSECONDS_IN_MS) + "ms, total = " + (mDbSyncTime / NANOSECONDS_IN_MS) + "ms"); setTimeout(TIMEOUT_BETWEEN_PAGES_MS); mTotalContactsAdded += mAddContactList.size(); mAddContactList.clear(); return true; } /** * Updates the local database with contacts received from the server (listed * in the {@link #mModifyContactList} list). * * @return true if > 0 contacts were modified, false otherwise. */ private boolean modifyContactList() { if (mModifyContactList.size() == 0) { return false; } LogUtils.logI("DownloadServerContacts.modifyContactList " + mModifyContactList.size() + " contacts..."); long startTime = System.nanoTime(); ServiceStatus status = mDb.syncModifyContactList(mModifyContactList, false, true); if (ServiceStatus.SUCCESS != status) { complete(status); return true; diff --git a/src/com/vodafone360/people/engine/contactsync/UploadServerContacts.java b/src/com/vodafone360/people/engine/contactsync/UploadServerContacts.java index 41ea014..547bb5e 100644 --- a/src/com/vodafone360/people/engine/contactsync/UploadServerContacts.java +++ b/src/com/vodafone360/people/engine/contactsync/UploadServerContacts.java @@ -1,1127 +1,1127 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import android.database.Cursor; import com.vodafone360.people.Settings; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.DatabaseHelper.ServerIdInfo; import com.vodafone360.people.database.tables.ContactChangeLogTable; import com.vodafone360.people.database.tables.ContactDetailsTable; import com.vodafone360.people.database.tables.ContactsTable; import com.vodafone360.people.database.tables.ContactChangeLogTable.ContactChangeInfo; import com.vodafone360.people.database.tables.ContactChangeLogTable.ContactChangeType; import com.vodafone360.people.database.tables.ContactsTable.ContactIdInfo; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactChanges; import com.vodafone360.people.datatypes.ContactDetail; import com.vodafone360.people.datatypes.ContactDetailDeletion; import com.vodafone360.people.datatypes.ContactListResponse; import com.vodafone360.people.datatypes.GroupItem; import com.vodafone360.people.datatypes.ItemList; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.contactsync.SyncStatus.Task; import com.vodafone360.people.engine.contactsync.SyncStatus.TaskStatus; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Contacts; import com.vodafone360.people.service.io.api.GroupPrivacy; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * Processor handling upload of contacts to the People server. */ public class UploadServerContacts extends BaseSyncProcessor { /** * Internal states supported by the processor. */ protected enum InternalState { /** Internal state when processing new contacts. **/ PROCESSING_NEW_CONTACTS, /** Internal state when processing modified details. **/ PROCESSING_MODIFIED_DETAILS, /** Internal state when processing deleted contacts. **/ PROCESSING_DELETED_CONTACTS, /** Internal state when processing deleted details. **/ PROCESSING_DELETED_DETAILS, /** Internal state when processing group additions. **/ PROCESSING_GROUP_ADDITIONS, /** Internal state when processing group deletions. **/ PROCESSING_GROUP_DELETIONS } /** * Maximum progress percentage value. */ private static final int MAX_PROGESS = 100; /** * Used for converting between nanoseconds and milliseconds. */ private static final long NANOSECONDS_IN_MS = 1000000L; /** * Maximum number of contacts to send to the server in a request. */ protected static final int MAX_UP_PAGE_SIZE = 25; /** * No of items which were sent in the current batch, used for updating the * progress bar once a particular call is complete. */ private long mNoOfItemsSent; /** * Total number of items which need to be sync'ed to the server (includes * all types of updates). Used for updating the progress. */ private int mTotalNoOfItems; /** * Total number of contacts sync'ed so far. */ private int mItemsDone; /** * Contains the next page of changes from the server change log. */ private final List<ContactChangeInfo> mContactChangeInfoList = new ArrayList<ContactChangeInfo>(); /** * Contains the next page of contacts being sent to the server which have * either been added or changed. */ private final List<Contact> mContactChangeList = new ArrayList<Contact>(); /** * Current internal state of the processor. */ private InternalState mInternalState; /** * Used for debug to monitor the database read/write time during a sync. */ private long mDbSyncTime = 0; /** * Cursor used for fetching new/modified contacts from the NowPlus database. */ private Cursor mContactsCursor; /** * List of server IDs which is sent to the server by the {@code * DeleteContacts} API. */ private final List<Long> mContactIdList = new ArrayList<Long>(); /** * Current list of groups being added to the contacts listed in the * {@link #mContactIdList}. Will only contain a single group (list is needed * for the * {@link GroupPrivacy#addContactGroupRelations(BaseEngine, List, List)} * API). */ private final List<GroupItem> mGroupList = new ArrayList<GroupItem>(); /** * Contains the main contact during the contact detail deletion process. */ private Contact mDeleteDetailContact = null; /** * Contains the server ID of the group being associated with a contact. */ private Long mActiveGroupId = null; /** * Processor constructor. * * @param callback Provides access to contact sync engine callback * functions. * @param db NowPlus Database needed for reading contact and group * information */ public UploadServerContacts(final IContactSyncCallback callback, final DatabaseHelper db) { super(callback, db); } /** * Called by framework to start the processor running. First sends all the * new contacts to the server. */ @Override protected final void doStart() { setSyncStatus(new SyncStatus(0, "", Task.UPDATE_SERVER_CONTACTS)); long startTime = System.nanoTime(); mTotalNoOfItems = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()) + ContactDetailsTable.syncServerFetchNoOfChanges(mDb.getReadableDatabase()); mDbSyncTime += (System.nanoTime() - startTime); mItemsDone = 0; startProcessNewContacts(); } /** * Sends the first page of new contacts to the server. */ private void startProcessNewContacts() { mInternalState = InternalState.PROCESSING_NEW_CONTACTS; long startTime = System.nanoTime(); mContactsCursor = ContactDetailsTable.syncServerFetchContactChanges(mDb .getReadableDatabase(), true); mDbSyncTime += (System.nanoTime() - startTime); if (mContactsCursor == null) { complete(ServiceStatus.ERROR_DATABASE_CORRUPT); } else { sendNextContactAdditionsPage(); } } /** * Sends the first page of contact modifications (includes new and modified * details) to the server. */ private void startProcessModifiedDetails() { mInternalState = InternalState.PROCESSING_MODIFIED_DETAILS; /** Cleanup unused objects **/ if (mContactsCursor != null) { mContactsCursor.close(); mContactsCursor = null; } long startTime = System.nanoTime(); mContactsCursor = ContactDetailsTable.syncServerFetchContactChanges(mDb .getReadableDatabase(), false); mDbSyncTime += (System.nanoTime() - startTime); sendNextDetailChangesPage(); } /** * Sends the first page of deleted contacts to the server. */ private void startProcessDeletedContacts() { mInternalState = InternalState.PROCESSING_DELETED_CONTACTS; /** Cleanup unused objects **/ mContactChangeList.clear(); if (mContactsCursor != null) { mContactsCursor.close(); mContactsCursor = null; } sendNextDeleteContactsPage(); } /** * Sends the deleted details of the first contact to the server. */ private void startProcessDeletedDetails() { mInternalState = InternalState.PROCESSING_DELETED_DETAILS; sendNextDeleteDetailsPage(); } /** * Sends the first contact/group relation addition request to the server. */ private void startProcessGroupAdditions() { mInternalState = InternalState.PROCESSING_GROUP_ADDITIONS; sendNextAddGroupRelationsPage(); } /** * Sends the first contact/group relation deletion request to the server. */ private void startProcessGroupDeletions() { mInternalState = InternalState.PROCESSING_GROUP_DELETIONS; sendNextDelGroupRelationsPage(); } /** * Sends the next page of new contacts to the server. */ private void sendNextContactAdditionsPage() { long startTime = System.nanoTime(); ContactDetailsTable.syncServerGetNextNewContactDetails(mContactsCursor, mContactChangeList, MAX_UP_PAGE_SIZE); mDbSyncTime += (System.nanoTime() - startTime); if (mContactChangeList.size() == 0) { moveToNextState(); return; } if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - complete(ServiceStatus.ERROR_COMMS); + complete(NetworkAgent.getServiceStatusfromDisconnectReason()); return; } /** Debug output. **/ if (Settings.ENABLED_CONTACTS_SYNC_TRACE) { LogUtils.logI("UploadServerContacts." + "sendNextContactAdditionsPage() New Contacts:"); for (Contact contact : mContactChangeList) { for (ContactDetail detail : contact.details) { LogUtils.logI("UploadServerContacts." + "sendNextContactAdditionsPage() Contact: " + contact.localContactID + ", Detail: " + detail.key + ", " + detail.keyType + " = " + detail.value); } } } /** End debug output. **/ mNoOfItemsSent = mContactChangeList.size(); setReqId(Contacts.bulkUpdateContacts(getEngine(), mContactChangeList)); } /** * Sends the next page of new/modified details to the server. */ private void sendNextDetailChangesPage() { mContactChangeList.clear(); long startTime = System.nanoTime(); ContactDetailsTable.syncServerGetNextNewContactDetails(mContactsCursor, mContactChangeList, MAX_UP_PAGE_SIZE); mDbSyncTime += (System.nanoTime() - startTime); if (mContactChangeList.size() == 0) { moveToNextState(); return; } /** Debug output. **/ if (Settings.ENABLED_CONTACTS_SYNC_TRACE) { LogUtils.logI("UploadServerContacts.sendNextDetailChangesPage() " + "Contact detail changes:"); for (Contact c : mContactChangeList) { for (ContactDetail d : c.details) { LogUtils.logI("UploadServerContacts." + "sendNextDetailChangesPage() Contact: " + c.contactID + ", Detail: " + d.key + ", " + d.unique_id + " = " + d.value); } } } /** End debug output. **/ if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - complete(ServiceStatus.ERROR_COMMS); + complete(NetworkAgent.getServiceStatusfromDisconnectReason()); return; } mNoOfItemsSent = mContactChangeList.size(); setReqId(Contacts.bulkUpdateContacts(getEngine(), mContactChangeList)); } /** * Sends the next page of deleted contacts to the server. */ private void sendNextDeleteContactsPage() { mContactChangeInfoList.clear(); long startTime = System.nanoTime(); if (!ContactChangeLogTable.fetchContactChangeLog(mContactChangeInfoList, ContactChangeType.DELETE_CONTACT, 0, MAX_UP_PAGE_SIZE, mDb.getReadableDatabase())) { LogUtils.logE("UploadServerContacts.sendNextDeleteContactsPage() " + "Unable to fetch contact changes from database"); complete(ServiceStatus.ERROR_DATABASE_CORRUPT); return; } mDbSyncTime += (System.nanoTime() - startTime); if (mContactChangeInfoList.size() == 0) { moveToNextState(); return; } mContactIdList.clear(); for (ContactChangeInfo info : mContactChangeInfoList) { if (info.mServerContactId != null) { mContactIdList.add(info.mServerContactId); } } if (mContactIdList.size() == 0) { startTime = System.nanoTime(); mDb.deleteContactChanges(mContactChangeInfoList); mDbSyncTime += (System.nanoTime() - startTime); moveToNextState(); return; } /** Debug output. **/ if (Settings.ENABLED_CONTACTS_SYNC_TRACE) { LogUtils.logI("UploadServerContacts.sendNextDeleteContactsPage() " + "Contacts deleted:"); for (Long id : mContactIdList) { LogUtils.logI("UploadServerContacts." + "sendNextDeleteContactsPage() Contact Id: " + id); } } /** Debug output. **/ if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - complete(ServiceStatus.ERROR_COMMS); + complete(NetworkAgent.getServiceStatusfromDisconnectReason()); return; } mNoOfItemsSent = mContactIdList.size(); setReqId(Contacts.deleteContacts(getEngine(), mContactIdList)); } /** * Sends the next deleted details to the server. This has to be done one * contact at a time. */ private void sendNextDeleteDetailsPage() { mContactChangeInfoList.clear(); long startTime = System.nanoTime(); List<ContactChangeInfo> groupInfoList = new ArrayList<ContactChangeInfo>(); if (!ContactChangeLogTable.fetchContactChangeLog(groupInfoList, ContactChangeType.DELETE_DETAIL, 0, MAX_UP_PAGE_SIZE, mDb.getReadableDatabase())) { LogUtils.logE("UploadServerContacts.sendNextDeleteDetailsPage() " + "Unable to fetch contact changes from database"); complete(ServiceStatus.ERROR_DATABASE_CORRUPT); return; } mDbSyncTime += (System.nanoTime() - startTime); if (groupInfoList.size() == 0) { moveToNextState(); return; } mDeleteDetailContact = new Contact(); List<ContactChangeInfo> deleteInfoList = new ArrayList<ContactChangeInfo>(); int i = 0; for (i = 0; i < groupInfoList.size(); i++) { ContactChangeInfo info = groupInfoList.get(i); if (info.mServerContactId == null) { info.mServerContactId = mDb.fetchServerId(info.mLocalContactId); } if (info.mServerContactId != null) { mDeleteDetailContact.localContactID = info.mLocalContactId; mDeleteDetailContact.contactID = info.mServerContactId; break; } deleteInfoList.add(info); info.mLocalContactId = null; } mDb.deleteContactChanges(deleteInfoList); if (mDeleteDetailContact.contactID == null) { moveToNextState(); return; } mContactChangeInfoList.clear(); for (; i < groupInfoList.size(); i++) { ContactChangeInfo info = groupInfoList.get(i); if (info.mLocalContactId != null && info.mLocalContactId.equals(mDeleteDetailContact.localContactID)) { final ContactDetail detail = new ContactDetail(); detail.localDetailID = info.mLocalDetailId; detail.key = info.mServerDetailKey; detail.unique_id = info.mServerDetailId; mDeleteDetailContact.details.add(detail); mContactChangeInfoList.add(info); } } /** Debug output. **/ if (Settings.ENABLED_CONTACTS_SYNC_TRACE) { LogUtils.logI("UploadServerContacts.sendNextDeleteDetailsPage() " + "Contact details for deleting:"); for (ContactDetail detail : mDeleteDetailContact.details) { LogUtils.logI("UploadServerContacts." + "sendNextDeleteDetailsPage() Contact ID: " + mDeleteDetailContact.contactID + ", detail = " + detail.key + ", unique_id = " + detail.unique_id); } } /** Debug output. **/ if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - complete(ServiceStatus.ERROR_COMMS); + complete(NetworkAgent.getServiceStatusfromDisconnectReason()); return; } mNoOfItemsSent = mDeleteDetailContact.details.size(); setReqId(Contacts.deleteContactDetails(getEngine(), mDeleteDetailContact.contactID, mDeleteDetailContact.details)); } /** * Sends next add contact/group relation request to the server. Many * contacts can be added by a single request. */ private void sendNextAddGroupRelationsPage() { ContactChangeInfo info = null; mActiveGroupId = null; mContactIdList.clear(); mContactChangeInfoList.clear(); List<ContactChangeInfo> groupInfoList = new ArrayList<ContactChangeInfo>(); long startTime = System.nanoTime(); if (!ContactChangeLogTable.fetchContactChangeLog(groupInfoList, ContactChangeType.ADD_GROUP_REL, 0, MAX_UP_PAGE_SIZE, mDb.getReadableDatabase())) { LogUtils.logE("UploadServerContacts." + "sendNextAddGroupRelationsPage() Unable to fetch add " + "group relations from database"); complete(ServiceStatus.ERROR_DATABASE_CORRUPT); return; } mDbSyncTime += (System.nanoTime() - startTime); if (groupInfoList.size() == 0) { moveToNextState(); return; } mContactChangeInfoList.clear(); List<ContactChangeInfo> deleteInfoList = new ArrayList<ContactChangeInfo>(); for (int i = 0; i < groupInfoList.size(); i++) { info = groupInfoList.get(i); if (info.mServerContactId == null) { info.mServerContactId = mDb.fetchServerId(info.mLocalContactId); } if (info.mServerContactId != null && info.mGroupOrRelId != null) { if (mActiveGroupId == null) { mActiveGroupId = info.mGroupOrRelId; } if (info.mGroupOrRelId.equals(mActiveGroupId)) { mContactIdList.add(info.mServerContactId); mContactChangeInfoList.add(info); } continue; } LogUtils.logE("UploadServerContact.sendNextAddGroupRelationsPage() " + "Invalid add group change: SID = " + info.mServerContactId + ", gid=" + info.mGroupOrRelId); deleteInfoList.add(info); } mDb.deleteContactChanges(deleteInfoList); if (mActiveGroupId == null) { moveToNextState(); return; } mGroupList.clear(); GroupItem group = new GroupItem(); group.mId = mActiveGroupId; mGroupList.add(group); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - complete(ServiceStatus.ERROR_COMMS); + complete(NetworkAgent.getServiceStatusfromDisconnectReason()); return; } mNoOfItemsSent = mGroupList.size(); setReqId(GroupPrivacy.addContactGroupRelations(getEngine(), mContactIdList, mGroupList)); } /** * Sends next delete contact/group relation request to the server. */ private void sendNextDelGroupRelationsPage() { ContactChangeInfo info = null; mActiveGroupId = null; mContactChangeInfoList.clear(); List<ContactChangeInfo> groupInfoList = new ArrayList<ContactChangeInfo>(); long startTime = System.nanoTime(); if (!ContactChangeLogTable.fetchContactChangeLog(groupInfoList, ContactChangeType.DELETE_GROUP_REL, 0, MAX_UP_PAGE_SIZE, mDb.getReadableDatabase())) { LogUtils.logE("UploadServerContacts." + "sendNextDelGroupRelationsPage() Unable to fetch delete " + "group relations from database"); complete(ServiceStatus.ERROR_DATABASE_CORRUPT); return; } mDbSyncTime += (System.nanoTime() - startTime); if (groupInfoList.size() == 0) { moveToNextState(); return; } mContactChangeInfoList.clear(); List<ContactChangeInfo> deleteInfoList = new ArrayList<ContactChangeInfo>(); for (int i = 0; i < groupInfoList.size(); i++) { info = groupInfoList.get(i); if (info.mServerContactId == null) { info.mServerContactId = mDb.fetchServerId(info.mLocalContactId); } if (info.mServerContactId != null && info.mGroupOrRelId != null) { if (mActiveGroupId == null) { mActiveGroupId = info.mGroupOrRelId; } if (mActiveGroupId.equals(info.mGroupOrRelId)) { mContactIdList.add(info.mServerContactId); mContactChangeInfoList.add(info); } continue; } LogUtils.logE("UploadServerContact.sendNextDelGroupRelationsPage() " + "Invalid delete group change: SID = " + info.mServerContactId + ", gid=" + info.mGroupOrRelId); deleteInfoList.add(info); } mDb.deleteContactChanges(deleteInfoList); if (mActiveGroupId == null) { moveToNextState(); return; } if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - complete(ServiceStatus.ERROR_COMMS); + complete(NetworkAgent.getServiceStatusfromDisconnectReason()); return; } mNoOfItemsSent = mContactIdList.size(); setReqId(GroupPrivacy.deleteContactGroupRelationsExt(getEngine(), mActiveGroupId, mContactIdList)); } /** * Changes the state of the processor to the next internal state. Is called * when the current state has finished. */ private void moveToNextState() { switch (mInternalState) { case PROCESSING_NEW_CONTACTS: startProcessModifiedDetails(); break; case PROCESSING_MODIFIED_DETAILS: startProcessDeletedContacts(); break; case PROCESSING_DELETED_CONTACTS: startProcessDeletedDetails(); break; case PROCESSING_DELETED_DETAILS: startProcessGroupAdditions(); break; case PROCESSING_GROUP_ADDITIONS: startProcessGroupDeletions(); break; case PROCESSING_GROUP_DELETIONS: LogUtils.logV("UploadServerContacts.moveToNextState() " + "Total DB access time = " + (mDbSyncTime / NANOSECONDS_IN_MS) + "ms, no of changes = " + mTotalNoOfItems); complete(ServiceStatus.SUCCESS); break; default: complete(ServiceStatus.ERROR_NOT_READY); break; } } /** * Called by framework to cancel contact sync. No implementation required, * the server response will be ignored and the contact sync will be repeated * if necessary. */ @Override protected void doCancel() { // Do nothing. } /** * Called by framework when a response to a server request is received. * Processes response based on the current internal state. * * @param resp Response data */ @Override public final void processCommsResponse(final DecodedResponse resp) { switch (mInternalState) { case PROCESSING_NEW_CONTACTS: processNewContactsResp(resp); break; case PROCESSING_MODIFIED_DETAILS: processModifiedDetailsResp(resp); break; case PROCESSING_DELETED_CONTACTS: processDeletedContactsResp(resp); break; case PROCESSING_DELETED_DETAILS: processDeletedDetailsResp(resp); break; case PROCESSING_GROUP_ADDITIONS: processGroupAdditionsResp(resp); break; case PROCESSING_GROUP_DELETIONS: processGroupDeletionsResp(resp); break; default: // Do nothing. break; } } /** * Called when a server response is received during a new contact sync. The * server ID, user ID and contact detail unique IDs are extracted from the * response and the NowPlus database updated. Possibly server errors are * also handled. * * @param resp Response from server. */ private void processNewContactsResp(final DecodedResponse resp) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.CONTACT_CHANGES_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { ContactChanges contactChanges = (ContactChanges)resp.mDataTypes.get(0); ListIterator<Contact> itContactSrc = contactChanges.mContacts.listIterator(); ListIterator<Contact> itContactDest = mContactChangeList.listIterator(); List<ServerIdInfo> contactServerIdList = new ArrayList<ServerIdInfo>(); List<ServerIdInfo> detailServerIdList = new ArrayList<ServerIdInfo>(); while (itContactSrc.hasNext()) { if (!itContactDest.hasNext()) { /** * The response should contain the same number of contacts * as was supplied but must handle the error. */ status = ServiceStatus.ERROR_COMMS_BAD_RESPONSE; break; } Contact contactSrc = itContactSrc.next(); Contact contactDest = itContactDest.next(); if (Settings.ENABLED_CONTACTS_SYNC_TRACE) { String name = null; String sns = null; for (ContactDetail detail : contactDest.details) { if (detail.key == ContactDetail.DetailKeys.VCARD_NAME) { if (detail.value != null) { VCardHelper.Name nameObj = detail.getName(); if (nameObj != null) { name = nameObj.toString(); } } } if (detail.key == ContactDetail.DetailKeys.VCARD_INTERNET_ADDRESS) { sns = detail.alt; } } LogUtils.logV("UploadServerContacts." + "processNewContactsResp() Contact uploaded: SID" + " = " + contactSrc.contactID + ", name = " + name + ", sns = " + sns + ", no of details = " + contactDest.details.size() + ", deleted=" + contactSrc.deleted); } if (contactSrc.contactID != null && contactSrc.contactID.longValue() != -1L) { if (contactDest.contactID == null || !contactDest.contactID.equals(contactSrc.contactID)) { ServerIdInfo info = new ServerIdInfo(); info.localId = contactDest.localContactID; info.serverId = contactSrc.contactID; info.userId = contactSrc.userID; contactServerIdList.add(info); } } else { LogUtils.logE("UploadServerContacts." + "processNewContactsResp() The server failed to " + "add the following contact: " + contactDest.localContactID + ", server ID = " + contactDest.contactID); mFailureList += "Failed to add contact: " + contactDest.localContactID + "\n"; for (ContactDetail d : contactDest.details) { LogUtils.logV("Failed Contact Info: " + contactDest.localContactID + ", Detail: " + d.key + ", " + d.keyType + " = " + d.value); } } status = handleUploadDetailChanges(contactSrc, contactDest, detailServerIdList); } if (status != ServiceStatus.SUCCESS) { /** Something is going wrong - cancel the update **/ complete(status); return; } long startTime = System.nanoTime(); List<ContactIdInfo> dupList = new ArrayList<ContactIdInfo>(); status = ContactsTable.syncSetServerIds(contactServerIdList, dupList, mDb .getWritableDatabase()); if (status != ServiceStatus.SUCCESS) { complete(status); return; } status = ContactDetailsTable.syncSetServerIds(detailServerIdList, mDb .getWritableDatabase()); if (status != ServiceStatus.SUCCESS) { complete(status); return; } if (dupList.size() > 0) { LogUtils.logV("UploadServerContacts.processNewContactsResp() Found " +dupList.size()+ " duplicate contacts. Trying to remove them..."); if(VersionUtils.is2XPlatform()) { // This is a very important distinction for 2.X devices! // the NAB IDs from the contacts we first import are stripped away // So we won't have the correct ID if syncMergeContactList() is executed // This is critical because a chain reaction will cause a Contact Delete in the end // Instead we can syncDeleteContactList() which should be safe on 2.X! status = mDb.syncDeleteContactList(dupList, false, true); } else { status = mDb.syncMergeContactList(dupList); } if (status != ServiceStatus.SUCCESS) { complete(status); return; } markDbChanged(); } mDbSyncTime += (System.nanoTime() - startTime); while (itContactDest.hasNext()) { Contact contactDest = itContactDest.next(); LogUtils.logE("UploadServerContacts.processNewContactsResp() " + "The server failed to add the following contact (not " + "included in returned list): " + contactDest.localContactID); mFailureList += "Failed to add contact (missing from return " + "list): " + contactDest.localContactID + "\n"; } updateProgress(); sendNextContactAdditionsPage(); return; } complete(status); } /** * Called when a server response is received during a modified contact sync. * The server ID, user ID and contact detail unique IDs are extracted from * the response and the NowPlus database updated if necessary. Possibly * server errors are also handled. * * @param resp Response from server. */ private void processModifiedDetailsResp(final DecodedResponse resp) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.CONTACT_CHANGES_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { ContactChanges contactChanges = (ContactChanges)resp.mDataTypes.get(0); ListIterator<Contact> itContactSrc = contactChanges.mContacts.listIterator(); ListIterator<Contact> itContactDest = mContactChangeList.listIterator(); List<ServerIdInfo> detailServerIdList = new ArrayList<ServerIdInfo>(); while (itContactSrc.hasNext()) { if (!itContactDest.hasNext()) { /* * The response should contain the same number of contacts * as was supplied but must handle the error. */ status = ServiceStatus.ERROR_COMMS_BAD_RESPONSE; break; } status = handleUploadDetailChanges(itContactSrc.next(), itContactDest.next(), detailServerIdList); } if (status != ServiceStatus.SUCCESS) { /** Something is going wrong - cancel the update. **/ complete(status); return; } long startTime = System.nanoTime(); status = ContactDetailsTable.syncSetServerIds(detailServerIdList, mDb .getWritableDatabase()); if (status != ServiceStatus.SUCCESS) { complete(status); return; } mDb.deleteContactChanges(mContactChangeInfoList); mDbSyncTime += (System.nanoTime() - startTime); mContactChangeInfoList.clear(); updateProgress(); sendNextDetailChangesPage(); return; } LogUtils.logE("UploadServerContacts.processModifiedDetailsResp() " + "Error requesting contact changes, error = " + status); complete(status); } /** * Called when a server response is received during a deleted contact sync. * The server change log is updated. Possibly server errors are also * handled. * * @param resp Response from server. */ private void processDeletedContactsResp(final DecodedResponse resp) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.CONTACT_LIST_RESPONSE_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { ContactListResponse result = (ContactListResponse)resp.mDataTypes.get(0); ListIterator<ContactChangeInfo> infoIt = mContactChangeInfoList.listIterator(); for (Integer contactID : result.mContactIdList) { if (!infoIt.hasNext()) { complete(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); return; } ContactChangeInfo info = infoIt.next(); if (contactID == null || contactID.intValue() == -1) { LogUtils.logE("UploadServerContacts." + "processDeletedContactsResp() The server failed " + "to delete the following contact: LocalId = " + info.mLocalContactId + ", ServerId = " + info.mServerContactId); mFailureList += "Failed to delete contact: " + info.mLocalContactId + "\n"; } } long startTime = System.nanoTime(); mDb.deleteContactChanges(mContactChangeInfoList); mDbSyncTime += (System.nanoTime() - startTime); mContactChangeInfoList.clear(); updateProgress(); sendNextDeleteContactsPage(); return; } LogUtils.logE("UploadServerContacts.processModifiedDetailsResp() " + "Error requesting contact changes, error = " + status); complete(status); } /** * Called when a server response is received during a deleted contact detail * sync. The server change log is updated. Possibly server errors are also * handled. * * @param resp Response from server. */ private void processDeletedDetailsResp(final DecodedResponse resp) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.CONTACT_DETAIL_DELETION_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { ContactDetailDeletion result = (ContactDetailDeletion)resp.mDataTypes.get(0); if (result.mDetails != null) { LogUtils.logV("UploadServerContacts." + "processDeletedDetailsResp() Deleted details " + result.mDetails.size()); } ListIterator<ContactChangeInfo> infoIt = mContactChangeInfoList.listIterator(); if (result.mContactId == null || result.mContactId == -1) { boolean first = true; while (infoIt.hasNext()) { ContactChangeInfo info = infoIt.next(); if (first) { first = false; LogUtils.logE("UploadServerContacts." + "processDeletedDetailsResp() The server " + "failed to delete detail from the following " + "contact: LocalId = " + info.mLocalContactId + ", ServerId = " + info.mServerContactId); } mFailureList += "Failed to delete detail: " + info.mLocalDetailId + "\n"; } } else if (result.mDetails != null) { for (ContactDetail d : result.mDetails) { if (!infoIt.hasNext()) { complete(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); return; } ContactChangeInfo info = infoIt.next(); if (!d.key.equals(info.mServerDetailKey)) { LogUtils.logE("UploadServerContacts." + "processDeletedDetailsResp() The server " + "failed to delete the following detail: " + "LocalId = " + info.mLocalContactId + ", " + "ServerId = " + info.mServerContactId + ", key = " + info.mServerDetailKey + ", detail ID = " + info.mServerDetailId); mFailureList += "Failed to delete detail: " + info.mLocalDetailId + "\n"; } } } long startTime = System.nanoTime(); mDb.deleteContactChanges(mContactChangeInfoList); mDbSyncTime += (System.nanoTime() - startTime); mContactChangeInfoList.clear(); updateProgress(); sendNextDeleteDetailsPage(); return; } LogUtils.logE("UploadServerContacts.processModifiedDetailsResp() " + "Error requesting contact changes, error = " + status); complete(status); } /** * Called when a server response is received during a group/contact add * relation sync. The server change log is updated. Possibly server errors * are also handled. * * @param resp Response from server. */ private void processGroupAdditionsResp(final DecodedResponse resp) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.ITEM_LIST_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { if (resp.mDataTypes.size() == 0) { LogUtils.logE("UploadServerContacts." + "processGroupAdditionsResp() " + "Item list cannot be empty"); complete(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); return; } ItemList itemList = (ItemList)resp.mDataTypes.get(0); if (itemList.mItemList == null) { LogUtils.logE("UploadServerContacts." + "processGroupAdditionsResp() " + "Item list cannot be NULL"); complete(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); return; } // TODO: Check response long startTime = System.nanoTime(); mDb.deleteContactChanges(mContactChangeInfoList); mDbSyncTime += (System.nanoTime() - startTime); mContactChangeInfoList.clear(); updateProgress(); sendNextAddGroupRelationsPage(); return; } LogUtils.logE("UploadServerContacts.processGroupAdditionsResp() " + "Error adding group relations, error = " + status); complete(status); } /** * Called when a server response is received during a group/contact delete * relation sync. The server change log is updated. Possibly server errors * are also handled. * * @param resp Response from server. */ private void processGroupDeletionsResp(final DecodedResponse resp) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { if (resp.mDataTypes.size() == 0) { LogUtils.logE("UploadServerContacts." + "processGroupDeletionsResp() " + "Response cannot be empty"); complete(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); return; } StatusMsg result = (StatusMsg)resp.mDataTypes.get(0); if (!result.mStatus.booleanValue()) { LogUtils.logE("UploadServerContacts." + "processGroupDeletionsResp() Error deleting group " + "relation, error = " + result.mError); complete(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); } LogUtils.logV("UploadServerContacts." + "processGroupDeletionsResp() Deleted relation"); long startTime = System.nanoTime(); mDb.deleteContactChanges(mContactChangeInfoList); mDbSyncTime += (System.nanoTime() - startTime); mContactChangeInfoList.clear(); updateProgress(); sendNextDelGroupRelationsPage(); return; } LogUtils.logE("UploadServerContacts.processGroupDeletionsResp() " + "Error deleting group relation, error = " + status); complete(status); } /** * Called when handling the server response from a new contact or modify * contact sync. Updates the unique IDs for all the details if necessary. * * @param contactSrc Contact received from server. * @param contactDest Contact from database. * @param detailServerIdList List of contact details with updated unique id. * @return ServiceStatus object. */ private ServiceStatus handleUploadDetailChanges(final Contact contactSrc, final Contact contactDest, final List<ServerIdInfo> detailServerIdList) { if (contactSrc.contactID == null || contactSrc.contactID.longValue() == -1L) { LogUtils.logE("UploadServerContacts.handleUploadDetailChanges() " + "The server failed to modify the following contact: " + contactDest.localContactID); mFailureList += "Failed to add contact: " + contactDest.localContactID + "\n"; return ServiceStatus.SUCCESS; } ListIterator<ContactDetail> itContactDetailSrc = contactSrc.details.listIterator(); ListIterator<ContactDetail> itContactDetailDest = contactDest.details.listIterator(); while (itContactDetailSrc.hasNext()) { if (!itContactDetailDest.hasNext()) { /* * The response should contain the same number of details as was * supplied but must handle the error. */ return ServiceStatus.ERROR_COMMS_BAD_RESPONSE; } ContactDetail contactDetailSrc = itContactDetailSrc.next(); ContactDetail contactDetailDest = itContactDetailDest.next(); ServerIdInfo info = new ServerIdInfo(); info.localId = contactDetailDest.localDetailID; if (contactDetailSrc.unique_id != null && contactDetailSrc.unique_id.longValue() == -1L) { LogUtils.logE("UploadServerContacts." + "handleUploadDetailChanges() The server failed to " + "modify the following contact detail: LocalDetailId " + "= " + contactDetailDest.localDetailID + ", Key = " + contactDetailDest.key + ", value = " + contactDetailDest.value); mFailureList += "Failed to modify contact detail: " + contactDetailDest.localDetailID + ", for contact " + contactDetailDest.localContactID + "\n"; info.serverId = null; } else { info.serverId = contactDetailSrc.unique_id; } diff --git a/src/com/vodafone360/people/engine/login/LoginEngine.java b/src/com/vodafone360/people/engine/login/LoginEngine.java index b01c080..267ffe9 100644 --- a/src/com/vodafone360/people/engine/login/LoginEngine.java +++ b/src/com/vodafone360/people/engine/login/LoginEngine.java @@ -192,1210 +192,1211 @@ public class LoginEngine extends BaseEngine { */ private final ArrayList<ILoginEventsListener> mEventsListener = new ArrayList<ILoginEventsListener>(); /** * Determines if the user is currently logged in with a valid session */ private boolean mCurrentLoginState = false; /** * Listener interface that can be used by clients to receive login state * events from the engine. */ public static interface ILoginEventsListener { void onLoginStateChanged(boolean loggedIn); } /** * Public constructor. * * @param context The service Context * @param eventCallback Provides access to useful engine manager * functionality * @param db The Now+ database used for fetching/storing login state * information */ public LoginEngine(Context context, IEngineEventCallback eventCallback, DatabaseHelper db) { super(eventCallback); LogUtils.logD("LoginEngine.LoginEngine()"); mContext = context; mTelephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); mDb = db; mEngineId = EngineId.LOGIN_ENGINE; } /** * This will be called immediately after creation to perform extra * initialisation. */ @Override public void onCreate() { LogUtils.logD("LoginEngine.OnCreate()"); mState = State.NOT_INITIALISED; mCurrentSubscriberId = mTelephonyManager.getSubscriberId(); IntentFilter filter = new IntentFilter(SmsBroadcastReceiver.ACTION_ACTIVATION_CODE); mContext.registerReceiver(mEventReceiver, filter); mIsRegistrationComplete = StateTable.isRegistrationComplete(mDb.getReadableDatabase()); } /** * This will be called just before the engine is shutdown. Cleans up any * resources used. */ @Override public void onDestroy() { LogUtils.logD("LoginEngine.onDestroy()"); // Intent intent = new Intent(); // intent.setAction(Intents.HIDE_LOGIN_NOTIFICATION); // mContext.sendBroadcast(intent); removeAllListeners(); mContext.unregisterReceiver(mEventReceiver); } /** * Called by the INowPlusService implementation to start a manual login. * Adds a manual login UI request to the queue and kicks the worker thread. * * @param loginDetails The login information entered by the user */ public void addUiLoginRequest(LoginDetails loginDetails) { LogUtils.logD("LoginEngine.addUiLoginRequest()"); addUiRequestToQueue(ServiceUiRequest.LOGIN, loginDetails); } /** * Called by the INowPlusService implementation to remove user data Issues a * UI request to effectively log out. */ public void addUiRemoveUserDataRequest() { LogUtils.logD("LoginEngine.addUiRemoveUserDataRequest()"); addUiRequestToQueue(ServiceUiRequest.REMOVE_USER_DATA, null); } /** * Called by the INowPlusService implementation to start the sign-up * process. Adds a registration UI request to the queue and kicks the worker * thread. * * @param details The registration details entered by the user */ public void addUiRegistrationRequest(RegistrationDetails details) { LogUtils.logD("LoginEngine.addUiRegistrationRequest()"); addUiRequestToQueue(ServiceUiRequest.REGISTRATION, details); } /** * Called by the INowPlusService implementation to fetch terms of service * text for the UI. Adds a fetch terms of service UI request to the queue * and kicks the worker thread. */ public void addUiFetchTermsOfServiceRequest() { LogUtils.logD("LoginEngine.addUiFetchTermsOfServiceRequest()"); addUiRequestToQueue(ServiceUiRequest.FETCH_TERMS_OF_SERVICE, null); } /** * Called by the INowPlusService implementation to privacy statement for the * UI. Adds a fetch privacy statement UI request to the queue and kicks the * worker thread. */ public void addUiFetchPrivacyStatementRequest() { LogUtils.logD("LoginEngine.addUiFetchPrivacyStatementRequest()"); addUiRequestToQueue(ServiceUiRequest.FETCH_PRIVACY_STATEMENT, null); } /** * Called by the INowPlusService implementation to check if a username is * available for registration. Adds a get username state UI request to the * queue and kicks the worker thread. * * @param username Username to fetch the state of * TODO: Not currently used by UI. */ public void addUiGetUsernameStateRequest(String username) { LogUtils.logD("LoginEngine.addUiGetUsernameStateRequest()"); addUiRequestToQueue(ServiceUiRequest.USERNAME_AVAILABILITY, username); } /** * Return the absolute time in milliseconds when the engine needs to run * (based on System.currentTimeMillis). * * @return -1 never needs to run, 0 needs to run as soon as possible, * CurrentTime + 60000 to run in 1 minute, etc. */ @Override public long getNextRunTime() { if (isCommsResponseOutstanding()) { return 0; } if (uiRequestReady()) { return 0; } switch (mState) { case NOT_INITIALISED: return 0; case NOT_REGISTERED: case LOGGED_ON: case LOGIN_FAILED: case LOGIN_FAILED_WRONG_CREDENTIALS: return -1; case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: if (mActivationCode != null) { return 0; } break; case LOGGED_OFF: return 0; case LOGGED_OFF_WAITING_FOR_NETWORK: if (NetworkAgent.getAgentState() == AgentState.CONNECTED) { return 0; } break; case RETRIEVING_PUBLIC_KEY: return 0; default: // Do nothing. break; } return getCurrentTimeout(); } /** * Do some work but anything that takes longer than 1 second must be broken * up. The type of work done includes: * <ul> * <li>If a comms response from server is outstanding, process it</li> * <li>If a timeout is pending, process it</li> * <li>If an SMS activation code has been received, process it</li> * <li>Retry auto login if necessary</li> * </ul> */ @Override public void run() { LogUtils.logD("LoginEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { return; } if (processTimeout()) { return; } switch (mState) { case NOT_INITIALISED: initialiseEngine(); return; case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: if (mActivationCode != null) { handleSmsResponse(); return; } break; case RETRIEVING_PUBLIC_KEY: break; case LOGGED_OFF: case LOGGED_OFF_WAITING_FOR_NETWORK: AuthSessionHolder session = StateTable.fetchSession(mDb.getReadableDatabase()); // if session is null we try to login automatically again if (null == session) { if (retryAutoLogin()) { return; } } else { // otherwise we try to reuse the session sActivatedSession = session; newState(State.LOGGED_ON); } default: // do nothing. break; } if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { if (!isUiRequestOutstanding()) { return false; } switch (mState) { case NOT_REGISTERED: case LOGGED_OFF: case LOGGED_ON: case LOGIN_FAILED: case CREATING_SESSION_AUTO: case LOGIN_FAILED_WRONG_CREDENTIALS: case LOGGED_OFF_WAITING_FOR_RETRY: return true; default: return false; } } /** * Determines if the user is currently logged in with a valid session. * * @return true if logged in, false otherwise */ public boolean isLoggedIn() { return mState == State.LOGGED_ON; } /** * Add a listener which will receive events whenever the login state * changes. * * @param listener The callback interface */ public synchronized void addListener(ILoginEventsListener listener) { LogUtils.logD("LoginEngine.addListener()"); if (!mEventsListener.contains(listener)) { mEventsListener.add(listener); } } /** * Remove a listener added by the addListener function. * * @param listener The same callback interface passed in to the add function */ public synchronized void removeListener(ILoginEventsListener listener) { LogUtils.logD("LoginEngine.removeListener()"); mEventsListener.remove(listener); } /** * Remove all ILoginStateChangeListener (done as part of cleanup). */ private synchronized void removeAllListeners() { LogUtils.logD("LoginEngine.removeAllListeners()"); if (mEventsListener != null) { mEventsListener.clear(); } } /** * Once the engine has finished processing a user request, this function is * called to restore the state back to an appropriate value (based on the * user login state). */ private synchronized void restoreLoginState() { LogUtils.logD("LoginEngine.restoreLoginState"); if (mIsRegistrationComplete) { if (sActivatedSession != null) { newState(State.LOGGED_ON); } else { if (mAreLoginDetailsValid) { newState(State.LOGGED_OFF); } else { newState(State.LOGIN_FAILED); } } } else { newState(State.NOT_REGISTERED); } } /** * Called when a server response is received, processes the response based * on the engine state. * * @param resp Response data from server */ @Override protected void processCommsResponse(ResponseQueue.DecodedResponse resp) { LogUtils.logD("LoginEngine.processCommsResponse() - resp = " + resp); switch (mState) { case SIGNING_UP: handleSignUpResponse(resp.mDataTypes); break; case RETRIEVING_PUBLIC_KEY: handleNewPublicKeyResponse(resp.mDataTypes); break; case CREATING_SESSION_MANUAL: handleCreateSessionManualResponse(resp.mDataTypes); break; case CREATING_SESSION_AUTO: handleCreateSessionAutoResponse(resp.mDataTypes); break; case REQUESTING_ACTIVATION_CODE: handleRequestingActivationResponse(resp.mDataTypes); break; case ACTIVATING_ACCOUNT: handleActivateAccountResponse(resp.mDataTypes); break; case FETCHING_TERMS_OF_SERVICE: case FETCHING_PRIVACY_STATEMENT: case FETCHING_USERNAME_STATE: handleServerSimpleTextResponse(resp.mDataTypes, mState); break; default: // do nothing. break; } } /** * Called when a UI request is ready to be processed. Handlers the UI * request based on the type. * * @param requestId UI request type * @param data Interpretation of this data depends on the request type */ @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { LogUtils.logD("LoginEngine.processUiRequest() - reqID = " + requestId); switch (requestId) { case LOGIN: startManualLoginProcess((LoginDetails)data); break; case REGISTRATION: startRegistrationProcessCrypted((RegistrationDetails)data); break; case REMOVE_USER_DATA: startLogout(); // Remove NAB Account at this point (does nothing on 1.X) NativeContactsApi.getInstance().removePeopleAccount(); super.onReset(); // Sets the reset flag as done break; case LOGOUT: startLogout(); break; case FETCH_TERMS_OF_SERVICE: startFetchTermsOfService(); break; case FETCH_PRIVACY_STATEMENT: startFetchPrivacyStatement(); break; case USERNAME_AVAILABILITY: startFetchUsernameState((String)data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); } } /** * Called by the run() function the first time it is executed to perform * non-trivial initialisation such as auto login. */ private void initialiseEngine() { LogUtils.logD("LoginEngine.initialiseEngine()"); if (ServiceStatus.SUCCESS == mDb.fetchLogonCredentialsAndPublicKey(mLoginDetails, mPublicKey)) { if (mLoginDetails.mSubscriberId != null && !mLoginDetails.mSubscriberId.equals(mCurrentSubscriberId)) { LogUtils.logW("SIM card has changed. Login session invalid"); } else { sActivatedSession = StateTable.fetchSession(mDb.getReadableDatabase()); } } mAreLoginDetailsValid = true; restoreLoginState(); clearTimeout(); } /** * Starts the sign-up process where the password is RSA encrypted. A setting * determines if this function is used in preference to * {@link #startRegistrationProcess(RegistrationDetails)} function. * * @param details Registration details received from the UI request */ private void startRegistrationProcessCrypted(RegistrationDetails details) { LogUtils.logD("startRegistrationCrypted"); if (details == null || details.mUsername == null || details.mPassword == null) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } setRegistrationComplete(false); setActivatedSession(null); mRegistrationDetails.copy(details); mLoginDetails.mUsername = mRegistrationDetails.mUsername; mLoginDetails.mPassword = mRegistrationDetails.mPassword; try { final long timestampInSeconds = System.currentTimeMillis() / MS_IN_SECONDS; final byte[] theBytes = prepareBytesForSignup(timestampInSeconds); mLoginDetails.mAutoConnect = true; mLoginDetails.mRememberMe = true; mLoginDetails.mMobileNo = mRegistrationDetails.mMsisdn; mLoginDetails.mSubscriberId = mCurrentSubscriberId; mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); startSignUpCrypted(theBytes, timestampInSeconds); } catch (InvalidCipherTextException e) { e.printStackTrace(); } } /** * Encrypts the sign-up data ready for sending to the server * * @param timeStampInSeconds Current time in milliseconds * @return Raw data that can be sent to the server */ private byte[] prepareBytesForSignup(long timeStampInSeconds) throws InvalidCipherTextException { byte[] theBytes = null; if (mPublicKey != null) { if (mPublicKey.mExponential != null && (mPublicKey.mModulus != null)) { theBytes = RSAEncryptionUtils.encryptRSA(RSAEncryptionUtils.getRSAPubKey( mPublicKey.mModulus, mPublicKey.mExponential), makeSecurePassword( mLoginDetails.mUsername, mLoginDetails.mPassword, timeStampInSeconds)); } } if (theBytes == null) { RSAEncryptionUtils.copyDefaultPublicKey(mPublicKey);// we'll store // the default // public key // into the db theBytes = RSAEncryptionUtils.encryptRSA(RSAEncryptionUtils.getDefaultPublicKey(), makeSecurePassword(mLoginDetails.mUsername, mLoginDetails.mPassword, timeStampInSeconds)); } return theBytes; } /** * Concatenates the username, password, current time and some other data * into a string which can be encrypted and sent to the server. * * @param userName User name for sign-in or sign-up * @param password Password as entered by user * @param ts Current time in milliseconds * @return Concatenated data */ private static String makeSecurePassword(String userName, String password, long ts) { String appSecret = SettingsManager.getProperty(Settings.APP_SECRET_KEY);// RSAEncrypter.testAppSecretThrottled; final char amp = '&'; if (ts <= 0 || // userName == null || userName.trim().length() == 0 || // password == null || password.trim().length() == 0 || // // set application key somewhere appSecret == null || appSecret.trim().length() == 0) return null; final String passwordT = password.trim(); final String userNameT = userName.trim(); final StringBuffer sb = new StringBuffer(); sb.append(appSecret).append(amp).append(Long.toString(ts)).append(amp).append(userNameT) .append(amp).append(passwordT); return sb.toString(); } /** * Puts the engine into the signing up state and sends an encrypted sign-up * request to the server. * * @param theBytes byte-array containing encrypted password data. * @param timestamp Current timestamp. */ private void startSignUpCrypted(byte[] theBytes, long timestamp) { LogUtils.logD("startSignUpCrypted()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - completeUiRequest(ServiceStatus.ERROR_COMMS, null); + completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mActivationCode = null; newState(State.SIGNING_UP); if (!validateRegistrationDetails()) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } int reqId = Auth.signupUserCrypted( this, mRegistrationDetails.mFullname, mRegistrationDetails.mUsername, theBytes, // what is encrypted timestamp, mRegistrationDetails.mEmail, mRegistrationDetails.mBirthdayDate, mRegistrationDetails.mMsisdn, mRegistrationDetails.mAcceptedTAndC, mRegistrationDetails.mCountrycode, mRegistrationDetails.mTimezone, mRegistrationDetails.mLanguage, mRegistrationDetails.mMobileOperatorId, mRegistrationDetails.mMobileModelId, mRegistrationDetails.mSendConfirmationMail, mRegistrationDetails.mSendConfirmationSms, mRegistrationDetails.mSubscribeToNewsLetter); if (!setReqId(reqId)) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Basic check to determine if the registration details given by the user * are valid * * @return true if the details are valid, false otherwise. */ private boolean validateRegistrationDetails() { if (mRegistrationDetails.mFullname == null || mRegistrationDetails.mEmail == null || mRegistrationDetails.mBirthdayDate == null || mRegistrationDetails.mMsisdn == null || mRegistrationDetails.mAcceptedTAndC == null || mRegistrationDetails.mCountrycode == null || mRegistrationDetails.mTimezone == null || mRegistrationDetails.mLanguage == null || mRegistrationDetails.mMobileOperatorId == null || mRegistrationDetails.mMobileModelId == null || mRegistrationDetails.mSendConfirmationMail == null || mRegistrationDetails.mSendConfirmationSms == null || mRegistrationDetails.mSubscribeToNewsLetter == null) { return false; } return true; } /** * Requests a new Public Key from the server. */ public void getNewPublicKey() { LogUtils.logD("LoginEngine.getNewPublicKey"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - completeUiRequest(ServiceStatus.ERROR_COMMS, null); + completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mActivationCode = null; newState(State.RETRIEVING_PUBLIC_KEY); if (!setReqId(Auth.getPublicKey(this))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch terms of service request to the server. */ private void startFetchTermsOfService() { LogUtils.logD("LoginEngine.startFetchTermsOfService()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } newState(State.FETCHING_TERMS_OF_SERVICE); if (!setReqId(Auth.getTermsAndConditions(this))) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch privacy statement request to the server. */ private void startFetchPrivacyStatement() { LogUtils.logD("LoginEngine.startFetchPrivacyStatement()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } newState(State.FETCHING_PRIVACY_STATEMENT); if (!setReqId(Auth.getPrivacyStatement(this))) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch user-name state request to the server. * * @param username, the user-name to retrieve information for. */ private void startFetchUsernameState(String username) { LogUtils.logD("LoginEngine.startFetchUsernameState()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - completeUiRequest(ServiceStatus.ERROR_COMMS, null); + completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mLoginDetails.mUsername = username; newState(State.FETCHING_USERNAME_STATE); if (!setReqId(Auth.getUsernameState(this, username))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sets registration complete flag to false then starts a new sign-in * request. * * @param details Login details received from the UI request */ private void startManualLoginProcess(LoginDetails details) { LogUtils.logD("LoginEngine.startManualLoginProcess()"); setRegistrationComplete(false); setActivatedSession(null); if (details == null) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } mLoginDetails.copy(details); mLoginDetails.mSubscriberId = mCurrentSubscriberId; mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); if (Settings.ENABLE_ACTIVATION) { startRequestActivationCode(); } else { startGetSessionManual(); } } /** * Sends a request activation code request to the server. */ private void startRequestActivationCode() { LogUtils.logD("LoginEngine.startRequestActivationCode()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - completeUiRequest(ServiceStatus.ERROR_COMMS, null); + completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } mActivationCode = null; newState(State.REQUESTING_ACTIVATION_CODE); if (!setReqId(Auth.requestActivationCode(this, mLoginDetails.mUsername, mLoginDetails.mMobileNo))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a get session by credentials request to the server. */ private void startGetSessionManual() { LogUtils.logD("LoginEngine.startGetSessionManual()"); + if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - completeUiRequest(ServiceStatus.ERROR_COMMS, null); + completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } newState(State.CREATING_SESSION_MANUAL); if (!setReqId(Auth.getSessionByCredentials(this, mLoginDetails.mUsername, mLoginDetails.mPassword, null))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a activate account request to the server. */ private void startActivateAccount() { LogUtils.logD("LoginEngine.startActivateAccount()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - completeUiRequest(ServiceStatus.ERROR_COMMS, null); + completeUiRequest(NetworkAgent.getServiceStatusfromDisconnectReason(), null); return; } if (Settings.ENABLE_ACTIVATION) { newState(State.ACTIVATING_ACCOUNT); if (!setReqId(Auth.activate(this, mActivationCode))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } else { setRegistrationComplete(true); completeUiRequest(ServiceStatus.SUCCESS, null); } } /** * Clears the session and registration complete information so that the user * will need to manually login again to use the now+ services. Does not * currently send a request to the server to log out. */ private void startLogout() { LogUtils.logD("LoginEngine.startLogout()"); setRegistrationComplete(false); setActivatedSession(null); completeUiRequest(ServiceStatus.SUCCESS, null); } /** * Clears the session and registration complete information so that the user * will need to manually login again to use the now+ services. Does not * currently send a request to the server to log out. */ public final void logoutAndRemoveUser() { LogUtils.logD("LoginEngine.startLogout()"); addUiRemoveUserDataRequest(); LoginPreferences.clearPreferencesFile(mContext); mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UNSOLICITED_GO_TO_LANDING_PAGE, null); } /** * Retries to log the user in based on credential information stored in the * database. * * @return true if the login process was able to start */ public boolean retryAutoLogin() { LogUtils.logD("LoginEngine.retryAutoLogin()"); setActivatedSession(null); if (ServiceStatus.SUCCESS != mDb.fetchLogonCredentialsAndPublicKey(mLoginDetails, mPublicKey)) { LogUtils .logE("LoginEngine.retryAutoLogin() - Unable to fetch credentials from database"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } // AA: commented the condition out if (Settings.ENABLE_ACTIVATION) { // AA: the old version if (mCurrentSubscriberId == null || // !mCurrentSubscriberId.equals(mLoginDetails.mSubscriberId)) { // // logging off/fail will be done in another way according to bug 8288 if (mCurrentSubscriberId != null && !mCurrentSubscriberId.equals(mLoginDetails.mSubscriberId)) { LogUtils.logV("LoginEngine.retryAutoLogin() -" + " SIM card has changed or is missing (old subId = " + mLoginDetails.mSubscriberId + ", new subId = " + mCurrentSubscriberId + ")"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } // } if (mLoginDetails.mUsername == null || mLoginDetails.mPassword == null || mLoginDetails.mMobileNo == null) { LogUtils.logV("LoginEngine.retryAutoLogin() - Username, password " + "or mobile number are missing (old username = " + mLoginDetails.mUsername + ", mobile no = " + mLoginDetails.mMobileNo + ")"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } mAreLoginDetailsValid = true; if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { newState(State.LOGGED_OFF_WAITING_FOR_NETWORK); LogUtils.logV("LoginEngine.retryAutoLogin() - Internet connection down. " + "Will try again when connection is available"); return false; } newState(State.CREATING_SESSION_AUTO); if (!setReqId(Auth.getSessionByCredentials(this, mLoginDetails.mUsername, mLoginDetails.mPassword, null))) { return false; } return true; } /** * Helper function to set the registration complete flag and update the * database with the new state. * * @param value true if registration is completed */ private void setRegistrationComplete(boolean value) { LogUtils.logD("LoginEngine.setRegistrationComplete(" + value + ")"); if (value != mIsRegistrationComplete) { StateTable.setRegistrationComplete(value, mDb.getWritableDatabase()); mIsRegistrationComplete = value; if (mIsRegistrationComplete) { // Create NAB Account at this point (does nothing on 1.X // devices) final NativeContactsApi nabApi = NativeContactsApi.getInstance(); if (!nabApi.isPeopleAccountCreated()) { // TODO: React upon failure to create account nabApi.addPeopleAccount(LoginPreferences.getUsername()); } } } } /** * Changes the state of the engine. Also displays the login notification if * necessary. * * @param newState The new state */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("LoginEngine.newState: " + oldState + " -> " + mState); Intent intent = null; // Update notification switch (mState) { case LOGIN_FAILED_WRONG_CREDENTIALS: intent = new Intent(); intent.setAction(Intents.START_LOGIN_ACTIVITY); mContext.sendBroadcast(intent); setRegistrationComplete(false); break; // here should be no break case NOT_REGISTERED: case LOGIN_FAILED: // intent = new Intent(); // intent.setAction(Intents.LOGIN_FAILED); // mContext.sendBroadcast(intent); setRegistrationComplete(false); // startLogout(); // mDb.removeUserData(); // sending user to login screen again // should be done by UI itself because // when it's done from here it cause problems when user tries to // login // giving wrong credentials, ui flow will be broken break; case LOGGED_OFF: case LOGGED_OFF_WAITING_FOR_NETWORK: case LOGGED_OFF_WAITING_FOR_RETRY: case LOGGED_ON: // intent = new Intent(); // intent.setAction(Intents.HIDE_LOGIN_NOTIFICATION); // mContext.sendBroadcast(intent); break; default:// do nothing break; } // Update listeners with any state changes switch (mState) { case NOT_REGISTERED: case LOGIN_FAILED: case LOGIN_FAILED_WRONG_CREDENTIALS: case LOGGED_OFF: onLoginStateChanged(false); break; case LOGGED_ON: onLoginStateChanged(true); break; default: // do nothing. break; } } /** * Called when the engine transitions between the logged in and logged out * states. Notifies listeners. * * @param loggedIn true if the user is now logged in, false otherwise. */ private synchronized void onLoginStateChanged(boolean loggedIn) { LogUtils.logD("LoginEngine.onLoginStateChanged() Login state changed to " + (loggedIn ? "logged in." : "logged out.")); if (loggedIn == mCurrentLoginState) { return; } mCurrentLoginState = loggedIn; for (ILoginEventsListener listener : mEventsListener) { listener.onLoginStateChanged(loggedIn); } } /** * A helper function which determines which activity should be displayed * when the UI is loaded. * * @return true if landing page should be displayed, false otherwise */ public synchronized boolean getLoginRequired() { LogUtils.logD("LoginEngine.getLoginRequired() - " + !mIsRegistrationComplete); return !mIsRegistrationComplete; } /** * Retrieves the active comms session. * * @return The session or NULL if the user is logged out. */ public static AuthSessionHolder getSession() { return sActivatedSession; } /** * Helper function to store the new session in the database and inform * clients that the session has changed. * * @param session The new session or NULL if the user has logged off. */ public synchronized void setActivatedSession(AuthSessionHolder session) { LogUtils.logD("LoginEngine.setActivatedSession() session[" + session + "]"); sActivatedSession = session; if (session != null) { LogUtils.logD("LoginEngine.setActivatedSession() Login successful"); } else { LogUtils.logW("LoginEngine.setActivatedSession() " + "Login unsuccessful, the session is NULL"); } StateTable.setSession(session, mDb.getWritableDatabase()); } /** * Called when a response to the sign-up API is received. In case of success * sets a timeout value waiting for the activation SMS to arrive. * * @param data The received data */ private void handleSignUpResponse(List<BaseDataType> data) { ServiceStatus errorStatus = getResponseStatus(BaseDataType.CONTACT_DATA_TYPE, data); LogUtils.logD("LoginEngine.handleSignUpResponse() errorStatus[" + errorStatus.name() + "]"); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils.logD("LoginEngine.handleSignUpResponse() - Registration successful"); if (!Settings.ENABLE_ACTIVATION) { startGetSessionManual(); } else { // Now waiting for SMS... setTimeout(ACTIVATE_LOGIN_TIMEOUT); } // AA } else if (errorStatus == ServiceStatus.ERROR_INVALID_PUBLIC_KEY) { // start new key retrieval and make the new cycle getNewPublicKey(); } else { completeUiRequest(errorStatus, null); } } /** * Called when a response to the server fetch public key request is * received. Validates the response and stores the new public key details. * * @param mDataTypes Response data from server. */ private void handleNewPublicKeyResponse(List<BaseDataType> mDataTypes) { LogUtils.logD("LoginEngine.handleNewPublicKeyResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.PUBLIC_KEY_DETAILS_DATA_TYPE, mDataTypes); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils.logD("LoginEngine.handleNewPublicKeyResponse() - Succesfully retrieved"); // AA // 1. save to DB; save the flag that we aren't using default and // have to use one from DB // 2. start registration again mPublicKey = (PublicKeyDetails)mDataTypes.get(0); // done in startRegistrationProcessCrypted already // mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); startRegistrationProcessCrypted(mRegistrationDetails); } else { completeUiRequest(errorStatus, null); } } /** * Called when a response to the GetSessionByCredentials API is received * (manual login). In case of success, tries to activate the account using * the activation code received by SMS. * * @param data The received data */ private void handleCreateSessionManualResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleCreateSessionManualResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AUTH_SESSION_HOLDER_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS && (data.size() > 0)) { setActivatedSession((AuthSessionHolder)data.get(0)); startActivateAccount(); return; } completeUiRequest(errorStatus, null); } /** * Called when a response to the GetSessionByCredentials API is received * (auto login). In case of success, moves to the logged in state * * @param data The received data */ private void handleCreateSessionAutoResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleCreateSessionResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AUTH_SESSION_HOLDER_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { clearTimeout(); setActivatedSession((AuthSessionHolder)data.get(0)); newState(State.LOGGED_ON); } else { LogUtils.logE("LoginEngine.handleCreateSessionResponse() - Auto Login Failed Error " + errorStatus); // AA:the 1st retry failed, just go to the start page, // if (loginAttemptsRemaining() // && errorStatus!=ServiceStatus.ERROR_INVALID_PASSWORD) { // newState(State.LOGGED_OFF_WAITING_FOR_RETRY); // setTimeout(LOGIN_RETRY_TIME); // } else { // mAreLoginDetailsValid = false; if (errorStatus == ServiceStatus.ERROR_INVALID_PASSWORD) { mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED_WRONG_CREDENTIALS); } else { newState(State.LOGIN_FAILED); } // } } } /** * Called when a response to the RequestActivationCode API is received * (manual login). In case of success, tries to fetch a login session from * the server. * * @param data The received data */ private void handleRequestingActivationResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleRequestingActivationResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { // Now waiting for SMS... setTimeout(ACTIVATE_LOGIN_TIMEOUT); return; } completeUiRequest(errorStatus, null); } /** * Called when a response to the Activate API is received (manual login or * sign-up). In case of success, moves to the logged in state and completes * the manual login or sign-up request. * * @param data The received data */ private void handleActivateAccountResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleActivateAccountResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils .logD("LoginEngine.handleActivateAccountResponse: ** Mobile number activated **"); setRegistrationComplete(true); completeUiRequest(ServiceStatus.SUCCESS, null); return; } setActivatedSession(null); completeUiRequest(ServiceStatus.ERROR_ACCOUNT_ACTIVATION_FAILED, null); } /** * Called when a response to the GetTermsAndConditions, GetPrivacyStatement * and GetUsernameState APIs are received. In case of success, completes the * request and passes the response data to the UI. * * @param data The received data */ private void handleServerSimpleTextResponse(List<BaseDataType> data, State type) { LogUtils.logV("LoginEngine.handleServerSimpleTextResponse()"); ServiceStatus serviceStatus = getResponseStatus(BaseDataType.SIMPLE_TEXT_DATA_TYPE, data); String result = null; if (serviceStatus == ServiceStatus.SUCCESS) { result = ((SimpleText) data.get(0)).mValue.toString().replace( CARRIAGE_RETURN_CHARACTER, SPACE_CHARACTER); switch (type) { case FETCHING_TERMS_OF_SERVICE: LogUtils.logD("LoginEngine.handleServerSimpleTextResponse() Terms of Service"); ApplicationCache.setTermsOfService(result, mContext); break; case FETCHING_PRIVACY_STATEMENT: LogUtils.logD("LoginEngine.handleServerSimpleTextResponse() Privacy Statemet"); ApplicationCache.setPrivacyStatemet(result, mContext); break; case FETCHING_USERNAME_STATE: // TODO: Unused by UI. break; } } updateTermsState(serviceStatus, result); } /*** * Informs the UI to update any terms which are being shown on screen. * * @param serviceStatus Current ServiceStatus. * @param messageText Legacy call for old UI (TODO: remove after UI-Refresh * merge). NULL when combined with a ServiceStatus of * ERROR_COMMS, or contains the Privacy or Terms and Conditions * text to be displayed in the UI. */ private void updateTermsState(ServiceStatus serviceStatus, String messageText) { ApplicationCache.setTermsStatus(serviceStatus); /** Trigger UiAgent. **/ mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.TERMS_CHANGED_EVENT, null); /** Clear this request from the UI queue. **/ completeUiRequest(serviceStatus, messageText); } /** * A broadcast receiver which is used to receive notifications when a data * SMS arrives. */ private final BroadcastReceiver mEventReceiver = new BroadcastReceiver() { /** * Called when an SMS arrives. The activation code is extracted from the * given intent and the worker thread kicked. * * @param context Context from which the intent was broadcast * @param intent Will only process the SMS which the action is * {@link SmsBroadcastReceiver#ACTION_ACTIVATION_CODE}. */ @Override public void onReceive(Context context, Intent intent) { LogUtils.logD("LoginEngine.BroadcastReceiver.onReceive - Processing data sms"); if (intent.getAction().equals(SmsBroadcastReceiver.ACTION_ACTIVATION_CODE)) { String activationCode = intent.getStringExtra("code"); LogUtils .logD("LoginEngine.BroadcastReceiver.onReceive - Activation code Received: " + activationCode); synchronized (LoginEngine.this) { mActivationCode = activationCode; } mEventCallback.kickWorkerThread(); } } }; /** * Called when an SMS is received during sign-up or manual login. Starts * requesting a session from the server. */ private void handleSmsResponse() { LogUtils.logD("LoginEngine.handleSmsResponse(" + mActivationCode + ")"); clearTimeout(); startGetSessionManual(); } /** * Called by the base engine implementation whenever a UI request is * completed to do any necessary cleanup. We use it to restore our state to * a suitable value. */ @Override protected void onRequestComplete() { LogUtils.logD("LoginEngine.onRequestComplete()"); restoreLoginState(); } /** * Handles timeouts for SMS activation and auto login retries. */ protected synchronized void onTimeoutEvent() { LogUtils.logD("LoginEngine.onTimeoutEvent()"); switch (mState) { case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: completeUiRequest(ServiceStatus.ERROR_SMS_CODE_NOT_RECEIVED, null); break; case LOGGED_OFF_WAITING_FOR_RETRY: retryAutoLogin(); break; default: // do nothing. break; } } /** * Called by the framework before a remove user data operation takes place. diff --git a/src/com/vodafone360/people/service/agent/NetworkAgent.java b/src/com/vodafone360/people/service/agent/NetworkAgent.java index 1d901ce..07b74f4 100644 --- a/src/com/vodafone360/people/service/agent/NetworkAgent.java +++ b/src/com/vodafone360/people/service/agent/NetworkAgent.java @@ -1,690 +1,714 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.agent; import java.security.InvalidParameterException; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.ContentObserver; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.telephony.TelephonyManager; import android.text.format.DateUtils; import com.vodafone360.people.Intents; import com.vodafone360.people.MainApplication; import com.vodafone360.people.service.PersistSettings; import com.vodafone360.people.service.RemoteService; +import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.interfaces.IConnectionManagerInterface; import com.vodafone360.people.service.interfaces.IWorkerThreadControl; import com.vodafone360.people.utils.LogUtils; /** * The network Agent monitors the connectivity status of the device and makes * decisions about the communication strategy. The Agent has the following * states {connected | disconnected}, with changes reported to various listeners * in the service. */ public class NetworkAgent { /** Roaming notification is on */ public static final int ROAMING_DIALOG_GLOBAL_ON = 0; /** Roaming notification is off */ public static final int ROAMING_DIALOG_GLOBAL_OFF = 1; private static final int TYPE_WIFI = 1; private static AgentState mAgentState = AgentState.UNKNOWN; private ConnectivityManager mConnectivityManager; private ContentResolver mContentResolver; - private AgentDisconnectReason mDisconnectReason = AgentDisconnectReason.UNKNOWN; + private static AgentDisconnectReason mDisconnectReason = AgentDisconnectReason.UNKNOWN; private SettingsContentObserver mDataRoamingSettingObserver; private boolean mInternetConnected; private boolean mDataRoaming; private boolean mBackgroundData; private boolean mIsRoaming; private boolean mIsInBackground; private boolean mNetworkWorking = true; // dateTime value in milliseconds private Long mDisableRoamingNotificationUntil = null; private IWorkerThreadControl mWorkerThreadControl; private IConnectionManagerInterface mConnectionMgrIf; private Context mContext; public enum AgentState { CONNECTED, DISCONNECTED, UNKNOWN }; private boolean mWifiNetworkAvailable; private boolean mMobileNetworkAvailable; /** * Reasons for Service Agent changing state to disconnected */ public enum AgentDisconnectReason { AGENT_IS_CONNECTED, // Sanity check NO_INTERNET_CONNECTION, NO_WORKING_NETWORK, DATA_SETTING_SET_TO_MANUAL_CONNECTION, DATA_ROAMING_DISABLED, BACKGROUND_CONNECTION_DISABLED, // WIFI_INACTIVE, UNKNOWN } public enum StatesOfService { IS_CONNECTED_TO_INTERNET, IS_NETWORK_WORKING, IS_ROAMING, IS_ROAMING_ALLOWED, IS_INBACKGROUND, IS_BG_CONNECTION_ALLOWED, IS_WIFI_ACTIVE }; /** * Listens for changes made to People client's status. The NetworkAgent is * specifically interested in changes to the data settings (e.g. data * disabled, only in home network or roaming). */ private class SettingsContentObserver extends ContentObserver { private String mSettingName; private SettingsContentObserver(String settingName) { super(new Handler()); mSettingName = settingName; } /** * Start content observer. */ private void start() { if (mContentResolver != null) { mContentResolver.registerContentObserver(Settings.Secure.getUriFor(mSettingName), true, this); } } /** * De-activate content observer. */ private void close() { if (mContentResolver != null) { mContentResolver.unregisterContentObserver(this); } } @Override public void onChange(boolean selfChange) { onDataSettingChanged(mSettingName); } public boolean getBooleanValue() { if (mContentResolver != null) { try { return (Settings.Secure.getInt(mContentResolver, mSettingName) != 0); } catch (SettingNotFoundException e) { LogUtils.logE("NetworkAgent.SettingsContentObserver.getBooleanValue() " + "SettingNotFoundException", e); return false; } } return false; } } /** * The constructor. * * @param context Android context. * @param workerThreadControl Handle to kick the worker thread. * @param connMgrIf Handler to signal the connection manager. * @throws InvalidParameterException Context is NULL. * @throws InvalidParameterException IWorkerThreadControl is NULL. * @throws InvalidParameterException IConnectionManagerInterface is NULL. */ public NetworkAgent(Context context, IWorkerThreadControl workerThreadControl, IConnectionManagerInterface connMgrIf) { if (context == null) { throw new InvalidParameterException("NetworkAgent() Context canot be NULL"); } if (workerThreadControl == null) { throw new InvalidParameterException("NetworkAgent() IWorkerThreadControl canot be NULL"); } if (connMgrIf == null) { throw new InvalidParameterException( "NetworkAgent() IConnectionManagerInterface canot be NULL"); } mContext = context; mWorkerThreadControl = workerThreadControl; mConnectionMgrIf = connMgrIf; mContentResolver = context.getContentResolver(); mConnectivityManager = (ConnectivityManager)context .getSystemService(Context.CONNECTIVITY_SERVICE); mDataRoamingSettingObserver = new SettingsContentObserver(Settings.Secure.DATA_ROAMING); } /** * Create NetworkAgent and start observers of device connectivity state. * * @throws InvalidParameterException DataRoamingSettingObserver is NULL. * @throws InvalidParameterException Context is NULL. * @throws InvalidParameterException ConnectivityManager is NULL. */ public void onCreate() { if (mDataRoamingSettingObserver == null) { throw new InvalidParameterException( "NetworkAgent.onCreate() DataRoamingSettingObserver canot be NULL"); } if (mContext == null) { throw new InvalidParameterException("NetworkAgent.onCreate() Context canot be NULL"); } if (mConnectivityManager == null) { throw new InvalidParameterException( "NetworkAgent.onCreate() ConnectivityManager canot be NULL"); } mDataRoamingSettingObserver.start(); mDataRoaming = mDataRoamingSettingObserver.getBooleanValue(); mContext.registerReceiver(mBackgroundDataBroadcastReceiver, new IntentFilter( ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED)); mContext.registerReceiver(mInternetConnectivityReceiver, new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION)); mContext.registerReceiver(mServiceStateRoamingReceiver, new IntentFilter( "android.intent.action.SERVICE_STATE")); NetworkInfo info = mConnectivityManager.getActiveNetworkInfo(); if (info != null) { mInternetConnected = (info.getState() == NetworkInfo.State.CONNECTED); mWifiNetworkAvailable = (info.getType() == TYPE_WIFI); mIsRoaming = info.isRoaming(); } mBackgroundData = mConnectivityManager.getBackgroundDataSetting(); onConnectionStateChanged(); } /** * Destroy NetworkAgent and un-register observers. * * @throws InvalidParameterException Context is NULL. * @throws InvalidParameterException DataRoamingSettingObserver is NULL. */ public void onDestroy() { if (mContext == null) { throw new InvalidParameterException("NetworkAgent.onCreate() Context canot be NULL"); } if (mDataRoamingSettingObserver == null) { throw new InvalidParameterException( "NetworkAgent.onDestroy() DataRoamingSettingObserver canot be NULL"); } mContext.unregisterReceiver(mInternetConnectivityReceiver); mContext.unregisterReceiver(mBackgroundDataBroadcastReceiver); mContext.unregisterReceiver(mServiceStateRoamingReceiver); mDataRoamingSettingObserver.close(); mDataRoamingSettingObserver = null; } /** * Receive notification from * ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED */ private final BroadcastReceiver mBackgroundDataBroadcastReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogUtils .logV("NetworkAgent.broadcastReceiver.onReceive() ACTION_BACKGROUND_DATA_SETTING_CHANGED"); synchronized (NetworkAgent.this) { if (mConnectivityManager != null) { mBackgroundData = mConnectivityManager.getBackgroundDataSetting(); onConnectionStateChanged(); } } } }; /** * Receive notification from ConnectivityManager.CONNECTIVITY_ACTION */ private final BroadcastReceiver mInternetConnectivityReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() CONNECTIVITY_ACTION"); synchronized (NetworkAgent.this) { NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); if (info == null) { LogUtils.logW("NetworkAgent.broadcastReceiver.onReceive() EXTRA_NETWORK_INFO not found."); } else { if (info.getType() == TYPE_WIFI) { mWifiNetworkAvailable = (info.getState() == NetworkInfo.State.CONNECTED); } else { mMobileNetworkAvailable = (info.getState() == NetworkInfo.State.CONNECTED); } } if (noConnectivity) { LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() EXTRA_NO_CONNECTIVITY found!"); mInternetConnected = false; } else { mInternetConnected = mWifiNetworkAvailable || mMobileNetworkAvailable; } LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() mInternetConnected = " + mInternetConnected + ", mWifiNetworkAvailable = " + mWifiNetworkAvailable + ", mMobileNetworkAvailable = " + mMobileNetworkAvailable); onConnectionStateChanged(); } } }; /** * Receive notification from android.intent.action.SERVICE_STATE */ private final BroadcastReceiver mServiceStateRoamingReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() SERVICE_STATE"); synchronized (NetworkAgent.this) { // //ConnectivityManager provides wrong information about // roaming // NetworkInfo info = // mConnectivityManager.getActiveNetworkInfo(); // if (info != null) { // mIsRoaming = info.isRoaming(); // } LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() Extras are: " + intent.getExtras()); Bundle bu = intent.getExtras(); // int state = bu.getInt("state"); boolean roam = bu.getBoolean("roaming"); mIsRoaming = roam; onConnectionStateChanged(); LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() Network Roaming = " + mIsRoaming); LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() WiFi active = " + mWifiNetworkAvailable); } processRoaming(null); } }; /** * Notify interested parties of changes in Internet setting. * * @param val updated InternetAvail value. */ public void notifyDataSettingChanged(InternetAvail val) { processRoaming(val); onConnectionStateChanged(); } /** * Displaying notification to the user about roaming * * @param InternetAvail value. */ private void processRoaming(InternetAvail val) { InternetAvail internetAvail; if (val != null) { internetAvail = val; } else { internetAvail = getInternetAvailSetting(); } Intent intent = new Intent(); if (mContext != null && mIsRoaming && (internetAvail == InternetAvail.ALWAYS_CONNECT) && (mDisableRoamingNotificationUntil == null || mDisableRoamingNotificationUntil < System .currentTimeMillis())) { LogUtils.logV("NetworkAgent.processRoaming() " + "Displaying notification - DisplayRoaming[" + mIsRoaming + "]"); intent.setAction(Intents.ROAMING_ON); } else { /* * We are not roaming then we should remove notification, if no * notification were before nothing happens */ LogUtils.logV("NetworkAgent.processRoaming() Removing notification - " + " DisplayRoaming[" + mIsRoaming + "]"); intent.setAction(Intents.ROAMING_OFF); } mContext.sendBroadcast(intent); } private InternetAvail getInternetAvailSetting() { if (mContext != null) { PersistSettings setting = ((MainApplication)((RemoteService)mContext).getApplication()) .getDatabase().fetchOption(PersistSettings.Option.INTERNETAVAIL); if (setting != null) { return setting.getInternetAvail(); } } return null; } public int getRoamingNotificationType() { int type; if (mDataRoaming) { type = ROAMING_DIALOG_GLOBAL_ON; } else { type = ROAMING_DIALOG_GLOBAL_OFF; } return type; } /** * Get current device roaming setting. * * @return current device roaming setting. */ public boolean getRoamingDeviceSetting() { return mDataRoaming; } public void setShowRoamingNotificationAgain(boolean showAgain) { LogUtils.logV("NetworkAgent.setShowRoamingNotificationAgain() " + "showAgain[" + showAgain + "]"); if (showAgain) { mDisableRoamingNotificationUntil = null; } else { mDisableRoamingNotificationUntil = System.currentTimeMillis() + DateUtils.DAY_IN_MILLIS; if (mContext != null) { LogUtils.logV("NetworkAgent.setShowRoamingNotificationAgain() " + "Next notification on [" + DateUtils.formatDateTime(mContext, mDisableRoamingNotificationUntil, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_YEAR) + "]"); } } processRoaming(null); } /** * Received when user modifies one of the system settings */ private synchronized void onDataSettingChanged(String settingName) { LogUtils.logV("NetworkAgent.onDataSettingChanged() settingName[" + settingName + "]" + " has changed"); if (settingName.equals(Settings.Secure.DATA_ROAMING)) { if (mDataRoamingSettingObserver != null) { mDataRoaming = mDataRoamingSettingObserver.getBooleanValue(); onConnectionStateChanged(); } } } /** * Contains the main logic that determines the agent state for network * access */ private void onConnectionStateChanged() { - if (!mInternetConnected) { - LogUtils.logV("NetworkAgent.onConnectionStateChanged() No internet connection"); - mDisconnectReason = AgentDisconnectReason.NO_INTERNET_CONNECTION; - setNewState(AgentState.DISCONNECTED); - return; - } else { - if (mWifiNetworkAvailable) { - LogUtils.logV("NetworkAgent.onConnectionStateChanged() WIFI connected"); - } else { - LogUtils.logV("NetworkAgent.onConnectionStateChanged() Cellular connected"); - } - } if (mContext != null) { MainApplication app = (MainApplication)((RemoteService)mContext).getApplication(); if ((app.getInternetAvail() == InternetAvail.MANUAL_CONNECT)/* * AA: I * commented * it - * TBD * &&! * mWifiNetworkAvailable */) { LogUtils.logV("NetworkAgent.onConnectionStateChanged()" + " Internet allowed only in manual mode"); mDisconnectReason = AgentDisconnectReason.DATA_SETTING_SET_TO_MANUAL_CONNECTION; setNewState(AgentState.DISCONNECTED); return; } } if (!mNetworkWorking) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() Network is not working"); mDisconnectReason = AgentDisconnectReason.NO_WORKING_NETWORK; setNewState(AgentState.DISCONNECTED); return; } if (mIsRoaming && !mDataRoaming && !mWifiNetworkAvailable) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() " + "Connect while roaming not allowed"); mDisconnectReason = AgentDisconnectReason.DATA_ROAMING_DISABLED; setNewState(AgentState.DISCONNECTED); return; } if (mIsInBackground && !mBackgroundData) { - LogUtils - .logV("NetworkAgent.onConnectionStateChanged() Background connection not allowed"); + LogUtils.logV("NetworkAgent.onConnectionStateChanged() Background connection not allowed"); mDisconnectReason = AgentDisconnectReason.BACKGROUND_CONNECTION_DISABLED; setNewState(AgentState.DISCONNECTED); return; } + if (!mInternetConnected) { + LogUtils.logV("NetworkAgent.onConnectionStateChanged() No internet connection"); + mDisconnectReason = AgentDisconnectReason.NO_INTERNET_CONNECTION; + setNewState(AgentState.DISCONNECTED); + return; + } + + if (mWifiNetworkAvailable) { + LogUtils.logV("NetworkAgent.onConnectionStateChanged() WIFI connected"); + } else { + LogUtils.logV("NetworkAgent.onConnectionStateChanged() Cellular connected"); + } + LogUtils.logV("NetworkAgent.onConnectionStateChanged() Connection available"); setNewState(AgentState.CONNECTED); } public static AgentState getAgentState() { LogUtils.logV("NetworkAgent.getAgentState() mAgentState[" + mAgentState.name() + "]"); return mAgentState; } + public static ServiceStatus getServiceStatusfromDisconnectReason() { + + if (mDisconnectReason != null) + switch (mDisconnectReason) + { + case AGENT_IS_CONNECTED: + return ServiceStatus.SUCCESS; + case NO_WORKING_NETWORK: + return ServiceStatus.ERROR_NO_INTERNET; + case NO_INTERNET_CONNECTION: + return ServiceStatus.ERROR_NO_INTERNET; + case DATA_ROAMING_DISABLED: + return ServiceStatus.ERROR_ROAMING_INTERNET_NOT_ALLOWED; + case DATA_SETTING_SET_TO_MANUAL_CONNECTION: + return ServiceStatus.ERROR_NO_AUTO_CONNECT; + case BACKGROUND_CONNECTION_DISABLED: + // TODO: define appropriate ServiceStatus + return ServiceStatus.ERROR_COMMS; + } + + return ServiceStatus.ERROR_COMMS; + } + private void setNewState(AgentState newState) { if (newState == mAgentState) { return; } LogUtils.logI("NetworkAgent.setNewState(): " + mAgentState + " -> " + newState); mAgentState = newState; if (newState == AgentState.CONNECTED) { mDisconnectReason = AgentDisconnectReason.AGENT_IS_CONNECTED; onConnected(); } else if (newState == AgentState.DISCONNECTED) { onDisconnected(); } } private void onConnected() { checkActiveNetworkState(); if (mWorkerThreadControl != null) { mWorkerThreadControl.kickWorkerThread(); } if (mConnectionMgrIf != null) { mConnectionMgrIf.signalConnectionManager(true); } } private void onDisconnected() { // AA:need to kick it to make engines run and set the if (mWorkerThreadControl != null) { mWorkerThreadControl.kickWorkerThread(); } if (mConnectionMgrIf != null) { mConnectionMgrIf.signalConnectionManager(false); } } private void checkActiveNetworkState() { if (mConnectivityManager != null) { NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo == null) { LogUtils.logW("NetworkAgent.checkActiveNetworkInfoy() " + "mConnectivityManager.getActiveNetworkInfo() Returned null"); return; } else { if (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { LogUtils.logV("NetworkAgent.checkActiveNetworkInfoy() WIFI network"); // TODO: Do something } else if (mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { LogUtils.logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE and ROAMING"); // TODO: Do something // Only works when you are registering with network switch (mNetworkInfo.getSubtype()) { case TelephonyManager.NETWORK_TYPE_EDGE: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE EDGE network"); // TODO: Do something break; case TelephonyManager.NETWORK_TYPE_GPRS: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE GPRS network"); // TODO: Do something break; case TelephonyManager.NETWORK_TYPE_UMTS: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE UMTS network"); // TODO: Do something break; case TelephonyManager.NETWORK_TYPE_UNKNOWN: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE UNKNOWN network"); // TODO: Do something break; default: // Do nothing. break; } ; } } } else { LogUtils.logW("NetworkAgent.checkActiveNetworkInfoy() mConnectivityManager is null"); } } public void setNetworkAgentState(NetworkAgentState state) { LogUtils.logD("NetworkAgent.setNetworkAgentState() state[" + state + "]"); // TODO: make assignments if any changes boolean changes[] = state.getChanges(); if (changes[StatesOfService.IS_CONNECTED_TO_INTERNET.ordinal()]) mInternetConnected = state.isInternetConnected(); if (changes[StatesOfService.IS_NETWORK_WORKING.ordinal()]) mNetworkWorking = state.isNetworkWorking(); if (changes[StatesOfService.IS_ROAMING_ALLOWED.ordinal()]) mDataRoaming = state.isRoamingAllowed(); if (changes[StatesOfService.IS_INBACKGROUND.ordinal()]) mIsInBackground = state.isInBackGround(); if (changes[StatesOfService.IS_BG_CONNECTION_ALLOWED.ordinal()]) mBackgroundData = state.isBackDataAllowed(); if (changes[StatesOfService.IS_WIFI_ACTIVE.ordinal()]) mWifiNetworkAvailable = state.isWifiActive(); if (changes[StatesOfService.IS_ROAMING.ordinal()]) {// special case for // roaming mIsRoaming = state.isRoaming(); // This method sets the mAgentState, and mDisconnectReason as well // by calling setNewState(); onConnectionStateChanged(); processRoaming(null); } else // This method sets the mAgentState, and mDisconnectReason as well // by calling setNewState(); onConnectionStateChanged(); } public NetworkAgentState getNetworkAgentState() { NetworkAgentState state = new NetworkAgentState(); state.setRoaming(mIsRoaming); state.setRoamingAllowed(mDataRoaming); state.setBackgroundDataAllowed(mBackgroundData); state.setInBackGround(mIsInBackground); state.setInternetConnected(mInternetConnected); state.setNetworkWorking(mNetworkWorking); state.setWifiActive(mWifiNetworkAvailable); state.setDisconnectReason(mDisconnectReason); state.setAgentState(mAgentState); LogUtils.logD("NetworkAgent.getNetworkAgentState() state[" + state + "]"); return state; } // ///////////////////////////// // FOR TESTING PURPOSES ONLY // // ///////////////////////////// /** * Forces the AgentState to a specific value. * * @param newState the state to set Note: to be used only for test purposes */ public static void setAgentState(AgentState newState) { mAgentState = newState; } }
360/360-Engine-for-Android
c9d578a26685b421a8a555269b694f234798b64a
PAND-2360 call getMyIdentities() after the credentials are validated
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 9fffe3e..3396162 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,969 +1,977 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.identities; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import android.os.Bundle; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Identities; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.ThirdPartyAccount; /** * Engine responsible for handling retrieval and validation of Identities (e.g. * 3rd party/web accounts). The Identities engine can fetch a list of available * accounts, and set required capabilities and validate credentials for * specified accounts. */ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { /** * States for IdentitiesEngine. States are based on the requests that the * engine needs to handle. */ private enum State { IDLE, FETCHING_IDENTITIES, VALIDATING_IDENTITY_CREDENTIALS, SETTING_IDENTITY_STATUS, GETTING_MY_IDENTITIES, GETTING_MY_CHATABLE_IDENTITIES, DELETE_IDENTITY } /** * Mutex for thread synchronisation */ private final Object mMutex = new Object(); /** * Container class for Identity Capability Status request. Consists of a * network, identity id and a filter containing the required capabilities. */ private static class IdentityStatusRequest { private String mNetwork; private String mIdentityId; private String mIdentityStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setIdentityStatus(String status) { mIdentityStatus = status; } } /** * Container class encapsulating an Identity validation request containing: * dry-run flag, network, user-name, password, set of required capabilities. */ private static class IdentityValidateCredentialsRequest { /** Performs a dry run if true. */ private boolean mDryRun; /** Network to sign into. */ private String mNetwork; /** Username to sign into identity with. */ private String mUserName; /** Password to sign into identity with. */ private String mPassword; private Map<String, Boolean> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } /** * * Container class for Delete Identity request. Consist network and identity id. * */ private static class DeleteIdentityRequest { /** Network to delete.*/ private String mNetwork; /** IdentityID which needs to be Deleted.*/ private String mIdentityId; } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mMyIdentityList; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; /** * Maintaining DeleteIdentityRequest so that it can be later removed from * maintained cache. **/ private DeleteIdentityRequest identityToBeDeleted; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; mMyIdentityList = new ArrayList<Identity>(); mAvailableIdentityList = new ArrayList<Identity>(); mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { final ArrayList<Identity> availableIdentityList; synchronized(mAvailableIdentityList) { // make a shallow copy availableIdentityList = new ArrayList<Identity>(mAvailableIdentityList); } if ((availableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return availableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { final ArrayList<Identity> myIdentityList; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } if ((myIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return myIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = getMyThirdPartyChattableIdentities(); // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chattableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chattableIdentities; } /** * * Takes all third party identities that have a chat capability set to true. * * @return A list of chattable 3rd party identities the user is signed in to. If the retrieval identities failed the returned list will be empty. * */ public ArrayList<Identity> getMyThirdPartyChattableIdentities() { final ArrayList<Identity> chattableIdentities = new ArrayList<Identity>(); final ArrayList<Identity> myIdentityList; final int identityListSize; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } identityListSize = myIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = myIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue)) { chattableIdentities.add(identity); break; } } } return chattableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Delete the given social network. * * @param network Name of the identity, * @param identityId Id of identity. */ public final void addUiDeleteIdentityRequest(final String network, final String identityId) { LogUtils.logD("IdentityEngine.addUiRemoveIdentity()"); DeleteIdentityRequest data = new DeleteIdentityRequest(); data.mNetwork = network; data.mIdentityId = identityId; /**maintaining the sent object*/ setIdentityToBeDeleted(data); addUiRequestToQueue(ServiceUiRequest.DELETE_IDENTITY, data); } /** * Setting the DeleteIdentityRequest object. * * @param data */ private void setIdentityToBeDeleted(final DeleteIdentityRequest data) { identityToBeDeleted = data; } /** * Return the DeleteIdentityRequest object. * */ private DeleteIdentityRequest getIdentityToBeDeleted() { return identityToBeDeleted; } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { + case GET_MY_IDENTITIES: + sendGetMyIdentitiesRequest(); + completeUiRequest(ServiceStatus.SUCCESS); + break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; case DELETE_IDENTITY: executeDeleteIdentityRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to delete the identity as specified . (Request is not issued if there * is currently no connectivity). * * @param data bundled request data containing network and identityId. */ private void executeDeleteIdentityRequest(final Object data) { if (!isConnected()) { completeUiRequest(ServiceStatus.ERROR_NO_INTERNET); } newState(State.DELETE_IDENTITY); DeleteIdentityRequest reqData = (DeleteIdentityRequest) data; if (!setReqId(Identities.deleteIdentity(this, reqData.mNetwork, reqData.mIdentityId))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(DecodedResponse resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if ((null == resp) || (null == resp.mDataTypes)) { LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); return; } // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; case BaseDataType.IDENTITY_DELETION_DATA_TYPE: handleDeleteIdentity(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); } } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { Identity identity = (Identity)item; mMyIdentityList.add(identity); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); + + if (errorStatus == ServiceStatus.SUCCESS) { + addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, null); + } } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response of request to delete the identity. The response * should be a status that whether the operation is succeeded or not. The * response will be a status result otherwise ERROR_UNEXPECTED_RESPONSE if * the response is not as expected. * * @param data * List of BaseDataTypes generated from Server response. */ private void handleDeleteIdentity(final List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus( BaseDataType.IDENTITY_DELETION_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { for (BaseDataType item : data) { if (item.getType() == BaseDataType.IDENTITY_DELETION_DATA_TYPE) { synchronized(mMyIdentityList) { // iterating through the subscribed identities for (Identity identity : mMyIdentityList) { if (identity.mIdentityId .equals(getIdentityToBeDeleted().mIdentityId)) { mMyIdentityList.remove(identity); break; } } } completeUiRequest(ServiceStatus.SUCCESS); return; } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } } completeUiRequest(errorStatus, bu); } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; synchronized (mAvailableIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mAvailableIdentityList); } } else { requestKey = KEY_MY_IDS; synchronized (mMyIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mMyIdentityList); } } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } /** * * Retrieves the filter for the getAvailableIdentities and getMyIdentities * calls. * * @return The identities filter in form of a bundle. * */ private Bundle getIdentitiesFilter() { Bundle b = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); l.add(IdentityCapability.CapabilityID.get_own_status.name()); b.putStringArrayList("capability", l); return b; } @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } /** * Generate Map containing String capability filters for m supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, List<String>> prepareStringFilter(Bundle filter) { Map<String, List<String>> returnFilter = null; if (filter != null && filter.keySet().size() > 0) { returnFilter = new Hashtable<String, List<String>>(); for (String key : filter.keySet()) { returnFilter.put(key, filter.getStringArrayList(key)); } } else { returnFilter = null; } return returnFilter; } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ /** {@inheritDoc} */ @Override public final void onReset() { super.onReset(); mMyIdentityList.clear(); mAvailableIdentityList.clear(); mStatusList.clear(); mState = State.IDLE; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of Identity objects, can be NULL. * @return TRUE if the given Identity contains a Facebook account. */ public boolean isFacebookInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_FACEBOOK)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given Identity contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given Identity contains a Hyves account. */ public boolean isHyvesInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_HYVES)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Hyves not found in list"); return false; } }
360/360-Engine-for-Android
792bec303c0c3cd1737f7c2dac4adddb76fc43e1
PAND-2356. Log original chat message userID.
diff --git a/src/com/vodafone360/people/engine/presence/ChatDbUtils.java b/src/com/vodafone360/people/engine/presence/ChatDbUtils.java index 4c44453..a33b6df 100644 --- a/src/com/vodafone360/people/engine/presence/ChatDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/ChatDbUtils.java @@ -1,263 +1,267 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.database.sqlite.SQLiteDatabase; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ActivitiesTable; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineNativeTypes; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.database.tables.ContactDetailsTable; import com.vodafone360.people.database.tables.ContactSummaryTable; import com.vodafone360.people.database.tables.ContactsTable; import com.vodafone360.people.database.tables.ConversationsTable; import com.vodafone360.people.datatypes.ActivityItem; import com.vodafone360.people.datatypes.ChatMessage; import com.vodafone360.people.datatypes.ContactDetail; import com.vodafone360.people.datatypes.ContactDetail.DetailKeys; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.LogUtils; public class ChatDbUtils { protected static final String COLUMNS = "::"; protected static void convertUserIds(ChatMessage msg, DatabaseHelper databaseHelper) { - String userId = msg.getUserId(); - String network = SocialNetwork.VODAFONE.name(); + + String userId = msg.getUserId(); + String network = SocialNetwork.VODAFONE.name(); + + // TODO: PAND-2356: log original userID, in case of NumberFormatException + String originalUserId = userId; + int columnsIndex = userId.indexOf(COLUMNS); if (columnsIndex > -1) { network = userId.substring(0, columnsIndex); userId = userId.substring(columnsIndex + COLUMNS.length()); } SocialNetwork sn = SocialNetwork.getValue(network); if (sn != null) { msg.setNetworkId(sn.ordinal()); } else { throw new RuntimeException("ChatUtils.convertUserIds: Invalid network : " + network); } msg.setUserId(userId); int networkId = msg.getNetworkId(); if (networkId == SocialNetwork.VODAFONE.ordinal()) { try { Long id = Long.valueOf(msg.getUserId()); msg.setLocalContactId(ContactsTable.fetchLocalIdFromUserId(id, databaseHelper.getReadableDatabase())); } catch (NumberFormatException e) { - LogUtils.logE("ChatDbUtils.convertUserIds() " - + " Invalid vodafone userid: " + msg.getUserId()); + LogUtils.logE("ChatDbUtils.convertUserIds() Original userid: " + originalUserId); } } else { msg.setLocalContactId(ContactDetailsTable.findLocalContactIdByKey(SocialNetwork .getChatValue(networkId).toString(), msg.getUserId(), ContactDetail.DetailKeys.VCARD_IMADDRESS, databaseHelper .getReadableDatabase())); } } /** * This method saves the supplied * * @param msg * @param type * @param databaseHelper */ protected static void saveChatMessageAsATimeline(ChatMessage message, TimelineSummaryItem.Type type, DatabaseHelper databaseHelper) { TimelineSummaryItem item = new TimelineSummaryItem(); fillInContactDetails(message, item, databaseHelper, type); SQLiteDatabase writableDatabase = databaseHelper.getWritableDatabase(); boolean isRead = true; if(type == TimelineSummaryItem.Type.INCOMING) { isRead = false; } if (ActivitiesTable.addChatTimelineEvent(item, isRead, writableDatabase) != -1) { ConversationsTable.addNewConversationId(message, writableDatabase); } else { LogUtils.logE("The msg was not saved to the ActivitiesTable"); } } /** * Remove hard code * * @param msg * @param item * @param databaseHelper * @param incoming */ private static void fillInContactDetails(ChatMessage msg, TimelineSummaryItem item, DatabaseHelper databaseHelper, TimelineSummaryItem.Type incoming) { item.mTimestamp = System.currentTimeMillis(); // here we set the time stamp back into the chat message // in order to be able to remove it from the chat history by time stamp in case its delivery fails msg.setTimeStamp(item.mTimestamp); item.mType = ActivityItem.Type.MESSAGE_IM_CONVERSATION; item.mDescription = msg.getBody(); item.mTitle = DateFormat.getDateInstance().format(new Date(item.mTimestamp)); // we store sender's localContactId for incoming msgs and recipient's // localContactId for outgoing msgs item.mLocalContactId = msg.getLocalContactId(); if (item.mLocalContactId != null && item.mLocalContactId != -1) { ContactDetail cd = ContactDetailsTable.fetchDetail(item.mLocalContactId, DetailKeys.VCARD_NAME, databaseHelper.getReadableDatabase()); if (cd == null || cd.getName() == null) { // if we don't get any details, we have to check the summary // table because gtalk contacts // without name will be otherwise show as unknown ContactSummary contactSummary = new ContactSummary(); ServiceStatus error = ContactSummaryTable.fetchSummaryItem(item.mLocalContactId, contactSummary, databaseHelper.getReadableDatabase()); if (error == ServiceStatus.SUCCESS) { item.mContactName = (contactSummary.formattedName != null) ? contactSummary.formattedName : ContactDetail.UNKNOWN_NAME; } else { item.mContactName = ContactDetail.UNKNOWN_NAME; } } else { /** Get name from contact details. **/ VCardHelper.Name name = cd.getName(); item.mContactName = (name != null) ? name.toString() : ContactDetail.UNKNOWN_NAME; } } item.mIncoming = incoming; item.mContactNetwork = SocialNetwork.getChatValue(msg.getNetworkId()).toString(); item.mNativeItemType = TimelineNativeTypes.ChatLog.ordinal(); } /** * This method copies the conversation id and user id into the supplied * ChatMessage based on its mNetworkId and mLocalContactId * * @param chatMessage ChatMessage * @param databaseHelper Databasehelper */ protected static void fillMessageByLocalContactIdAndNetworkId(ChatMessage chatMessage, DatabaseHelper databaseHelper) { ConversationsTable.fillMessageInByLocalContactIdAndNetworkId(chatMessage, databaseHelper .getReadableDatabase(), databaseHelper.getWritableDatabase()); } /** * This method finds the user id (360 UserId or 3rd-party network id) and * sets it into the supplied chat message * * @param msg ChatMessage - the supplied chat message * @param databaseHelper DatabaseHelper - the database */ protected static void findUserIdForMessageByLocalContactIdAndNetworkId(ChatMessage msg, DatabaseHelper databaseHelper) { List<String> tos = new ArrayList<String>(); if (msg.getNetworkId() == SocialNetwork.VODAFONE.ordinal()) { msg.setUserId(String.valueOf(ContactsTable.fetchUserIdFromLocalContactId(msg .getLocalContactId(), databaseHelper.getReadableDatabase()))); tos.add(msg.getUserId()); } else { msg.setUserId(ContactDetailsTable.findChatIdByLocalContactIdAndNetwork(SocialNetwork .getChatValue(msg.getNetworkId()).toString(), msg.getLocalContactId(), databaseHelper.getReadableDatabase())); String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + COLUMNS + msg.getUserId(); tos.add(fullUserId); msg.setUserId(fullUserId); } msg.setTos(tos); } /** * This method deletes the conversation with the given id from the * ConversationsTable * * @param conversationId String - the conversation id * @param dbHelper DatabaseHelper - the database */ protected static void deleteConversationById(String conversationId, DatabaseHelper dbHelper) { ConversationsTable.removeConversation(conversationId, dbHelper.getWritableDatabase()); } /** * This method deletes conversations older than 1 week except for those with * current contact * * @param localContactId long- current contact mLocalContactId * @param dbHelper DatabaseHelper - the database */ protected static void cleanOldConversationsExceptForContact(long localContactId, DatabaseHelper dbHelper) { ActivitiesTable.removeChatTimelineExceptForContact(localContactId, dbHelper .getWritableDatabase()); } /** * This method returns the number of unread chat messages for this contact * * @param localContactId long - the contact's mLocalContactId * @param network String - the specified network, @see SocialNetwork * @param dbHelper Database - the database * @return int - the number of unread chat messages for the specified * contact */ public static int getNumberOfUnreadChatMessagesForContactAndNetwork(long localContactId, String network, DatabaseHelper dbHelper) { return ActivitiesTable.getNumberOfUnreadChatMessagesForContactAndNetwork(localContactId, network, dbHelper.getReadableDatabase()); } /** * This method deletes the last outgoing chat message in * ActivitiesTable, and removes the conversation id of this message from the * ConversationsTable. So that next time when user tries to send a message a * new conversation id will be requested. The message sending might fail * because the conversation id might have expired. * * Currently there's no reliable way to get the reason of message delivery failure, so * we assume that an expired conversation id might cause it as well, and remove it. * * In case the conversation id is valid the "get conversation" call will return the old id. * * @param dbHelper DatabaseHelper - database * @param message ChatMessage - the chat message which has not been sent and needs to be deleted from the history. */ protected static void deleteUnsentMessage(DatabaseHelper dbHelper, ChatMessage message) { ConversationsTable.removeConversation(message.getConversationId(), dbHelper.getWritableDatabase()); ActivitiesTable.deleteUnsentChatMessageForContact(message.getLocalContactId(), message.getTimeStamp(), dbHelper.getWritableDatabase()); } }
360/360-Engine-for-Android
4f2b92af07d42f323da701f232e0b2e91746a854
PAND-2390
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 9999a4f..f7fee47 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -360,534 +360,532 @@ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ synchronized public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Method used to set availability of me profile when user logs in. * This is primarily used for reacting to login/connection state changes. */ private void initSetMyAvailabilityRequestAfterLogin() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } String meProfileUserId = Long.toString(PresenceDbUtils.getMeProfileUserId(mDbHelper)); Hashtable<String, String> availability = new Hashtable<String, String>(); ArrayList<Identity> identityList = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if ((identityList.size() != 0)) { for (int i=0; i<identityList.size(); i++) { Identity myIdentity = identityList.get(i); availability.put(myIdentity.mNetwork, OnlineStatus.ONLINE.toString()); } } User meUser = new User(); meUser.setLocalContactId(Long.valueOf(meProfileUserId)); meUser.setPayload(presenceList); updateMyPresenceInDatabase(meUser); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } // Get presences Hashtable<String, String> presenceList = getPresencesForStatus(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** * Changes the user's availability. * * @param status - Hashtable<String, String> of pairs <communityName, statusName>. */ public void setMyAvailability(Hashtable<String, String> presenceHash) { if (presenceHash == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceHash); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } /** * Changes the user's availability. * * @param network - SocialNetwork to set presence on. * @param status - OnlineStatus presence status to set. */ public void setMyAvailability(SocialNetwork network, OnlineStatus status) { LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+ network + "=" + status); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); final NetworkPresence newPresence = new NetworkPresence(userId, network.ordinal(), status.ordinal()); presenceList.add(newPresence); User me = new User(userId, null); me.setPayload(presenceList); MePresenceCacheTable.updateCache(newPresence, mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now Hashtable<String, String> presenceHash = new Hashtable<String, String>(); presenceHash.put(network.toString(), status.toString()); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } @Override public void onConnectionStateChanged(int state) { if (mLoggedIn && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initializeAvailabilityFromDb(); break; case STATE_CONNECTING: case STATE_DISCONNECTED: mFirstRun = true; setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * Initializes or re-initializes availability from the Database. * If there are cached presences then these will be used * instead of values from the presence table. */ private void initializeAvailabilityFromDb() { final User user = getMyAvailabilityStatusFromDatabase(); ArrayList<NetworkPresence> cachedPresences = MePresenceCacheTable.getCache(mDbHelper.getReadableDatabase()); if(cachedPresences != null) { user.setPayload(cachedPresences); } initSetMyAvailabilityRequest(user); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if (identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); for (Identity identity : identities) { - presences.put(identity.mNetwork, status.equals(OnlineStatus.INVISIBLE)? - (identity.mNetwork.trim().equals(SocialNetwork.MOBILE.toString())? statusString: OnlineStatus.OFFLINE.toString()) - :statusString); + presences.put(identity.mNetwork, statusString); } return presences; } @Override public void onReset() { // reset the engine as if it was just created super.onReset(); mFirstRun = true; mLoggedIn = false; mIterations = 0; mState = IDLE; mUsers = null; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } }
360/360-Engine-for-Android
89d72b5eb3e018557be2c30beea35ab437fda3fa
PAND-2389 followed up the code review
diff --git a/src/com/vodafone360/people/Settings.java b/src/com/vodafone360/people/Settings.java index 0f20281..b92aec8 100644 --- a/src/com/vodafone360/people/Settings.java +++ b/src/com/vodafone360/people/Settings.java @@ -1,307 +1,306 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; /** * All application settings. */ public final class Settings { /* * LogCat. */ /** LogCat TAG prefix. **/ public static final String LOG_TAG = "People_"; /* * Transport. */ /** Milliseconds until HTTP connection will time out. */ public static final int HTTP_CONNECTION_TIMEOUT = 30000; /** Maximum number of HTTP connection attempts. */ public static final int HTTP_MAX_RETRY_COUNT = 3; /** HTTP header content type. */ public static final String HTTP_HEADER_CONTENT_TYPE = "application/binary"; /** Number of empty RPG poll responses before stopping RPG poll. */ public static final int BLANK_RPG_HEADER_COUNT = 4; /** TCP Heartbeat interval (10 seconds). */ public static final long TCP_VF_HEARTBEAT_INTERVAL = 10 * 60 * 1000; /** TCP retry interval if we have lost the connection (30 seconds). */ public static final long TCP_RETRY_BROKEN_CONNECTION_INTERVAL = 30 * 60 * 1000; /** TCP socket read time out for the read-operation. */ public static final int TCP_SOCKET_READ_TIMEOUT = 10 * 60 * 1000; /* * Notifications. */ /** LED colour. */ public static final int NOTIFICATION_LED_COLOR = 0xff00ff00; // Green /** LED on time. */ public static final int NOTIFICATION_LED_OFF_TIME = 300; /** LED on time. */ public static final int NOTIFICATION_LED_ON_TIME = 1000; /* * Upgrade Engine */ /** * See UpdateSettingsActivity.FREQUENCY_SETTING_LONG array for meaning (i.e. * Every 6 hours) */ public static final int PREFS_CHECK_FREQUENCY_DEFAULT = 3; /** Show the upgrade dialog box every 10 minutes. */ public static final int DIALOG_CHECK_FREQUENCY_MILLIS = 10 * 60 * 1000; /** * Component trace flags (always checked in as false, not part of build * script). */ /** Trace output for engine components. **/ public static final boolean ENABLED_ENGINE_TRACE = false; /** Trace output for database components. **/ public static final boolean ENABLED_DATABASE_TRACE = false; /** Trace output for contact synchronisation components. **/ public static final boolean ENABLED_CONTACTS_SYNC_TRACE = false; /** Log engine runtime information to file for profiling. **/ public static final boolean ENABLED_PROFILE_ENGINES = false; /** Trace output for protocol (i.e. network IO) components. **/ - public static boolean sEnableProtocolTrace = true; - - + public static boolean sEnableProtocolTrace = false; + /** * This is a list of strings containing the names of engines to be * deactivated in the build. A de-activated engine is constructed but will * never be run (nor will onCreate or onDestroy be called). Any UI requests * will be automatically completed by the framework with a * ServiceStatus.ERROR_NOT_IMPLEMENTED error. */ public static final String DEACTIVATE_ENGINE_LIST_KEY = "deactivated-engines-list"; /* * Hard coded settings */ /** Enable dialler cheat code. **/ public static final boolean DIALER_CHEATCODES_ENABLED = true; /** Enable SMS account activation. **/ public static final boolean ENABLE_ACTIVATION = false; /** * Enable SIM inserted check. Always set to TRUE. Makes the application * unusable if there is no valid SIM card inserted into the device. */ public static final boolean ENABLE_SIM_CHECK = true; /** Enable fetching native contacts. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS = true; /** Enable fetching native contacts on change. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS_ON_CHANGE = true; /** Enable ME profile synchronisation. **/ public static final boolean ENABLE_ME_PROFILE_SYNC = true; /** Enable server contact synchronisation. **/ public static final boolean ENABLE_SERVER_CONTACT_SYNC = true; /** Enable server thumbnail synchronisation. **/ public static final boolean ENABLE_THUMBNAIL_SYNC = true; /** Enable update native contacts synchronisation. **/ public static final boolean ENABLE_UPDATE_NATIVE_CONTACTS = true; /** Enable hiding of connected friends group. **/ public static final boolean HIDE_CONNECTED_FRIENDS_GROUP = true; /** Disable the native sync after the first time import for Android 1.X devices only **/ public static final boolean DISABLE_NATIVE_SYNC_AFTER_IMPORT_ON_ANDROID_1X = true; /* * Keys for properties that can be changed at build time. */ /** Key for application ID setting. **/ public static final String APP_KEY_ID = "app-key-id"; /** Key for application secret key setting. **/ public static final String APP_SECRET_KEY = "app-secret-key"; /** Key for enable logging setting. **/ protected static final String ENABLE_LOGCAT_KEY = "enable-logcat"; /** Key for enable RPG setting. **/ public static final String ENABLE_RPG_KEY = "use-rpg"; /** Key for enable SNS resource icon setting. **/ public static final String ENABLE_SNS_RESOURCE_ICON_KEY = "enable-sns-resource-icon"; /** Key for RPG server URL setting. **/ public static final String RPG_SERVER_KEY = "rpg-url"; /** Key for Hessian URL setting. **/ public static final String SERVER_URL_HESSIAN_KEY = "hessian-url"; /** Key for enabling 3rd party applications to access data via AIDL. **/ public static final String ENABLE_AIDL_KEY = "allow-aidl"; /** Default setting ENABLE_AIDL_KEY. **/ public static final String ENABLE_AIDL_DEFAULT = "false"; /* * Keys without defaults. */ /** Key for TCP server URL setting. **/ public static final String TCP_RPG_URL_KEY = "rpg-tcp-url"; /** Key for TCP port setting. **/ public static final String TCP_RPG_PORT_KEY = "rpg-tcp-port"; /** Key for upgrade check URL setting. **/ public static final String UPGRADE_CHECK_URL_KEY = "upgrade-url"; /* * Default for properties that can be changed at build time. */ /** Default for logging enabled setting. **/ protected static final String DEFAULT_ENABLE_LOGCAT = "true"; /** Default for RPG enabled setting. **/ protected static final String DEFAULT_ENABLE_RPG = "true"; /** Default for SNS resource icon setting. **/ protected static final String DEFAULT_ENABLE_SNS_RESOURCE_ICON = "true"; /** Default for RPG server URL setting. **/ protected static final String DEFAULT_RPG_SERVER = "http://rpg.vodafone360.com/rpg/mcomet/"; /** Default for Hessian URL setting. **/ protected static final String DEFAULT_SERVER_URL_HESSIAN = "http://api.vodafone360.com/services/hessian/"; /* * Request timeouts for all engines and requests, except for fire and * forget calls to RPG: SET_AVAILABILITY and SEND_CHAT_MSG. */ /** Do not handle timeouts for this API. **/ private static final long DONT_HANDLE_TIMEOUTS = -1; /** Generic timeout for requests. **/ private static final long ALL_ENGINES_REQUESTS_TIMEOUT = 60000; /** Timeout for all presence API requests. **/ private static final long PRESENCE_ENGINE_REQUESTS_TIMEOUT = 120000; /** Number of milliseconds in a week. **/ public static final long HISTORY_IS_WEEK_LONG = 7 * 24 * 60 * 60 * 1000; /** Timeout for request waiting in queue. **/ public static final long REMOVE_REQUEST_FROM_QUEUE_MILLIS = 15 * 60 * 1000; /* * The timeouts in milliseconds for the different APIs. */ /** Timeout for activities API. **/ public static final long API_REQUESTS_TIMEOUT_ACTIVITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for authentication API. **/ public static final long API_REQUESTS_TIMEOUT_AUTH = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat create conversation API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_CREATE_CONV = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat send message API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_SEND_MESSAGE = DONT_HANDLE_TIMEOUTS; /** Timeout for contacts API. **/ public static final long API_REQUESTS_TIMEOUT_CONTACTS = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for group privacy API. **/ public static final long API_REQUESTS_TIMEOUT_GROUP_PRIVACY = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for identities API. **/ public static final long API_REQUESTS_TIMEOUT_IDENTITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for presence list API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_LIST = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Timeout for presence set availability API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Enable Facebook chat. **/ public static boolean sEnableFacebookChat = true; /** * Danger! Only set to true if you know what you are doing! This logs each * response no matter if gzipped or not to the SD card under the given * request ID. */ public static boolean sEnableSuperExpensiveResponseFileLogging = false; /** * Private constructor to prevent instantiation. */ private Settings() { } /** * a debug flag to see what's coming with availability state change push messages. */ public static boolean LOG_PRESENCE_PUSH_ON_LOGCAT = false; } \ No newline at end of file diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index cd70c2d..9fffe3e 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -135,837 +135,835 @@ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener private String mNetwork; /** IdentityID which needs to be Deleted.*/ private String mIdentityId; } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mMyIdentityList; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; /** * Maintaining DeleteIdentityRequest so that it can be later removed from * maintained cache. **/ private DeleteIdentityRequest identityToBeDeleted; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; mMyIdentityList = new ArrayList<Identity>(); mAvailableIdentityList = new ArrayList<Identity>(); mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { final ArrayList<Identity> availableIdentityList; synchronized(mAvailableIdentityList) { // make a shallow copy availableIdentityList = new ArrayList<Identity>(mAvailableIdentityList); } if ((availableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return availableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { final ArrayList<Identity> myIdentityList; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } if ((myIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return myIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = getMyThirdPartyChattableIdentities(); // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chattableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chattableIdentities; } /** * * Takes all third party identities that have a chat capability set to true. * * @return A list of chattable 3rd party identities the user is signed in to. If the retrieval identities failed the returned list will be empty. * */ public ArrayList<Identity> getMyThirdPartyChattableIdentities() { final ArrayList<Identity> chattableIdentities = new ArrayList<Identity>(); final ArrayList<Identity> myIdentityList; final int identityListSize; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } identityListSize = myIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = myIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue)) { chattableIdentities.add(identity); break; } } } return chattableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Delete the given social network. * * @param network Name of the identity, * @param identityId Id of identity. */ public final void addUiDeleteIdentityRequest(final String network, final String identityId) { LogUtils.logD("IdentityEngine.addUiRemoveIdentity()"); DeleteIdentityRequest data = new DeleteIdentityRequest(); data.mNetwork = network; data.mIdentityId = identityId; /**maintaining the sent object*/ setIdentityToBeDeleted(data); addUiRequestToQueue(ServiceUiRequest.DELETE_IDENTITY, data); } /** * Setting the DeleteIdentityRequest object. * * @param data */ private void setIdentityToBeDeleted(final DeleteIdentityRequest data) { identityToBeDeleted = data; } /** * Return the DeleteIdentityRequest object. * */ private DeleteIdentityRequest getIdentityToBeDeleted() { return identityToBeDeleted; } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; case DELETE_IDENTITY: executeDeleteIdentityRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to delete the identity as specified . (Request is not issued if there * is currently no connectivity). * * @param data bundled request data containing network and identityId. */ private void executeDeleteIdentityRequest(final Object data) { if (!isConnected()) { completeUiRequest(ServiceStatus.ERROR_NO_INTERNET); } newState(State.DELETE_IDENTITY); DeleteIdentityRequest reqData = (DeleteIdentityRequest) data; if (!setReqId(Identities.deleteIdentity(this, reqData.mNetwork, reqData.mIdentityId))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(DecodedResponse resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if ((null == resp) || (null == resp.mDataTypes)) { LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); return; } // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; case BaseDataType.IDENTITY_DELETION_DATA_TYPE: handleDeleteIdentity(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); } } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { - // check if any chat identities were added to set them to "online" + mMyIdentityList.clear(); for (BaseDataType item : data) { Identity identity = (Identity)item; mMyIdentityList.add(identity); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); - - - + LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response of request to delete the identity. The response * should be a status that whether the operation is succeeded or not. The * response will be a status result otherwise ERROR_UNEXPECTED_RESPONSE if * the response is not as expected. * * @param data * List of BaseDataTypes generated from Server response. */ private void handleDeleteIdentity(final List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus( BaseDataType.IDENTITY_DELETION_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { for (BaseDataType item : data) { if (item.getType() == BaseDataType.IDENTITY_DELETION_DATA_TYPE) { synchronized(mMyIdentityList) { // iterating through the subscribed identities for (Identity identity : mMyIdentityList) { if (identity.mIdentityId .equals(getIdentityToBeDeleted().mIdentityId)) { mMyIdentityList.remove(identity); break; } } } completeUiRequest(ServiceStatus.SUCCESS); return; } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } } completeUiRequest(errorStatus, bu); } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; synchronized (mAvailableIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mAvailableIdentityList); } } else { requestKey = KEY_MY_IDS; synchronized (mMyIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mMyIdentityList); } } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } /** * * Retrieves the filter for the getAvailableIdentities and getMyIdentities * calls. * * @return The identities filter in form of a bundle. * */ private Bundle getIdentitiesFilter() { Bundle b = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); l.add(IdentityCapability.CapabilityID.get_own_status.name()); b.putStringArrayList("capability", l); return b; } @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } /** * Generate Map containing String capability filters for m supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, List<String>> prepareStringFilter(Bundle filter) { Map<String, List<String>> returnFilter = null; if (filter != null && filter.keySet().size() > 0) { returnFilter = new Hashtable<String, List<String>>(); for (String key : filter.keySet()) { returnFilter.put(key, filter.getStringArrayList(key)); } } else { returnFilter = null; } return returnFilter; } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ /** {@inheritDoc} */ @Override public final void onReset() { super.onReset(); mMyIdentityList.clear(); mAvailableIdentityList.clear(); mStatusList.clear(); mState = State.IDLE; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of Identity objects, can be NULL. * @return TRUE if the given Identity contains a Facebook account. */ public boolean isFacebookInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_FACEBOOK)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given Identity contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given Identity contains a Hyves account. */ public boolean isHyvesInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_HYVES)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Hyves not found in list"); return false; } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index b9c86ed..486902f 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -112,780 +112,777 @@ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, **/ private int mIterations = 0; /** * True if the engine runs for the 1st time. */ private boolean mFirstRun = true; /** * * @param eventCallback * @param databaseHelper */ public PresenceEngine(IEngineEventCallback eventCallback, DatabaseHelper databaseHelper) { super(eventCallback); mEngineId = EngineId.PRESENCE_ENGINE; mDbHelper = databaseHelper; mSendMessagesHash = new Hashtable<String, ChatMessage>(); mFailedMessagesList = new ArrayList<TimelineSummaryItem>(); } @Override public void onCreate() { } @Override public void onDestroy() { if (mDbHelper != null && SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper) != null) { PresenceDbUtils.resetPresenceStatesAcceptForMe(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), mDbHelper); } EngineManager.getInstance().getLoginEngine().removeListener(this); } /** * Checks if the SyncMe and ContactSync Engines have both completed first time sync. * * @return true if both engines have completed first time sync */ private boolean isFirstTimeSyncComplete() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!isFirstTimeSyncComplete()) { LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"); return -1; } /** * need isUiRequestOutstanding() because currently the worker thread is * running and finishing before PresenceEngine.setNextRuntime is called */ if (isCommsResponseOutstanding() || isUiRequestOutstanding()) { LogUtils.logV("PresenceEngine getNextRunTime() comms response outstanding"); return 0; } if (mFirstRun) { getPresenceList(); initSetMyAvailabilityRequestAfterLogin(); mFirstRun = false; } return getCurrentTimeout(); } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + getCurrentTimeout() + "]"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logV("PresenceEngine.run() handled processCommsInQueue()"); return; } if (processTimeout()) { LogUtils.logV("PresenceEngine.run() handled processTimeout()"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logV("PresenceEngine.run(): AgentState.DISCONNECTED"); setPresenceOffline(); } /** * and the getNextRunTime must check the uiRequestReady() function and * return 0 if it is true */ if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { return isUiRequestOutstanding(); } private User getMyAvailabilityStatusFromDatabase() { return PresenceDbUtils.getMeProfilePresenceStatus(mDbHelper); } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (!mLoggedIn) { mFirstRun = true; mFailedMessagesList.clear(); mSendMessagesHash.clear(); setPresenceOffline(); } } /*** * Set the Global presence status to offline. */ private synchronized void setPresenceOffline() { PresenceDbUtils.setPresenceOfflineInDatabase(mDbHelper); // We clear the mUsers of any pending presence updates because this // Offline presence update request should take the highest priority. mUsers = null; mState = IDLE; mEventCallback.getUiAgent().updatePresence(UiAgent.ALL_USERS); } @Override protected void onRequestComplete() { LogUtils.logI("PresenceEngine.onRequestComplete()"); } @Override protected void onTimeoutEvent() { LogUtils.logI("PresenceEngine.onTimeoutEvent()"); switch (mState) { case UPDATE_PROCESSING_GOING_ON: updatePresenceDatabaseNextPage(); break; case IDLE: default: if (mLoggedIn) { if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setTimeout(CHECK_FREQUENCY); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); setTimeout(CHECK_FREQUENCY / 20); } } break; } } @Override protected void processCommsResponse(DecodedResponse resp) { handleServerResponse(resp.mDataTypes); } private void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg) { UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribedWithChat()) { uiAgent.sendUnsolicitedUiEvent(errorEvent, null); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users List of users that require updating. */ private synchronized void updatePresenceDatabase(List<User> users) { if (users == null || users.size() == 0) { LogUtils.logW("PresenceEngine.updatePresenceDatabase() users is NULL or zero size"); } else { if (mUsers == null) { mUsers = users; } else { // Doing an add one by one is not an efficient way but then // there is an issue in the addAll API. It crashes sometimes. // And the java code for the AddAll API seems to be erroneous. // More investigation is needed on this. for (User user : users) { mUsers.add(user); } } } mState = UPDATE_PROCESSING_GOING_ON; updatePresenceDatabaseNextPage(); } /** * This API makes the presence updates in pages of 10 with a timeout * after each page. The HandlerAgent is notified after every 10 pages. */ private synchronized void updatePresenceDatabaseNextPage(){ UiAgent uiAgent = mEventCallback.getUiAgent(); if(mUsers == null){ mState = IDLE; return; } int listSize = mUsers.size(); int start = 0; int end = UPDATE_PRESENCE_PAGE_SIZE; if(listSize == 0){ mState = IDLE; mUsers = null; return; } else if(listSize < end) { end = listSize; } List<User> userSubset = mUsers.subList(start, end); if ((userSubset != null)) { long idListeningTo = UiAgent.ALL_USERS; if (uiAgent != null) { idListeningTo = uiAgent.getLocalContactId(); } boolean updateUI = PresenceDbUtils.updateDatabase(userSubset, idListeningTo, mDbHelper); userSubset.clear(); // Send the update notification to UI for every UPDATE_PRESENCE_PAGE_SIZE*NOTIFY_AGENT_PAGE_INTERVAL updates. if (updateUI) { if (mUsers.size() == 0 || NOTIFY_AGENT_PAGE_INTERVAL == mIterations) { if (uiAgent != null) { uiAgent.updatePresence(idListeningTo); } mIterations = 0; } else { mIterations++; } } this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ synchronized public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Method used to set availability of me profile when user logs in. * This is primarily used for reacting to login/connection state changes. */ private void initSetMyAvailabilityRequestAfterLogin() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } String meProfileUserId = Long.toString(PresenceDbUtils.getMeProfileUserId(mDbHelper)); Hashtable<String, String> availability = new Hashtable<String, String>(); ArrayList<Identity> identityList = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); - ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if ((identityList.size() != 0)) { for (int i=0; i<identityList.size(); i++) { Identity myIdentity = identityList.get(i); availability.put(myIdentity.mNetwork, OnlineStatus.ONLINE.toString()); } } - User meUser = new User(); + User meUser = new User(meProfileUserId, availability); meUser.setLocalContactId(Long.valueOf(meProfileUserId)); - meUser.setPayload(presenceList); updateMyPresenceInDatabase(meUser); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } // Get presences Hashtable<String, String> presenceList = getPresencesForStatus(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** * Changes the user's availability. * * @param status - Hashtable<String, String> of pairs <communityName, statusName>. */ public void setMyAvailability(Hashtable<String, String> presenceHash) { if (presenceHash == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceHash); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } /** * Changes the user's availability. * * @param network - SocialNetwork to set presence on. * @param status - OnlineStatus presence status to set. */ public void setMyAvailability(SocialNetwork network, OnlineStatus status) { LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+ network + "=" + status); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); final NetworkPresence newPresence = new NetworkPresence(userId, network.ordinal(), status.ordinal()); presenceList.add(newPresence); User me = new User(userId, null); me.setPayload(presenceList); MePresenceCacheTable.updateCache(newPresence, mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now Hashtable<String, String> presenceHash = new Hashtable<String, String>(); presenceHash.put(network.toString(), status.toString()); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } @Override public void onConnectionStateChanged(int state) { if (mLoggedIn && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initializeAvailabilityFromDb(); break; case STATE_CONNECTING: case STATE_DISCONNECTED: - mFirstRun = true; setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * Initializes or re-initializes availability from the Database. * If there are cached presences then these will be used * instead of values from the presence table. */ private void initializeAvailabilityFromDb() { final User user = getMyAvailabilityStatusFromDatabase(); ArrayList<NetworkPresence> cachedPresences = MePresenceCacheTable.getCache(mDbHelper.getReadableDatabase()); if(cachedPresences != null) { user.setPayload(cachedPresences); } initSetMyAvailabilityRequest(user); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if(identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); for(Identity identity : identities) { presences.put(identity.mNetwork, statusString); } return presences; } @Override public void onReset() { // reset the engine as if it was just created super.onReset(); mFirstRun = true; mLoggedIn = false; mIterations = 0; mState = IDLE; mUsers = null; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java index 5ad8fc5..9ab10cc 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,449 +1,449 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.interfaces; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import android.os.Bundle; import android.os.Handler; import android.os.Message; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.MainApplication; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.agent.NetworkAgentState; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.utils.LogUtils; /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback * @see com.vodafone360.people.service.interfaces.IPeopleService */ public class IPeopleServiceImpl implements IPeopleService, IEngineEventCallback { private final List<Handler> mUiEventCallbackList = new ArrayList<Handler>(); private IWorkerThreadControl mWorkerThreadControl; private RemoteService mService; private NetworkAgent mNetworkAgent; private UiAgent mHandlerAgent; private ApplicationCache mApplicationCache; /** * Initialises the object, creating the UiAgent. * * @param workerThreadControl Provides access to worker thread control * functions. * @param service Provides access to remote service functions (mainly used * to retrieve context). */ public IPeopleServiceImpl(IWorkerThreadControl workerThreadControl, RemoteService service) { mWorkerThreadControl = workerThreadControl; mService = service; mHandlerAgent = new UiAgent((MainApplication)service.getApplication(), service); mApplicationCache = ((MainApplication)service.getApplication()).getCache(); } /*** * Sets the ServiceAgent, as this needs to be called after the constructor. * * @param agent Handle to ServiceAgent. */ public void setNetworkAgent(NetworkAgent agent) { mNetworkAgent = agent; } /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#onUiEvent(UiEvent, * int, int, Object) */ @Override public void onUiEvent(ServiceUiRequest event, int arg1, int arg2, Object data) { synchronized (mUiEventCallbackList) { for (Handler handler : mUiEventCallbackList) { Message msg = handler.obtainMessage(event.ordinal(), data); msg.arg1 = arg1; msg.arg2 = arg2; if (!handler.sendMessage(msg)) { LogUtils.logE("IPeopleServiceImpl.onUiEvent() Sending msg FAILED"); } } } } /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#kickWorkerThread() */ @Override public void kickWorkerThread() { mWorkerThreadControl.kickWorkerThread(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#addEventCallback(Handler) */ @Override public void addEventCallback(Handler uiHandler) { synchronized (mUiEventCallbackList) { if (!mUiEventCallbackList.contains(uiHandler)) { mUiEventCallbackList.add(uiHandler); } } } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#removeEventCallback(Handler) */ @Override public void removeEventCallback(Handler uiHandler) { synchronized (mUiEventCallbackList) { mUiEventCallbackList.remove(uiHandler); } } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#checkForUpdates() */ @Override public void checkForUpdates() { EngineManager.getInstance().getUpgradeEngine().checkForUpdates(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMyThirdPartyIdentities() */ public ArrayList<Identity> getMyThirdPartyIdentities() { return EngineManager.getInstance().getIdentityEngine().getMyThirdPartyIdentities(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyIdentities() */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { return EngineManager.getInstance().getIdentityEngine().getAvailableThirdPartyIdentities(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyChattableIdentities() */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { return EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchPrivacyStatement() */ @Override public void fetchPrivacyStatement() { EngineManager.getInstance().getLoginEngine().addUiFetchPrivacyStatementRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchTermsOfService() */ @Override public void fetchTermsOfService() { EngineManager.getInstance().getLoginEngine().addUiFetchTermsOfServiceRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchUsernameState(String) */ @Override public void fetchUsernameState(String userName) { EngineManager.getInstance().getLoginEngine().addUiGetUsernameStateRequest(userName); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getLoginRequired() */ @Override public boolean getLoginRequired() { EngineManager manager = EngineManager.getInstance(); return manager.getLoginEngine().getLoginRequired(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getRoamingNotificationType() */ @Override public int getRoamingNotificationType() { return mService.getNetworkAgent().getRoamingNotificationType(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getRoamingDeviceSetting() */ @Override public boolean getRoamingDeviceSetting() { return mService.getNetworkAgent().getRoamingDeviceSetting(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#notifyDataSettingChanged(InternetAvail) */ @Override public void notifyDataSettingChanged(InternetAvail val) { mService.getNetworkAgent().notifyDataSettingChanged(val); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#logon(LoginDetails) */ @Override public void logon(LoginDetails loginDetails) { EngineManager manager = EngineManager.getInstance(); manager.getLoginEngine().addUiLoginRequest(loginDetails); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#register(RegistrationDetails) */ @Override public void register(RegistrationDetails details) { EngineManager.getInstance().getLoginEngine().addUiRegistrationRequest(details); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setNewUpdateFrequency() */ @Override public void setNewUpdateFrequency() { EngineManager.getInstance().getUpgradeEngine().setNewUpdateFrequency(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setShowRoamingNotificationAgain(boolean) */ @Override public void setShowRoamingNotificationAgain(boolean showAgain) { mService.getNetworkAgent().setShowRoamingNotificationAgain(showAgain); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startContactSync() */ @Override public void startContactSync() { EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); EngineManager.getInstance().getContactSyncEngine().addUiStartFullSync(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startBackgroundContactSync(long) */ @Override public void startBackgroundContactSync(long delay) { EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); EngineManager.getInstance().getContactSyncEngine().addUiStartServerSync(delay); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#pingUserActivity() */ @Override public void pingUserActivity() { EngineManager.getInstance().getContactSyncEngine().pingUserActivity(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#validateIdentityCredentials(boolean, * String, String, String, Bundle) */ @Override public void validateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { EngineManager.getInstance().getIdentityEngine().addUiValidateIdentityCredentials(dryRun, network, username, password, identityCapabilityStatus); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startStatusesSync() */ @Override public void startStatusesSync() { EngineManager.getInstance().getActivitiesEngine().addStatusesSyncRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getNetworkAgentState() */ @Override public NetworkAgentState getNetworkAgentState() { return mNetworkAgent.getNetworkAgentState(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setNetowrkAgentState(NetworkAgentState) */ @Override public void setNetworkAgentState(NetworkAgentState state) { mNetworkAgent.setNetworkAgentState(state); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getPresenceList(long) */ @Override public void getPresenceList(long contactId) { -// EngineManager.getInstance().getPresenceEngine().getPresenceList(); + EngineManager.getInstance().getPresenceEngine().getPresenceList(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(OnlineStatus) */ @Override public void setAvailability(OnlineStatus status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(SocialNetwork, OnlineStatus) */ @Override public void setAvailability(SocialNetwork network, OnlineStatus status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(network, status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(Hashtable<String, String> status) */ @Override public void setAvailability(Hashtable<String, String> status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#subscribe(Handler, * long, boolean) */ @Override public void subscribe(Handler handler, Long contactId, boolean chat) { mHandlerAgent.subscribe(handler, contactId, chat); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#unsubscribe(Handler) */ @Override public void unsubscribe(Handler handler) { mHandlerAgent.unsubscribe(handler); } /** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#getUiAgent() */ @Override public UiAgent getUiAgent() { return mHandlerAgent; } /** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#getApplicationCache() */ @Override public ApplicationCache getApplicationCache() { return mApplicationCache; } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#sendMessage(long, * String, int) */ @Override public void sendMessage(long localContactId, String body, int networkId) { EngineManager.getInstance().getPresenceEngine() .sendMessage(localContactId, body, networkId); } @Override public void setIdentityStatus(String network, String identityId, boolean identityStatus) { EngineManager.getInstance().getIdentityEngine().addUiSetIdentityStatus(network, identityId, identityStatus); } @Override public void getStatuses() { EngineManager.getInstance().getActivitiesEngine().addStatusesSyncRequest(); } @Override public void getMoreTimelines() { EngineManager.getInstance().getActivitiesEngine().addOlderTimelinesRequest(); } @Override public void getOlderStatuses() { EngineManager.getInstance().getActivitiesEngine().addGetOlderStatusesRequest(); } @Override public void uploadMeProfile() { EngineManager.getInstance().getSyncMeEngine().addUpdateMeProfileContactRequest(); } @Override public void uploadMyStatus(String statusText) { EngineManager.getInstance().getSyncMeEngine().addUpdateMyStatusRequest(statusText); } @Override public void downloadMeProfileFirstTime() { EngineManager.getInstance().getSyncMeEngine().addGetMeProfileContactFirstTimeRequest(); } @Override public void updateChatNotification(long localContactId) { mHandlerAgent.updateChat(localContactId, false); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#deleteIdentity(String,String) */ @Override public void deleteIdentity(final String network, final String identityId) { EngineManager.getInstance().getIdentityEngine() .addUiDeleteIdentityRequest(network, identityId); } } \ No newline at end of file
360/360-Engine-for-Android
7d413d2b80f3c1c33e157a6b6a37671f2eef479a
PAND-2390 send offline for TPCs except for mobile when set the me profile status to invisible
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index e26391d..9999a4f 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -361,533 +361,533 @@ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ synchronized public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Method used to set availability of me profile when user logs in. * This is primarily used for reacting to login/connection state changes. */ private void initSetMyAvailabilityRequestAfterLogin() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } String meProfileUserId = Long.toString(PresenceDbUtils.getMeProfileUserId(mDbHelper)); Hashtable<String, String> availability = new Hashtable<String, String>(); ArrayList<Identity> identityList = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if ((identityList.size() != 0)) { for (int i=0; i<identityList.size(); i++) { Identity myIdentity = identityList.get(i); availability.put(myIdentity.mNetwork, OnlineStatus.ONLINE.toString()); } } User meUser = new User(); meUser.setLocalContactId(Long.valueOf(meProfileUserId)); meUser.setPayload(presenceList); updateMyPresenceInDatabase(meUser); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } // Get presences Hashtable<String, String> presenceList = getPresencesForStatus(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** * Changes the user's availability. * * @param status - Hashtable<String, String> of pairs <communityName, statusName>. */ public void setMyAvailability(Hashtable<String, String> presenceHash) { if (presenceHash == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceHash); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } /** * Changes the user's availability. * * @param network - SocialNetwork to set presence on. * @param status - OnlineStatus presence status to set. */ public void setMyAvailability(SocialNetwork network, OnlineStatus status) { LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+ network + "=" + status); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); final NetworkPresence newPresence = new NetworkPresence(userId, network.ordinal(), status.ordinal()); presenceList.add(newPresence); User me = new User(userId, null); me.setPayload(presenceList); MePresenceCacheTable.updateCache(newPresence, mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now Hashtable<String, String> presenceHash = new Hashtable<String, String>(); presenceHash.put(network.toString(), status.toString()); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } @Override public void onConnectionStateChanged(int state) { if (mLoggedIn && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initializeAvailabilityFromDb(); break; case STATE_CONNECTING: case STATE_DISCONNECTED: mFirstRun = true; setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * Initializes or re-initializes availability from the Database. * If there are cached presences then these will be used * instead of values from the presence table. */ private void initializeAvailabilityFromDb() { final User user = getMyAvailabilityStatusFromDatabase(); ArrayList<NetworkPresence> cachedPresences = MePresenceCacheTable.getCache(mDbHelper.getReadableDatabase()); if(cachedPresences != null) { user.setPayload(cachedPresences); } initSetMyAvailabilityRequest(user); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if (identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); for (Identity identity : identities) { presences.put(identity.mNetwork, status.equals(OnlineStatus.INVISIBLE)? - (identity.mNetwork.trim().equals("mobile")? statusString: OnlineStatus.OFFLINE.toString()) + (identity.mNetwork.trim().equals(SocialNetwork.MOBILE.toString())? statusString: OnlineStatus.OFFLINE.toString()) :statusString); } return presences; } @Override public void onReset() { // reset the engine as if it was just created super.onReset(); mFirstRun = true; mLoggedIn = false; mIterations = 0; mState = IDLE; mUsers = null; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } }
360/360-Engine-for-Android
05bd97b973fb06d261564f7c35419f2622cbd15e
PAND-2266: No SNS notification in other SNS entry opened
diff --git a/src/com/vodafone360/people/engine/presence/NetworkPresence.java b/src/com/vodafone360/people/engine/presence/NetworkPresence.java index cda42d3..2955e13 100644 --- a/src/com/vodafone360/people/engine/presence/NetworkPresence.java +++ b/src/com/vodafone360/people/engine/presence/NetworkPresence.java @@ -1,284 +1,285 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import android.os.Parcel; import android.os.Parcelable; import com.vodafone360.people.utils.ThirdPartyAccount; /** * A wrapper for the user presence state on certain web or IM account */ public class NetworkPresence implements Parcelable { private String mUserId; private int mNetworkId; private int mOnlineStatusId; /** * Constructor with parameters. * * @param mNetworkId - the ordinal of the network name in the overall * hardcoded network list. * @param mOnlineStatusId - the ordinal of user presence status in the * overall hardcoded statuses list specifically for this web * account */ public NetworkPresence(String userId, int networkId, int onlineStatusId) { super(); this.mUserId = userId; this.mNetworkId = networkId; this.mOnlineStatusId = onlineStatusId; } /** * @return the ordinal of the network name on the overall hardcoded network * list. */ public int getNetworkId() { return mNetworkId; } /** * @return the ordinal of the online status name on the overall hardcoded * status list. */ public int getOnlineStatusId() { return mOnlineStatusId; } /** * @return user account name on Nowplus or other social network */ public String getUserId() { return mUserId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mNetworkId; result = prime * result + mOnlineStatusId; result = prime * result + ((mUserId == null) ? 0 : mUserId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NetworkPresence other = (NetworkPresence)obj; if (mNetworkId != other.mNetworkId) return false; if (mOnlineStatusId != other.mOnlineStatusId) return false; if (mUserId == null) { if (other.mUserId != null) return false; } else if (!mUserId.equals(other.mUserId)) return false; return true; } @Override public String toString() { return "NetworkPresence [mNetworkId=" + mNetworkId + ", mOnlineStatusId=" + mOnlineStatusId + ", mUserId=" + mUserId + "]"; } /** * Hard coded networks with enable IM list */ public static enum SocialNetwork implements Parcelable { FACEBOOK_COM("facebook.com"), HYVES_NL("hyves.nl"), GOOGLE("google"), MICROSOFT("microsoft"), MOBILE("mobile"), PC("pc"), - VODAFONE("vodafone"); // the aggregated status for "pc" and "mobile" + VODAFONE("vodafone"), // the aggregated status for "pc" and "mobile" // only used by - UI - Contact Profile View + INVALID("invalid"); private String mSocialNetwork; // / The name of the field as it appears // in the database private SocialNetwork(String field) { mSocialNetwork = field; } @Override public String toString() { return mSocialNetwork; } /** * This method returns the SocialNetwork object based on the underlying string. * @param value - the String containing the SocialNetwork name. * @return SocialNetwork object for the provided string. */ public static SocialNetwork getValue(String value) { try { return valueOf(value.replace('.', '_').toUpperCase()); } catch (Exception e) { return null; } } /** * This method returns the SocialNetwork object based on index in the SocialNetwork enum. * This method should be called to get the SocialNetwork object by networkId * index from {@code}NetworkPresence. * @param index - integer index. * @return SocialNetwork object for the provided index. */ public static SocialNetwork getPresenceValue(int index) { if (index == VODAFONE.ordinal()) return MOBILE; return values()[index]; } /** * This method returns the SocialNetwork object based on index in the SocialNetwork enum. * This method should be called to get the SocialNetwork for a chat network id index. * @param index - integer index. * @return SocialNetwork object for the provided index. */ public static SocialNetwork getChatValue(int index) { if (index == MOBILE.ordinal() || index == PC.ordinal() || index == VODAFONE.ordinal()) return VODAFONE; return values()[index]; } /** * This method returns the SocialNetwork object based on the provided * string. * This method should be called to get the SocialNetwork objects for UI purposes, i.e. * it returns Vodafone rather than MOBILE or PC if "pc" and "mobile" are passed in. * @param index - integer index. * @return SocialNetwork object for the provided underlying string. */ public static SocialNetwork getNetworkBasedOnString(String sns) { if (sns != null) { if (sns.contains(ThirdPartyAccount.SNS_TYPE_FACEBOOK)) { return FACEBOOK_COM; } else if (sns.contains(ThirdPartyAccount.SNS_TYPE_HYVES)) { return HYVES_NL; } else if (ThirdPartyAccount.isWindowsLive(sns)) { return MICROSOFT; } else if (sns.contains(ThirdPartyAccount.SNS_TYPE_GOOGLE)) { return GOOGLE; } else if (sns.contains(ThirdPartyAccount.SNS_TYPE_TWITTER)) { return PC; } else if (ThirdPartyAccount.isVodafone(sns)) { return VODAFONE; } } return null; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(final Parcel dest, final int flags) { dest.writeString(mSocialNetwork); } /*** * Parcelable.Creator for SocialNetwork. */ Parcelable.Creator<SocialNetwork> CREATOR = new Parcelable.Creator<SocialNetwork>() { @Override public SocialNetwork createFromParcel(final Parcel source) { return getNetworkBasedOnString(source.readString()); } @Override public SocialNetwork[] newArray(final int size) { return new SocialNetwork[size]; } }; } @Override public final int describeContents() { return 0; } @Override public final void writeToParcel(final Parcel parcel, final int flags) { parcel.writeString(mUserId); parcel.writeInt(mNetworkId); parcel.writeInt(mOnlineStatusId); } /*** * Read in NetworkPresence data from Parcel. * * @param in NetworkPresence Parcel. */ public final void readFromParcel(final Parcel in) { mUserId = in.readString(); mNetworkId = in.readInt(); mOnlineStatusId = in.readInt(); return; } /*** * Parcelable constructor for NetworkPresence. * * @param source NetworkPresence Parcel. */ public NetworkPresence(final Parcel source) { this.readFromParcel(source); } /*** * Parcelable.Creator for NetworkPresence. */ public static final Parcelable.Creator<NetworkPresence> CREATOR = new Parcelable.Creator<NetworkPresence>(){ public NetworkPresence createFromParcel(final Parcel in) { return new NetworkPresence(in); } @Override public NetworkPresence[] newArray(final int size) { return new NetworkPresence[size]; } }; } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 980c618..a26bf8f 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,901 +1,901 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.MePresenceCacheTable; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.ChatMessage; import com.vodafone360.people.datatypes.Conversation; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.PresenceList; import com.vodafone360.people.datatypes.PushAvailabilityEvent; import com.vodafone360.people.datatypes.PushChatMessageEvent; import com.vodafone360.people.datatypes.PushClosedConversationEvent; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.datatypes.SystemNotification.Tags; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Chat; import com.vodafone360.people.service.io.api.Presence; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, ITcpConnectionListener { /** Check every 24 hours **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private final List<TimelineSummaryItem> mFailedMessagesList; // (to, network) /** The list of Users still to be processed. **/ private List<User> mUsers = null; /** * This state indicates there are no more pending presence payload * information to be processed. **/ private static final int IDLE = 0; /** * This state indicates there are some pending presence payload information * to be processed. **/ private static final int UPDATE_PROCESSING_GOING_ON = 1; /** Timeout between each presence update processing. **/ private static final long UPDATE_PRESENCE_TIMEOUT_MILLS = 0; /** The page size i.e the number of presence updates processed at a time. **/ private static final int UPDATE_PRESENCE_PAGE_SIZE = 10; /** The number of pages after which the HandlerAgent is notified. **/ private static final int NOTIFY_AGENT_PAGE_INTERVAL = 5; /** The state of the presence Engine. **/ private int mState = IDLE; /** * Number of pages of presence Updates done. This is used to control when a * notification is sent to the UI. **/ private int mIterations = 0; /** * True if the engine runs for the 1st time. */ private boolean firstRun = true; /** * * @param eventCallback * @param databaseHelper */ public PresenceEngine(IEngineEventCallback eventCallback, DatabaseHelper databaseHelper) { super(eventCallback); mEngineId = EngineId.PRESENCE_ENGINE; mDbHelper = databaseHelper; mSendMessagesHash = new Hashtable<String, ChatMessage>(); mFailedMessagesList = new ArrayList<TimelineSummaryItem>(); } @Override public void onCreate() { } @Override public void onDestroy() { if (mDbHelper != null && SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper) != null) { PresenceDbUtils.resetPresenceStatesAcceptForMe(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), mDbHelper); } EngineManager.getInstance().getLoginEngine().removeListener(this); } /** * Checks if the SyncMe and ContactSync Engines have both completed first time sync. * * @return true if both engines have completed first time sync */ private boolean isFirstTimeSyncComplete() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!isFirstTimeSyncComplete()) { LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"); return -1; } /** * need isUiRequestOutstanding() because currently the worker thread is * running and finishing before PresenceEngine.setNextRuntime is called */ if (isCommsResponseOutstanding() || isUiRequestOutstanding()) { LogUtils.logV("PresenceEngine getNextRunTime() comms response outstanding"); return 0; } if (firstRun) { getPresenceList(); initSetMyAvailabilityRequestAfterLogin(); firstRun = false; } return getCurrentTimeout(); } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + getCurrentTimeout() + "]"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logV("PresenceEngine.run() handled processCommsInQueue()"); return; } if (processTimeout()) { LogUtils.logV("PresenceEngine.run() handled processTimeout()"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logV("PresenceEngine.run(): AgentState.DISCONNECTED"); setPresenceOffline(); } /** * and the getNextRunTime must check the uiRequestReady() function and * return 0 if it is true */ if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { return isUiRequestOutstanding(); } private User getMyAvailabilityStatusFromDatabase() { return PresenceDbUtils.getMeProfilePresenceStatus(mDbHelper); } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { if (isFirstTimeSyncComplete()) { getPresenceList(); setTimeout(CHECK_FREQUENCY); } } else { firstRun = true; mFailedMessagesList.clear(); mSendMessagesHash.clear(); setPresenceOffline(); } } /*** * Set the Global presence status to offline. */ private synchronized void setPresenceOffline() { PresenceDbUtils.setPresenceOfflineInDatabase(mDbHelper); // We clear the mUsers of any pending presence updates because this // Offline presence update request should take the highest priority. mUsers = null; mState = IDLE; mEventCallback.getUiAgent().updatePresence(UiAgent.ALL_USERS); } @Override protected void onRequestComplete() { LogUtils.logI("PresenceEngine.onRequestComplete()"); } @Override protected void onTimeoutEvent() { LogUtils.logI("PresenceEngine.onTimeoutEvent()"); switch (mState) { case UPDATE_PROCESSING_GOING_ON: updatePresenceDatabaseNextPage(); break; case IDLE: default: if (mLoggedIn) { if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setTimeout(CHECK_FREQUENCY); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); setTimeout(CHECK_FREQUENCY / 20); } } } } @Override protected void processCommsResponse(DecodedResponse resp) { handleServerResponse(resp.mDataTypes); } private void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg) { UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribedWithChat()) { uiAgent.sendUnsolicitedUiEvent(errorEvent, null); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users List of users that require updating. */ private synchronized void updatePresenceDatabase(List<User> users) { if (users == null || users.size() == 0) { LogUtils.logW("PresenceEngine.updatePresenceDatabase() users is NULL or zero size"); } else { if (mUsers == null) { mUsers = users; } else { // Doing an add one by one is not an efficient way but then // there is an issue in the addAll API. It crashes sometimes. // And the java code for the AddAll API seems to be erroneous. // More investigation is needed on this. for (User user : users) { mUsers.add(user); } } } mState = UPDATE_PROCESSING_GOING_ON; updatePresenceDatabaseNextPage(); } /** * This API makes the presence updates in pages of 10 with a timeout * after each page. The HandlerAgent is notified after every 10 pages. */ private synchronized void updatePresenceDatabaseNextPage(){ UiAgent uiAgent = mEventCallback.getUiAgent(); if(mUsers == null){ mState = IDLE; return; } int listSize = mUsers.size(); int start = 0; int end = UPDATE_PRESENCE_PAGE_SIZE; if(listSize == 0){ mState = IDLE; mUsers = null; return; } else if(listSize < end) { end = listSize; } List<User> userSubset = mUsers.subList(start, end); if ((userSubset != null)) { long idListeningTo = UiAgent.ALL_USERS; if (uiAgent != null) { idListeningTo = uiAgent.getLocalContactId(); } boolean updateUI = PresenceDbUtils.updateDatabase(userSubset, idListeningTo, mDbHelper); userSubset.clear(); // Send the update notification to UI for every UPDATE_PRESENCE_PAGE_SIZE*NOTIFY_AGENT_PAGE_INTERVAL updates. if (updateUI) { if (mUsers.size() == 0 || NOTIFY_AGENT_PAGE_INTERVAL == mIterations) { if (uiAgent != null) { uiAgent.updatePresence(idListeningTo); } mIterations = 0; } else { mIterations++; } } this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { - uiAgent.updateChat(message.getLocalContactId(), true); + uiAgent.updateChat(message.getLocalContactId(), true, message.getNetworkId()); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Method used to set availability of me profile when user logs in. * This is primarily used for reacting to login/connection state changes. */ private void initSetMyAvailabilityRequestAfterLogin() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } String meProfileUserId = Long.toString(PresenceDbUtils.getMeProfileUserId(mDbHelper)); Hashtable<String, String> availability = new Hashtable<String, String>(); ArrayList<Identity> identityList = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if ((identityList.size() != 0)) { for (int i=0; i<identityList.size(); i++) { Identity myIdentity = identityList.get(i); if(myIdentity.mNetwork.equals(SocialNetwork.GOOGLE.toString())) { NetworkPresence networkPresence = new NetworkPresence(meProfileUserId, SocialNetwork.GOOGLE.ordinal(), OnlineStatus.ONLINE.ordinal()); presenceList.add(networkPresence); availability.put(SocialNetwork.GOOGLE.toString(), OnlineStatus.ONLINE.toString()); } else if(myIdentity.mNetwork.equals(SocialNetwork.HYVES_NL.toString())) { NetworkPresence networkPresence = new NetworkPresence(meProfileUserId, SocialNetwork.HYVES_NL.ordinal(), OnlineStatus.ONLINE.ordinal()); presenceList.add(networkPresence); availability.put(SocialNetwork.HYVES_NL.toString(), OnlineStatus.ONLINE.toString()); } else if(myIdentity.mNetwork.equals(SocialNetwork.FACEBOOK_COM.toString())) { NetworkPresence networkPresence = new NetworkPresence(meProfileUserId, SocialNetwork.FACEBOOK_COM.ordinal(), OnlineStatus.ONLINE.ordinal()); presenceList.add(networkPresence); availability.put(SocialNetwork.FACEBOOK_COM.toString(), OnlineStatus.ONLINE.toString()); } else if(myIdentity.mNetwork.equals(SocialNetwork.MICROSOFT.toString())) { NetworkPresence networkPresence = new NetworkPresence(meProfileUserId, SocialNetwork.MICROSOFT.ordinal(), OnlineStatus.ONLINE.ordinal()); presenceList.add(networkPresence); availability.put(SocialNetwork.MICROSOFT.toString(), OnlineStatus.ONLINE.toString()); } else if(myIdentity.mNetwork.equals(SocialNetwork.MOBILE.toString())) { NetworkPresence networkPresence = new NetworkPresence(meProfileUserId, SocialNetwork.MOBILE.ordinal(), OnlineStatus.ONLINE.ordinal()); presenceList.add(networkPresence); availability.put(SocialNetwork.MOBILE.toString(), OnlineStatus.ONLINE.toString()); } } } User meUser = new User(); meUser.setLocalContactId(Long.valueOf(meProfileUserId)); meUser.setPayload(presenceList); updateMyPresenceInDatabase(meUser); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } // Get presences Hashtable<String, String> presenceList = getPresencesForStatus(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** * Changes the user's availability. * * @param status - Hashtable<String, String> of pairs <communityName, statusName>. */ public void setMyAvailability(Hashtable<String, String> presenceHash) { if (presenceHash == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceHash); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } /** * Changes the user's availability. * * @param network - SocialNetwork to set presence on. * @param status - OnlineStatus presence status to set. */ public void setMyAvailability(SocialNetwork network, OnlineStatus status) { LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+ network + "=" + status); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); final NetworkPresence newPresence = new NetworkPresence(userId, network.ordinal(), status.ordinal()); presenceList.add(newPresence); User me = new User(userId, null); me.setPayload(presenceList); MePresenceCacheTable.updateCache(newPresence, mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now Hashtable<String, String> presenceHash = new Hashtable<String, String>(); presenceHash.put(network.toString(), status.toString()); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } @Override public void onConnectionStateChanged(int state) { if (mLoggedIn && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initializeAvailabilityFromDb(); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * Initializes or re-initializes availability from the Database. * If there are cached presences then these will be used * instead of values from the presence table. */ private void initializeAvailabilityFromDb() { final User user = getMyAvailabilityStatusFromDatabase(); ArrayList<NetworkPresence> cachedPresences = MePresenceCacheTable.getCache(mDbHelper.getReadableDatabase()); if(cachedPresences != null) { user.setPayload(cachedPresences); } initSetMyAvailabilityRequest(user); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if(identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); for(Identity identity : identities) { presences.put(identity.mNetwork, statusString); } return presences; } @Override diff --git a/src/com/vodafone360/people/service/agent/UiAgent.java b/src/com/vodafone360/people/service/agent/UiAgent.java index 3d206d4..d6fcdc5 100644 --- a/src/com/vodafone360/people/service/agent/UiAgent.java +++ b/src/com/vodafone360/people/service/agent/UiAgent.java @@ -1,375 +1,377 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.agent; import java.security.InvalidParameterException; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.Intents; import com.vodafone360.people.MainApplication; import com.vodafone360.people.engine.upgrade.UpgradeStatus; import com.vodafone360.people.engine.upgrade.VersionCheck; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.WidgetUtils; /** * The UiAgent is aware when any "Live" Activities are currently on screen, and * contains business logic for sending unsolicited messages to the UI. This is * useful for knowing when to send chat messages, presence updates, * notifications, error messages, etc to an on screen Activity. */ public class UiAgent { /** UI Notification identifier. **/ public static final int UI_AGENT_NOTIFICATION_ID = 1; /** Pointer to MainApplication. **/ private MainApplication mMainApplication; /** * Store for pending UiEvents while no People Activities are currently on * screen. */ private ServiceUiRequest mUiEventQueue = null; /** * Store for pending UiEvent Bundles while no People Activities are * currently on screen. */ private Bundle mUiBundleQueue = null; /** * Handler object from a subscribed UI Activity. Note: This object is * nullified by a separate thread and is thereby declared volatile. */ private volatile Handler mHandler; /** * Local ID of the contact the Handler is tracking (-1 when tracking all). */ private long mLocalContactId; /** TRUE if the subscribed UI Activity expects chat messages. **/ private boolean mShouldHandleChat; /** Reference to Android Context. **/ private Context mContext = null; /** * This constant is used to indicate the UiAgent is now subscribed * to refresh events related to all local contact ids. */ public static final int ALL_USERS = -1; /** * Constructor. * * @param mainApplication Pointer to MainApplication. * @param context Reference to Android Context. */ public UiAgent(final MainApplication mainApplication, final Context context) { mMainApplication = mainApplication; mContext = context; mHandler = null; mLocalContactId = ALL_USERS; mShouldHandleChat = false; } /*** * Send an unsolicited UI Event to the UI. If there are no on screen * Activities, then queue the message for later. The queue is of size one, * so higher priority messages will simply overwrite older ones. * * @param uiEvent Event to send. * @param bundle Optional Bundle to send to UI, usually set to NULL. */ public final void sendUnsolicitedUiEvent(final ServiceUiRequest uiEvent, final Bundle bundle) { if (uiEvent == null) { throw new InvalidParameterException("UiAgent." + "sendUnsolicitedUiEvent() UiEvent cannot be NULL"); } LogUtils.logW("UiAgent.sendUnsolicitedUiEvent() uiEvent[" + uiEvent.name() + "]"); if (mHandler != null) { /* * Send now. */ try { mHandler.sendMessage(mHandler.obtainMessage(uiEvent.ordinal(), bundle)); LogUtils.logV("UiAgent.sendUnsolicitedUiEvent() " + "Sending uiEvent[" + uiEvent + "]"); } catch (NullPointerException e) { LogUtils.logW("UiAgent.sendUnsolicitedUiEvent() Caught a race " + "condition where mHandler was set to NULL after " + "being explicitly checked"); /** Send later anyway. **/ addUiEventToQueue(uiEvent, bundle); } } else { /* * Send later. */ addUiEventToQueue(uiEvent, bundle); } } /*** * Add the given UiEvent and Bundle pair to the send later queue. * * @param uiEvent ServiceUiRequest to queue. * @param bundle Bundle to queue. */ private void addUiEventToQueue(final ServiceUiRequest uiEvent, final Bundle bundle) { if (mUiEventQueue == null || uiEvent.ordinal() < mUiEventQueue.ordinal()) { LogUtils.logV("UiAgent.sendUnsolicitedUiEvent() Sending uiEvent[" + uiEvent.name() + "] later"); mUiEventQueue = uiEvent; mUiBundleQueue = bundle; } else { LogUtils.logV("UiAgent.sendUnsolicitedUiEvent() Ignoring uiEvent[" + uiEvent.name() + "], as highter priority UiEvent[" + mUiEventQueue.name() + "] is already pending"); } } /** * Subscribes a UI Handler to receive unsolicited events. * * @param handler UI handler to receive unsolicited events. * @param localContactId Provide a local contact ID to receive updates for * the given contact only, or set this to -1 to receive updates * for every contact, or set this to NULL not to receive contact * updates. * @param shouldHandleChat TRUE if the Handler expects chat messages. */ public final void subscribe(final Handler handler, final Long localContactId, final boolean shouldHandleChat) { LogUtils.logV("UiAgent.subscribe() handler[" + handler + "] localContactId[" + localContactId + "] chat[" + shouldHandleChat + "]"); if (handler == null) { throw new NullPointerException("UiAgent.subscribe()" + "Handler cannot be NULL"); } mHandler = handler; mLocalContactId = localContactId; mShouldHandleChat = shouldHandleChat; if (mShouldHandleChat) { updateChatNotification(false); } if (mUiEventQueue != null) { LogUtils.logV("UiAgent.subscribe() Send pending uiEvent[" + mUiEventQueue + "]"); mHandler.sendMessage(mHandler.obtainMessage( mUiEventQueue.ordinal(), mUiBundleQueue)); mUiEventQueue = null; mUiBundleQueue = null; } UpgradeStatus upgradeStatus = new VersionCheck( mMainApplication.getApplicationContext(), false).getCachedUpdateStatus(); if (upgradeStatus != null) { sendUnsolicitedUiEvent(ServiceUiRequest.UNSOLICITED_DIALOG_UPGRADE, null); } ConnectionManager.getInstance().notifyOfUiActivity(); } /** * This method ends the UI Handler's subscription. This will have no effect * if a different handler is currently subscribed. * * @param handler - UI handler to no longer receive unsolicited events. */ public final void unsubscribe(final Handler handler) { if (handler == null) { throw new NullPointerException("UiAgent.unsubscribe() Handler" + "cannot be NULL."); } if (handler != mHandler) { LogUtils.logW("UiAgent.unsubscribe() Activity is trying to " + "unsubscribe with a different handler"); } else { mHandler = null; mLocalContactId = ALL_USERS; mShouldHandleChat = false; } } /** * This method returns the local ID of the contact the HandlerAgent is * tracking. * * @return LocalContactId of the contact the HandlerAgent is tracking */ public final long getLocalContactId() { return mLocalContactId; } /** * Returns TRUE if an Activity is currently listening out for unsolicited * events (i.e. a "Live" activity is currently on screen). * * @return TRUE if any subscriber is listening the presence state/chat * events */ public final boolean isSubscribed() { return mHandler != null; } /** * Returns TRUE if an Activity is currently listening out for unsolicited * events (i.e. a "Live" activity is currently on screen). * * @return TRUE if any subscriber is listening the presence chat events */ public final boolean isSubscribedWithChat() { return mHandler != null && mShouldHandleChat; } /** * This method is called by the Presence engine to notify a subscribed * Activity of updates. * * @param contactId Update an Activity that shows this contact ID only, or * set this to ALL_USERS to send updates relevant to all contacts. */ public final void updatePresence(final long contactId) { WidgetUtils.kickWidgetUpdateNow(mMainApplication); if (mHandler == null) { LogUtils.logW("UiAgent.updatePresence() No subscribed Activities"); return; } if(shouldSendPresenceToUi(contactId)) { mHandler.sendMessage(mHandler.obtainMessage( ServiceUiRequest.UNSOLICITED_PRESENCE.ordinal(), null)); } else { LogUtils.logV("UiAgent.updatePresence() No Activities are " + "interested in contactId[" + contactId + "]"); } } /** * Checks if a (Unsolicited) Presence event should be sent to the UI. * At the moment sending it only if contactId or mLocalContactId for ALL_USERS * or the monitored contact matches mLocalContactId. * @param contactId * @return */ private boolean shouldSendPresenceToUi(final long contactId) { if(mLocalContactId == ALL_USERS) { return true; } /* * Basically this fixes bug in the me profile where presence is not updated to invisible * when user goes into flight mode */ if(contactId == ALL_USERS) { return true; } return mLocalContactId == contactId; } /** * <p>Notifies an on screen Chat capable Activity of a relevant update. If the * wrong Activity is on screen, this update will be shown as a Notification.</p> * * <p><b>Please note that this method takes care of notification for adding AND * removing chat message notifications</b></p>! * * @param contactId Update an Activity that shows Chat information for this * localContact ID only. * @param isNewChatMessage True if this is a new chat message that we are notifying * for. False if we are for instance just deleting a notification. + * @param networkId the ordinal value of the SocialNetwork from which the chat + * message has been received */ - public final void updateChat(final long contactId, final boolean isNewChatMessage) { + public final void updateChat(final long contactId, final boolean isNewChatMessage, final int networkId) { if (mHandler != null && mShouldHandleChat && mLocalContactId == contactId) { LogUtils.logV("UiAgent.updateChat() Send message to UI (i.e. " + "update the screen)"); mHandler.sendMessage(mHandler.obtainMessage( - ServiceUiRequest.UNSOLICITED_CHAT.ordinal(), null)); + ServiceUiRequest.UNSOLICITED_CHAT.ordinal(), networkId, 0, null)); /* * Note: Do not update the chat notification at this point, as the * UI must update the database (e.g. mark messages as read) before * calling subscribe() to trigger a refresh. */ } else if (mHandler != null && mShouldHandleChat && mLocalContactId == -1) { LogUtils.logV("UiAgent.updateChat() Send message to UI (i.e. " + "update the screen) and do a noisy notification"); /* * Note: this was added because TimelineListActivity listens to all * localIds (i.e. localContactId = -1) */ mHandler.sendMessage(mHandler.obtainMessage( - ServiceUiRequest.UNSOLICITED_CHAT.ordinal(), null)); + ServiceUiRequest.UNSOLICITED_CHAT.ordinal(), networkId, 0, null)); updateChatNotification(isNewChatMessage); } else { LogUtils.logV("UiAgent.updateChat() Do a noisy notification only"); updateChatNotification(isNewChatMessage); } } /*** * Update the Notification bar with Chat information directly from the * database. * * @param isNewChatMessage True if we have a new chat message and want to * display a noise and notification, false if we for instance just delete a * chat message or update a multiple-user notification silently. * */ private void updateChatNotification(final boolean isNewChatMessage) { mContext.sendBroadcast(new Intent(Intents.NEW_CHAT_RECEIVED).putExtra( ApplicationCache.sIsNewMessage, isNewChatMessage)); } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java index 9ab10cc..3550e66 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,449 +1,449 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.interfaces; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import android.os.Bundle; import android.os.Handler; import android.os.Message; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.MainApplication; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.agent.NetworkAgentState; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.utils.LogUtils; /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback * @see com.vodafone360.people.service.interfaces.IPeopleService */ public class IPeopleServiceImpl implements IPeopleService, IEngineEventCallback { private final List<Handler> mUiEventCallbackList = new ArrayList<Handler>(); private IWorkerThreadControl mWorkerThreadControl; private RemoteService mService; private NetworkAgent mNetworkAgent; private UiAgent mHandlerAgent; private ApplicationCache mApplicationCache; /** * Initialises the object, creating the UiAgent. * * @param workerThreadControl Provides access to worker thread control * functions. * @param service Provides access to remote service functions (mainly used * to retrieve context). */ public IPeopleServiceImpl(IWorkerThreadControl workerThreadControl, RemoteService service) { mWorkerThreadControl = workerThreadControl; mService = service; mHandlerAgent = new UiAgent((MainApplication)service.getApplication(), service); mApplicationCache = ((MainApplication)service.getApplication()).getCache(); } /*** * Sets the ServiceAgent, as this needs to be called after the constructor. * * @param agent Handle to ServiceAgent. */ public void setNetworkAgent(NetworkAgent agent) { mNetworkAgent = agent; } /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#onUiEvent(UiEvent, * int, int, Object) */ @Override public void onUiEvent(ServiceUiRequest event, int arg1, int arg2, Object data) { synchronized (mUiEventCallbackList) { for (Handler handler : mUiEventCallbackList) { Message msg = handler.obtainMessage(event.ordinal(), data); msg.arg1 = arg1; msg.arg2 = arg2; if (!handler.sendMessage(msg)) { LogUtils.logE("IPeopleServiceImpl.onUiEvent() Sending msg FAILED"); } } } } /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#kickWorkerThread() */ @Override public void kickWorkerThread() { mWorkerThreadControl.kickWorkerThread(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#addEventCallback(Handler) */ @Override public void addEventCallback(Handler uiHandler) { synchronized (mUiEventCallbackList) { if (!mUiEventCallbackList.contains(uiHandler)) { mUiEventCallbackList.add(uiHandler); } } } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#removeEventCallback(Handler) */ @Override public void removeEventCallback(Handler uiHandler) { synchronized (mUiEventCallbackList) { mUiEventCallbackList.remove(uiHandler); } } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#checkForUpdates() */ @Override public void checkForUpdates() { EngineManager.getInstance().getUpgradeEngine().checkForUpdates(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMyThirdPartyIdentities() */ public ArrayList<Identity> getMyThirdPartyIdentities() { return EngineManager.getInstance().getIdentityEngine().getMyThirdPartyIdentities(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyIdentities() */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { return EngineManager.getInstance().getIdentityEngine().getAvailableThirdPartyIdentities(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyChattableIdentities() */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { return EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchPrivacyStatement() */ @Override public void fetchPrivacyStatement() { EngineManager.getInstance().getLoginEngine().addUiFetchPrivacyStatementRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchTermsOfService() */ @Override public void fetchTermsOfService() { EngineManager.getInstance().getLoginEngine().addUiFetchTermsOfServiceRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchUsernameState(String) */ @Override public void fetchUsernameState(String userName) { EngineManager.getInstance().getLoginEngine().addUiGetUsernameStateRequest(userName); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getLoginRequired() */ @Override public boolean getLoginRequired() { EngineManager manager = EngineManager.getInstance(); return manager.getLoginEngine().getLoginRequired(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getRoamingNotificationType() */ @Override public int getRoamingNotificationType() { return mService.getNetworkAgent().getRoamingNotificationType(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getRoamingDeviceSetting() */ @Override public boolean getRoamingDeviceSetting() { return mService.getNetworkAgent().getRoamingDeviceSetting(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#notifyDataSettingChanged(InternetAvail) */ @Override public void notifyDataSettingChanged(InternetAvail val) { mService.getNetworkAgent().notifyDataSettingChanged(val); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#logon(LoginDetails) */ @Override public void logon(LoginDetails loginDetails) { EngineManager manager = EngineManager.getInstance(); manager.getLoginEngine().addUiLoginRequest(loginDetails); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#register(RegistrationDetails) */ @Override public void register(RegistrationDetails details) { EngineManager.getInstance().getLoginEngine().addUiRegistrationRequest(details); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setNewUpdateFrequency() */ @Override public void setNewUpdateFrequency() { EngineManager.getInstance().getUpgradeEngine().setNewUpdateFrequency(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setShowRoamingNotificationAgain(boolean) */ @Override public void setShowRoamingNotificationAgain(boolean showAgain) { mService.getNetworkAgent().setShowRoamingNotificationAgain(showAgain); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startContactSync() */ @Override public void startContactSync() { EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); EngineManager.getInstance().getContactSyncEngine().addUiStartFullSync(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startBackgroundContactSync(long) */ @Override public void startBackgroundContactSync(long delay) { EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); EngineManager.getInstance().getContactSyncEngine().addUiStartServerSync(delay); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#pingUserActivity() */ @Override public void pingUserActivity() { EngineManager.getInstance().getContactSyncEngine().pingUserActivity(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#validateIdentityCredentials(boolean, * String, String, String, Bundle) */ @Override public void validateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { EngineManager.getInstance().getIdentityEngine().addUiValidateIdentityCredentials(dryRun, network, username, password, identityCapabilityStatus); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startStatusesSync() */ @Override public void startStatusesSync() { EngineManager.getInstance().getActivitiesEngine().addStatusesSyncRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getNetworkAgentState() */ @Override public NetworkAgentState getNetworkAgentState() { return mNetworkAgent.getNetworkAgentState(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setNetowrkAgentState(NetworkAgentState) */ @Override public void setNetworkAgentState(NetworkAgentState state) { mNetworkAgent.setNetworkAgentState(state); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getPresenceList(long) */ @Override public void getPresenceList(long contactId) { EngineManager.getInstance().getPresenceEngine().getPresenceList(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(OnlineStatus) */ @Override public void setAvailability(OnlineStatus status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(SocialNetwork, OnlineStatus) */ @Override public void setAvailability(SocialNetwork network, OnlineStatus status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(network, status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(Hashtable<String, String> status) */ @Override public void setAvailability(Hashtable<String, String> status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#subscribe(Handler, * long, boolean) */ @Override public void subscribe(Handler handler, Long contactId, boolean chat) { mHandlerAgent.subscribe(handler, contactId, chat); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#unsubscribe(Handler) */ @Override public void unsubscribe(Handler handler) { mHandlerAgent.unsubscribe(handler); } /** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#getUiAgent() */ @Override public UiAgent getUiAgent() { return mHandlerAgent; } /** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#getApplicationCache() */ @Override public ApplicationCache getApplicationCache() { return mApplicationCache; } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#sendMessage(long, * String, int) */ @Override public void sendMessage(long localContactId, String body, int networkId) { EngineManager.getInstance().getPresenceEngine() .sendMessage(localContactId, body, networkId); } @Override public void setIdentityStatus(String network, String identityId, boolean identityStatus) { EngineManager.getInstance().getIdentityEngine().addUiSetIdentityStatus(network, identityId, identityStatus); } @Override public void getStatuses() { EngineManager.getInstance().getActivitiesEngine().addStatusesSyncRequest(); } @Override public void getMoreTimelines() { EngineManager.getInstance().getActivitiesEngine().addOlderTimelinesRequest(); } @Override public void getOlderStatuses() { EngineManager.getInstance().getActivitiesEngine().addGetOlderStatusesRequest(); } @Override public void uploadMeProfile() { EngineManager.getInstance().getSyncMeEngine().addUpdateMeProfileContactRequest(); } @Override public void uploadMyStatus(String statusText) { EngineManager.getInstance().getSyncMeEngine().addUpdateMyStatusRequest(statusText); } @Override public void downloadMeProfileFirstTime() { EngineManager.getInstance().getSyncMeEngine().addGetMeProfileContactFirstTimeRequest(); } @Override public void updateChatNotification(long localContactId) { - mHandlerAgent.updateChat(localContactId, false); + mHandlerAgent.updateChat(localContactId, false, SocialNetwork.INVALID.ordinal()); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#deleteIdentity(String,String) */ @Override public void deleteIdentity(final String network, final String identityId) { EngineManager.getInstance().getIdentityEngine() .addUiDeleteIdentityRequest(network, identityId); } } \ No newline at end of file
360/360-Engine-for-Android
d55fb1ae9b596ba1d505d9cd989a0b9b5a61a337
PAND-2390 send offline for TPCs except for Mobile when set the me profile status to invisible
diff --git a/src/com/vodafone360/people/Settings.java b/src/com/vodafone360/people/Settings.java index 0f20281..3fca4e1 100644 --- a/src/com/vodafone360/people/Settings.java +++ b/src/com/vodafone360/people/Settings.java @@ -1,307 +1,307 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; /** * All application settings. */ public final class Settings { /* * LogCat. */ /** LogCat TAG prefix. **/ public static final String LOG_TAG = "People_"; /* * Transport. */ /** Milliseconds until HTTP connection will time out. */ public static final int HTTP_CONNECTION_TIMEOUT = 30000; /** Maximum number of HTTP connection attempts. */ public static final int HTTP_MAX_RETRY_COUNT = 3; /** HTTP header content type. */ public static final String HTTP_HEADER_CONTENT_TYPE = "application/binary"; /** Number of empty RPG poll responses before stopping RPG poll. */ public static final int BLANK_RPG_HEADER_COUNT = 4; /** TCP Heartbeat interval (10 seconds). */ public static final long TCP_VF_HEARTBEAT_INTERVAL = 10 * 60 * 1000; /** TCP retry interval if we have lost the connection (30 seconds). */ public static final long TCP_RETRY_BROKEN_CONNECTION_INTERVAL = 30 * 60 * 1000; /** TCP socket read time out for the read-operation. */ public static final int TCP_SOCKET_READ_TIMEOUT = 10 * 60 * 1000; /* * Notifications. */ /** LED colour. */ public static final int NOTIFICATION_LED_COLOR = 0xff00ff00; // Green /** LED on time. */ public static final int NOTIFICATION_LED_OFF_TIME = 300; /** LED on time. */ public static final int NOTIFICATION_LED_ON_TIME = 1000; /* * Upgrade Engine */ /** * See UpdateSettingsActivity.FREQUENCY_SETTING_LONG array for meaning (i.e. * Every 6 hours) */ public static final int PREFS_CHECK_FREQUENCY_DEFAULT = 3; /** Show the upgrade dialog box every 10 minutes. */ public static final int DIALOG_CHECK_FREQUENCY_MILLIS = 10 * 60 * 1000; /** * Component trace flags (always checked in as false, not part of build * script). */ /** Trace output for engine components. **/ public static final boolean ENABLED_ENGINE_TRACE = false; /** Trace output for database components. **/ public static final boolean ENABLED_DATABASE_TRACE = false; /** Trace output for contact synchronisation components. **/ public static final boolean ENABLED_CONTACTS_SYNC_TRACE = false; /** Log engine runtime information to file for profiling. **/ public static final boolean ENABLED_PROFILE_ENGINES = false; /** Trace output for protocol (i.e. network IO) components. **/ - public static boolean sEnableProtocolTrace = true; + public static boolean sEnableProtocolTrace = false; /** * This is a list of strings containing the names of engines to be * deactivated in the build. A de-activated engine is constructed but will * never be run (nor will onCreate or onDestroy be called). Any UI requests * will be automatically completed by the framework with a * ServiceStatus.ERROR_NOT_IMPLEMENTED error. */ public static final String DEACTIVATE_ENGINE_LIST_KEY = "deactivated-engines-list"; /* * Hard coded settings */ /** Enable dialler cheat code. **/ public static final boolean DIALER_CHEATCODES_ENABLED = true; /** Enable SMS account activation. **/ public static final boolean ENABLE_ACTIVATION = false; /** * Enable SIM inserted check. Always set to TRUE. Makes the application * unusable if there is no valid SIM card inserted into the device. */ public static final boolean ENABLE_SIM_CHECK = true; /** Enable fetching native contacts. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS = true; /** Enable fetching native contacts on change. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS_ON_CHANGE = true; /** Enable ME profile synchronisation. **/ public static final boolean ENABLE_ME_PROFILE_SYNC = true; /** Enable server contact synchronisation. **/ public static final boolean ENABLE_SERVER_CONTACT_SYNC = true; /** Enable server thumbnail synchronisation. **/ public static final boolean ENABLE_THUMBNAIL_SYNC = true; /** Enable update native contacts synchronisation. **/ public static final boolean ENABLE_UPDATE_NATIVE_CONTACTS = true; /** Enable hiding of connected friends group. **/ public static final boolean HIDE_CONNECTED_FRIENDS_GROUP = true; /** Disable the native sync after the first time import for Android 1.X devices only **/ public static final boolean DISABLE_NATIVE_SYNC_AFTER_IMPORT_ON_ANDROID_1X = true; /* * Keys for properties that can be changed at build time. */ /** Key for application ID setting. **/ public static final String APP_KEY_ID = "app-key-id"; /** Key for application secret key setting. **/ public static final String APP_SECRET_KEY = "app-secret-key"; /** Key for enable logging setting. **/ protected static final String ENABLE_LOGCAT_KEY = "enable-logcat"; /** Key for enable RPG setting. **/ public static final String ENABLE_RPG_KEY = "use-rpg"; /** Key for enable SNS resource icon setting. **/ public static final String ENABLE_SNS_RESOURCE_ICON_KEY = "enable-sns-resource-icon"; /** Key for RPG server URL setting. **/ public static final String RPG_SERVER_KEY = "rpg-url"; /** Key for Hessian URL setting. **/ public static final String SERVER_URL_HESSIAN_KEY = "hessian-url"; /** Key for enabling 3rd party applications to access data via AIDL. **/ public static final String ENABLE_AIDL_KEY = "allow-aidl"; /** Default setting ENABLE_AIDL_KEY. **/ public static final String ENABLE_AIDL_DEFAULT = "false"; /* * Keys without defaults. */ /** Key for TCP server URL setting. **/ public static final String TCP_RPG_URL_KEY = "rpg-tcp-url"; /** Key for TCP port setting. **/ public static final String TCP_RPG_PORT_KEY = "rpg-tcp-port"; /** Key for upgrade check URL setting. **/ public static final String UPGRADE_CHECK_URL_KEY = "upgrade-url"; /* * Default for properties that can be changed at build time. */ /** Default for logging enabled setting. **/ protected static final String DEFAULT_ENABLE_LOGCAT = "true"; /** Default for RPG enabled setting. **/ protected static final String DEFAULT_ENABLE_RPG = "true"; /** Default for SNS resource icon setting. **/ protected static final String DEFAULT_ENABLE_SNS_RESOURCE_ICON = "true"; /** Default for RPG server URL setting. **/ protected static final String DEFAULT_RPG_SERVER = "http://rpg.vodafone360.com/rpg/mcomet/"; /** Default for Hessian URL setting. **/ protected static final String DEFAULT_SERVER_URL_HESSIAN = "http://api.vodafone360.com/services/hessian/"; /* * Request timeouts for all engines and requests, except for fire and * forget calls to RPG: SET_AVAILABILITY and SEND_CHAT_MSG. */ /** Do not handle timeouts for this API. **/ private static final long DONT_HANDLE_TIMEOUTS = -1; /** Generic timeout for requests. **/ private static final long ALL_ENGINES_REQUESTS_TIMEOUT = 60000; /** Timeout for all presence API requests. **/ private static final long PRESENCE_ENGINE_REQUESTS_TIMEOUT = 120000; /** Number of milliseconds in a week. **/ public static final long HISTORY_IS_WEEK_LONG = 7 * 24 * 60 * 60 * 1000; /** Timeout for request waiting in queue. **/ public static final long REMOVE_REQUEST_FROM_QUEUE_MILLIS = 15 * 60 * 1000; /* * The timeouts in milliseconds for the different APIs. */ /** Timeout for activities API. **/ public static final long API_REQUESTS_TIMEOUT_ACTIVITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for authentication API. **/ public static final long API_REQUESTS_TIMEOUT_AUTH = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat create conversation API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_CREATE_CONV = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat send message API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_SEND_MESSAGE = DONT_HANDLE_TIMEOUTS; /** Timeout for contacts API. **/ public static final long API_REQUESTS_TIMEOUT_CONTACTS = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for group privacy API. **/ public static final long API_REQUESTS_TIMEOUT_GROUP_PRIVACY = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for identities API. **/ public static final long API_REQUESTS_TIMEOUT_IDENTITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for presence list API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_LIST = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Timeout for presence set availability API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Enable Facebook chat. **/ public static boolean sEnableFacebookChat = true; /** * Danger! Only set to true if you know what you are doing! This logs each * response no matter if gzipped or not to the SD card under the given * request ID. */ public static boolean sEnableSuperExpensiveResponseFileLogging = false; /** * Private constructor to prevent instantiation. */ private Settings() { } /** * a debug flag to see what's coming with availability state change push messages. */ public static boolean LOG_PRESENCE_PUSH_ON_LOGCAT = false; } \ No newline at end of file diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index b9c86ed..e26391d 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -351,541 +351,543 @@ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, if (uiAgent != null) { uiAgent.updatePresence(idListeningTo); } mIterations = 0; } else { mIterations++; } } this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ synchronized public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Method used to set availability of me profile when user logs in. * This is primarily used for reacting to login/connection state changes. */ private void initSetMyAvailabilityRequestAfterLogin() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } String meProfileUserId = Long.toString(PresenceDbUtils.getMeProfileUserId(mDbHelper)); Hashtable<String, String> availability = new Hashtable<String, String>(); ArrayList<Identity> identityList = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if ((identityList.size() != 0)) { for (int i=0; i<identityList.size(); i++) { Identity myIdentity = identityList.get(i); availability.put(myIdentity.mNetwork, OnlineStatus.ONLINE.toString()); } } User meUser = new User(); meUser.setLocalContactId(Long.valueOf(meProfileUserId)); meUser.setPayload(presenceList); updateMyPresenceInDatabase(meUser); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } // Get presences Hashtable<String, String> presenceList = getPresencesForStatus(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** * Changes the user's availability. * * @param status - Hashtable<String, String> of pairs <communityName, statusName>. */ public void setMyAvailability(Hashtable<String, String> presenceHash) { if (presenceHash == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceHash); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } /** * Changes the user's availability. * * @param network - SocialNetwork to set presence on. * @param status - OnlineStatus presence status to set. */ public void setMyAvailability(SocialNetwork network, OnlineStatus status) { LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+ network + "=" + status); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); final NetworkPresence newPresence = new NetworkPresence(userId, network.ordinal(), status.ordinal()); presenceList.add(newPresence); User me = new User(userId, null); me.setPayload(presenceList); MePresenceCacheTable.updateCache(newPresence, mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now Hashtable<String, String> presenceHash = new Hashtable<String, String>(); presenceHash.put(network.toString(), status.toString()); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } @Override public void onConnectionStateChanged(int state) { if (mLoggedIn && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initializeAvailabilityFromDb(); break; case STATE_CONNECTING: case STATE_DISCONNECTED: mFirstRun = true; setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * Initializes or re-initializes availability from the Database. * If there are cached presences then these will be used * instead of values from the presence table. */ private void initializeAvailabilityFromDb() { final User user = getMyAvailabilityStatusFromDatabase(); ArrayList<NetworkPresence> cachedPresences = MePresenceCacheTable.getCache(mDbHelper.getReadableDatabase()); if(cachedPresences != null) { user.setPayload(cachedPresences); } initSetMyAvailabilityRequest(user); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); - if(identities == null) { + if (identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); - for(Identity identity : identities) { - presences.put(identity.mNetwork, statusString); + for (Identity identity : identities) { + presences.put(identity.mNetwork, status.equals(OnlineStatus.INVISIBLE)? + (identity.mNetwork.trim().equals("mobile")? statusString: OnlineStatus.OFFLINE.toString()) + :statusString); } return presences; } @Override public void onReset() { // reset the engine as if it was just created super.onReset(); mFirstRun = true; mLoggedIn = false; mIterations = 0; mState = IDLE; mUsers = null; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } }
360/360-Engine-for-Android
bb5150f72a8ed507c634dd0d856f4de2ad98197c
Lost code review ammendments to PAND-1527
diff --git a/src/com/vodafone360/people/service/transport/tcp/HeartbeatSenderThread.java b/src/com/vodafone360/people/service/transport/tcp/HeartbeatSenderThread.java index 765024a..319c63e 100644 --- a/src/com/vodafone360/people/service/transport/tcp/HeartbeatSenderThread.java +++ b/src/com/vodafone360/people/service/transport/tcp/HeartbeatSenderThread.java @@ -1,390 +1,385 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.transport.tcp; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.util.Hashtable; import android.content.Context; import android.os.PowerManager; import com.vodafone360.people.Settings; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.IWakeupListener; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.AuthUtils; import com.vodafone360.people.service.utils.hessian.HessianEncoder; import com.vodafone360.people.service.utils.hessian.HessianUtils; import com.vodafone360.people.service.io.rpg.RpgHeader; import com.vodafone360.people.service.io.rpg.RpgMessageTypes; /** * Sends heartbeats to the RPG in order to keep the connection alive. * * @author Rudy Norff ([email protected]) */ public class HeartbeatSenderThread implements Runnable, IWakeupListener { /** * The HeartbeatSenderThread that was created by the TcpConnectionThread. It * will be compared to this thread. If they differ this thread must be a * lock thread that got stuck when the user changed APNs or switched from * WiFi to another data connection type. */ protected static HeartbeatSenderThread mCurrentThread; /** * The milliseconds in a second. */ private static final long MILLIS_PER_SEC = 1000; /** * The service under which context the hb sender runs in. Used for setting * alarms that wake up the CPU for sending out heartbeats. */ private RemoteService mService; /** * The managing thread that needs to be called back if an IOException occurs * sending a heartbeat. */ private TcpConnectionThread mConnThread; /** * The thread continuously sending the heartbeats. */ protected Thread mThread; /** * The output stream to write the heartbeat to. */ protected OutputStream mOs; /** * This is the interval at which the heartbeat gets sent. The problem with * this is that this timeout interval is only proven in the Vodafone * network. In other networks we will do an autodetect for the correct * interval settings. */ protected long mHeartbeatInterval; /** * Indicates that the connection is running if true. */ private boolean mIsConnectionRunning; /** * Keeps a partial wake lock on the CPU that will prevent it from sleeping * and allow the Sender to send off heartbeats. */ private PowerManager.WakeLock mWakeLock; /** * The socket to write to. */ private Socket mSocket; /** * Constructs a heartbeat-sender and passes the connection thread to call * back to in case of errors. * * @param connThread The connection thread to call back to in case of * networking issues. * @param service The remote service that we register with once we have set * the heartbeat alarm. */ public HeartbeatSenderThread(TcpConnectionThread connThread, RemoteService service, Socket socket) { mConnThread = connThread; mHeartbeatInterval = Settings.TCP_VF_HEARTBEAT_INTERVAL; mService = service; mSocket = socket; if (null != mService) { mService.registerCpuWakeupListener(this); PowerManager pm = (PowerManager)mService.getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "HeartbeatSenderThread.HeartbeatSenderThread()"); } } /** * Sets the state of the connection to run and spawns a thread to run it in. */ public synchronized void startConnection() { HttpConnectionThread.logI("RpgTcpHeartbeatSender.startConnection()", "STARTING HB Sender!"); mIsConnectionRunning = true; mThread = null; // if we are restarting let's clear the last traces mThread = new Thread(this, "RpgTcpHeartbeatSender"); mThread.start(); } /** * Stops the heartbeat-senders connection and closes the output-stream to * the socket-connection. */ public synchronized void stopConnection() { mIsConnectionRunning = false; synchronized (this) { notify(); } mService.setAlarm(false, 0); if (null != mSocket) { try { mSocket.shutdownOutput(); } catch (IOException ioe) { HttpConnectionThread.logE("RpgTcpHeartbeatSender.stopConnection()", "Could not shutdown OutputStream", ioe); } finally { mSocket = null; } } if (null != mOs) { try { mOs.close(); } catch (IOException ioe) { HttpConnectionThread.logE("RpgTcpHeartbeatSender.stopConnection()", "Could not close OutputStream", ioe); } finally { mOs = null; } } } /** * Sets the output-stream so that the heartbeat-sender can send its * heartbeats to the RPG. * * @param outputStream The open output-stream that the heartbeats shall be * sent to. Avoid passing null as this will result in an * error-callback to RpgTcpConnectionThread which will completely * reestablish the socket connection. */ public void setOutputStream(OutputStream outputStream) { HttpConnectionThread.logI("RpgTcpHeartbeatSender.setOutputStream()", "Setting new OS."); mOs = outputStream; } /** * The run-method overriding Thread.run(). The method continuously sends out * heartbeats by calling sendHeartbeat() and then waits for a * Thread.interrupt(), a notify or for the wait timer to time out after a * timer-value defined in Settings.TCP_VF_HEARTBEAT_INTERVAL. */ public void run() { // sets the wakeup alarm at XX minutes. This is important as the CPU // gets woken // by this call if it should be in standby mode. while (mIsConnectionRunning) { try { if (!this.equals(mCurrentThread)) { // The current thread created by the TcpConnectionThread is // not equal to this thread. // This thread must be old (locked due to the user changing // his network settings. HttpConnectionThread.logE("HeartbeatSenderThread.run()", "This thread is a " + "locked thread caused by the connection settings being switched.", null); stopConnection(); // exit this thread break; } mWakeLock.acquire(); sendHeartbeat(); mService.setAlarm(true, (System.currentTimeMillis() + mHeartbeatInterval)); } catch (IOException ioe) { if ((null != mConnThread) && (mIsConnectionRunning)) { mConnThread.notifyOfNetworkProblems(); } HttpConnectionThread.logE("RpgTcpHeartbeatSender.run()", "Could not send HB!", ioe); } catch (Throwable t) { if ((null != mConnThread) && (mIsConnectionRunning)) { mConnThread.notifyOfNetworkProblems(); } HttpConnectionThread.logE("RpgTcpHeartbeatSender.run()", "Could not send HB! Unknown: ", t); } finally { if (mWakeLock.isHeld()) { mWakeLock.release(); } } synchronized (this) { try { wait(mHeartbeatInterval + (mHeartbeatInterval / 5)); } catch (InterruptedException e) { HttpConnectionThread.logE("RpgTcpHeartbeatSender.run()", "Failed sleeping", e); } } } } /** * Prepares the necessary Hessian payload and writes it directly to the open * output-stream of the socket. * * @throws Exception Thrown if there was an unknown problem writing to the * output-stream. * @throws IOException Thrown if there was a problem regarding IO while * writing to the output-stream. */ public void sendHeartbeat() throws IOException, Exception { byte[] rpgMsg = null; try { rpgMsg = getHeartbeatHessianPayload(); } catch(NullPointerException e) { - EngineManager engManager = EngineManager.getInstance(); - LoginEngine loginEngine = engManager.getLoginEngine(); - mConnThread.stopThread(); - ConnectionManager mconn = ConnectionManager.getInstance(); - mconn.onLoginStateChanged(false); - loginEngine.logoutAndRemoveUser(); - - + // Stop connnection and log out + ConnectionManager.getInstance().onLoginStateChanged(false); + EngineManager.getInstance().getLoginEngine().logoutAndRemoveUser(); } try { // Try and issue the request if (Settings.sEnableProtocolTrace) { Long userID = null; AuthSessionHolder auth = LoginEngine.getSession(); if (auth != null) { userID = auth.userID; } HttpConnectionThread.logI("RpgTcpHeartbeatSender.sendHeartbeat()", "\n * Sending a heartbeat for user ID " + userID + "----------------------------------------" + HessianUtils.getInHessian(new ByteArrayInputStream(rpgMsg), true) + "\n"); } if (null != mOs) { synchronized (mOs) { mOs.write(rpgMsg); mOs.flush(); } } } catch (IOException ioe) { HttpConnectionThread.logE("RpgTcpHeartbeatSender.sendHeartbeat()", "Could not write HB to OS!", ioe); throw ioe; } catch (Exception e) { HttpConnectionThread.logE("RpgTcpHeartbeatSender.sendHeartbeat()", "Could not send HB to OS! Unknown: ", e); throw e; } finally { rpgMsg = null; } } /** * Returns a byte-array containing the data needed for sending a heartbeat * to the RPG. * * @throws IOException If there was an exception serializing the hash map to * a hessian byte array. * @return A byte array representing the heartbeat. */ private byte[] getHeartbeatHessianPayload() throws IOException { // hash table for parameters to Hessian encode final Hashtable<String, Object> ht = new Hashtable<String, Object>(); final String timestamp = "" + ((long)System.currentTimeMillis() / MILLIS_PER_SEC); final AuthSessionHolder auth = LoginEngine.getSession(); if(auth == null) { throw new NullPointerException(); } ht.put("auth", AuthUtils .calculateAuth("", new Hashtable<String, Object>(), timestamp, auth)); ht.put("userid", auth.userID); // do Hessian encoding final byte[] payload = HessianEncoder.createHessianByteArray("", ht); payload[1] = (byte)1; payload[2] = (byte)0; final int reqLength = RpgHeader.HEADER_LENGTH + payload.length; final RpgHeader rpgHeader = new RpgHeader(); rpgHeader.setPayloadLength(payload.length); rpgHeader.setReqType(RpgMessageTypes.RPG_TCP_HEARTBEAT); final byte[] rpgMsg = new byte[reqLength]; System.arraycopy(rpgHeader.createHeader(), 0, rpgMsg, 0, RpgHeader.HEADER_LENGTH); if (null != payload) { System.arraycopy(payload, 0, rpgMsg, RpgHeader.HEADER_LENGTH, payload.length); } return rpgMsg; } /** * <p> * Returns true if the heartbeat thread is currently running/active. * </p> * <p> * Calling startConnection() will make this method return as the heartbeat * thread gets started. * </p> * <p> * stopConnection() will stop the connection again and make this method * return false. * </p> * * @return True if the connection is running, false otherwise. */ public boolean getIsActive() { return mIsConnectionRunning; } @Override public void notifyOfWakeupAlarm() { if (Settings.sEnableProtocolTrace) { HttpConnectionThread.logI("HeartbeatSenderThread.notifyOfWakeupAlarm()", "Waking up for a heartbeat!"); } synchronized (this) { notify(); // this will try to send another heartbeat } } }
360/360-Engine-for-Android
a4455949525ad3dd7d9017f71bbee72acb7bc496
uncomment the engine internal timeout handling
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 6b9251a..b9c86ed 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,786 +1,786 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.MePresenceCacheTable; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.ChatMessage; import com.vodafone360.people.datatypes.Conversation; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.PresenceList; import com.vodafone360.people.datatypes.PushAvailabilityEvent; import com.vodafone360.people.datatypes.PushChatMessageEvent; import com.vodafone360.people.datatypes.PushClosedConversationEvent; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.datatypes.SystemNotification.Tags; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Chat; import com.vodafone360.people.service.io.api.Presence; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, ITcpConnectionListener { /** Check every 24 hours **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private final List<TimelineSummaryItem> mFailedMessagesList; // (to, network) /** The list of Users still to be processed. **/ private List<User> mUsers = null; /** * This state indicates there are no more pending presence payload * information to be processed. **/ private static final int IDLE = 0; /** * This state indicates there are some pending presence payload information * to be processed. **/ private static final int UPDATE_PROCESSING_GOING_ON = 1; /** Timeout between each presence update processing. **/ private static final long UPDATE_PRESENCE_TIMEOUT_MILLS = 0; /** The page size i.e the number of presence updates processed at a time. **/ private static final int UPDATE_PRESENCE_PAGE_SIZE = 10; /** The number of pages after which the HandlerAgent is notified. **/ private static final int NOTIFY_AGENT_PAGE_INTERVAL = 5; /** The state of the presence Engine. **/ private int mState = IDLE; /** * Number of pages of presence Updates done. This is used to control when a * notification is sent to the UI. **/ private int mIterations = 0; /** * True if the engine runs for the 1st time. */ private boolean mFirstRun = true; /** * * @param eventCallback * @param databaseHelper */ public PresenceEngine(IEngineEventCallback eventCallback, DatabaseHelper databaseHelper) { super(eventCallback); mEngineId = EngineId.PRESENCE_ENGINE; mDbHelper = databaseHelper; mSendMessagesHash = new Hashtable<String, ChatMessage>(); mFailedMessagesList = new ArrayList<TimelineSummaryItem>(); } @Override public void onCreate() { } @Override public void onDestroy() { if (mDbHelper != null && SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper) != null) { PresenceDbUtils.resetPresenceStatesAcceptForMe(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), mDbHelper); } EngineManager.getInstance().getLoginEngine().removeListener(this); } /** * Checks if the SyncMe and ContactSync Engines have both completed first time sync. * * @return true if both engines have completed first time sync */ private boolean isFirstTimeSyncComplete() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!isFirstTimeSyncComplete()) { LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"); return -1; } /** * need isUiRequestOutstanding() because currently the worker thread is * running and finishing before PresenceEngine.setNextRuntime is called */ if (isCommsResponseOutstanding() || isUiRequestOutstanding()) { LogUtils.logV("PresenceEngine getNextRunTime() comms response outstanding"); return 0; } if (mFirstRun) { getPresenceList(); initSetMyAvailabilityRequestAfterLogin(); mFirstRun = false; } return getCurrentTimeout(); } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + getCurrentTimeout() + "]"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logV("PresenceEngine.run() handled processCommsInQueue()"); return; } if (processTimeout()) { LogUtils.logV("PresenceEngine.run() handled processTimeout()"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logV("PresenceEngine.run(): AgentState.DISCONNECTED"); setPresenceOffline(); } /** * and the getNextRunTime must check the uiRequestReady() function and * return 0 if it is true */ if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { return isUiRequestOutstanding(); } private User getMyAvailabilityStatusFromDatabase() { return PresenceDbUtils.getMeProfilePresenceStatus(mDbHelper); } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (!mLoggedIn) { mFirstRun = true; mFailedMessagesList.clear(); mSendMessagesHash.clear(); setPresenceOffline(); } } /*** * Set the Global presence status to offline. */ private synchronized void setPresenceOffline() { PresenceDbUtils.setPresenceOfflineInDatabase(mDbHelper); // We clear the mUsers of any pending presence updates because this // Offline presence update request should take the highest priority. mUsers = null; mState = IDLE; mEventCallback.getUiAgent().updatePresence(UiAgent.ALL_USERS); } @Override protected void onRequestComplete() { LogUtils.logI("PresenceEngine.onRequestComplete()"); } @Override protected void onTimeoutEvent() { LogUtils.logI("PresenceEngine.onTimeoutEvent()"); switch (mState) { case UPDATE_PROCESSING_GOING_ON: updatePresenceDatabaseNextPage(); break; case IDLE: default: -// if (mLoggedIn) { -// if (isFirstTimeSyncComplete()) { -// getPresenceList(); -// initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); -// // Request to update the UI -// setTimeout(CHECK_FREQUENCY); -// } else { // check after 30 seconds -// LogUtils.logE("Can't run PresenceEngine before the contact" -// + " list is downloaded:3 - set next runtime in 30 seconds"); -// setTimeout(CHECK_FREQUENCY / 20); -// } -// } + if (mLoggedIn) { + if (isFirstTimeSyncComplete()) { + getPresenceList(); + initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); + // Request to update the UI + setTimeout(CHECK_FREQUENCY); + } else { // check after 30 seconds + LogUtils.logE("Can't run PresenceEngine before the contact" + + " list is downloaded:3 - set next runtime in 30 seconds"); + setTimeout(CHECK_FREQUENCY / 20); + } + } break; } } @Override protected void processCommsResponse(DecodedResponse resp) { handleServerResponse(resp.mDataTypes); } private void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg) { UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribedWithChat()) { uiAgent.sendUnsolicitedUiEvent(errorEvent, null); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users List of users that require updating. */ private synchronized void updatePresenceDatabase(List<User> users) { if (users == null || users.size() == 0) { LogUtils.logW("PresenceEngine.updatePresenceDatabase() users is NULL or zero size"); } else { if (mUsers == null) { mUsers = users; } else { // Doing an add one by one is not an efficient way but then // there is an issue in the addAll API. It crashes sometimes. // And the java code for the AddAll API seems to be erroneous. // More investigation is needed on this. for (User user : users) { mUsers.add(user); } } } mState = UPDATE_PROCESSING_GOING_ON; updatePresenceDatabaseNextPage(); } /** * This API makes the presence updates in pages of 10 with a timeout * after each page. The HandlerAgent is notified after every 10 pages. */ private synchronized void updatePresenceDatabaseNextPage(){ UiAgent uiAgent = mEventCallback.getUiAgent(); if(mUsers == null){ mState = IDLE; return; } int listSize = mUsers.size(); int start = 0; int end = UPDATE_PRESENCE_PAGE_SIZE; if(listSize == 0){ mState = IDLE; mUsers = null; return; } else if(listSize < end) { end = listSize; } List<User> userSubset = mUsers.subList(start, end); if ((userSubset != null)) { long idListeningTo = UiAgent.ALL_USERS; if (uiAgent != null) { idListeningTo = uiAgent.getLocalContactId(); } boolean updateUI = PresenceDbUtils.updateDatabase(userSubset, idListeningTo, mDbHelper); userSubset.clear(); // Send the update notification to UI for every UPDATE_PRESENCE_PAGE_SIZE*NOTIFY_AGENT_PAGE_INTERVAL updates. if (updateUI) { if (mUsers.size() == 0 || NOTIFY_AGENT_PAGE_INTERVAL == mIterations) { if (uiAgent != null) { uiAgent.updatePresence(idListeningTo); } mIterations = 0; } else { mIterations++; } } this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ synchronized public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Method used to set availability of me profile when user logs in. * This is primarily used for reacting to login/connection state changes. */ private void initSetMyAvailabilityRequestAfterLogin() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } String meProfileUserId = Long.toString(PresenceDbUtils.getMeProfileUserId(mDbHelper)); Hashtable<String, String> availability = new Hashtable<String, String>(); ArrayList<Identity> identityList = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if ((identityList.size() != 0)) { for (int i=0; i<identityList.size(); i++) { Identity myIdentity = identityList.get(i); availability.put(myIdentity.mNetwork, OnlineStatus.ONLINE.toString()); } } User meUser = new User(); meUser.setLocalContactId(Long.valueOf(meProfileUserId)); meUser.setPayload(presenceList); updateMyPresenceInDatabase(meUser); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } // Get presences Hashtable<String, String> presenceList = getPresencesForStatus(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** * Changes the user's availability. * * @param status - Hashtable<String, String> of pairs <communityName, statusName>. */ public void setMyAvailability(Hashtable<String, String> presenceHash) { if (presenceHash == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceHash); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } /** * Changes the user's availability. * * @param network - SocialNetwork to set presence on. * @param status - OnlineStatus presence status to set. */ public void setMyAvailability(SocialNetwork network, OnlineStatus status) { LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+ network + "=" + status); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); final NetworkPresence newPresence = new NetworkPresence(userId, network.ordinal(), status.ordinal()); presenceList.add(newPresence); User me = new User(userId, null); me.setPayload(presenceList); MePresenceCacheTable.updateCache(newPresence, mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now Hashtable<String, String> presenceHash = new Hashtable<String, String>(); presenceHash.put(network.toString(), status.toString()); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage();
360/360-Engine-for-Android
e8f4727799902c04b3e80732a652ac16d65fa59e
PAND-2389 getPresenceList and setAvailability calls sequence fixed, no setAvailability is called from the IdentitiesEngine
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 7fb3463..cd70c2d 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,981 +1,971 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.identities; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import android.os.Bundle; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; -import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.BaseEngine; -import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Identities; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.ThirdPartyAccount; /** * Engine responsible for handling retrieval and validation of Identities (e.g. * 3rd party/web accounts). The Identities engine can fetch a list of available * accounts, and set required capabilities and validate credentials for * specified accounts. */ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { /** * States for IdentitiesEngine. States are based on the requests that the * engine needs to handle. */ private enum State { IDLE, FETCHING_IDENTITIES, VALIDATING_IDENTITY_CREDENTIALS, SETTING_IDENTITY_STATUS, GETTING_MY_IDENTITIES, GETTING_MY_CHATABLE_IDENTITIES, DELETE_IDENTITY } /** * Mutex for thread synchronisation */ private final Object mMutex = new Object(); /** * Container class for Identity Capability Status request. Consists of a * network, identity id and a filter containing the required capabilities. */ private static class IdentityStatusRequest { private String mNetwork; private String mIdentityId; private String mIdentityStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setIdentityStatus(String status) { mIdentityStatus = status; } } /** * Container class encapsulating an Identity validation request containing: * dry-run flag, network, user-name, password, set of required capabilities. */ private static class IdentityValidateCredentialsRequest { /** Performs a dry run if true. */ private boolean mDryRun; /** Network to sign into. */ private String mNetwork; /** Username to sign into identity with. */ private String mUserName; /** Password to sign into identity with. */ private String mPassword; private Map<String, Boolean> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } /** * * Container class for Delete Identity request. Consist network and identity id. * */ private static class DeleteIdentityRequest { /** Network to delete.*/ private String mNetwork; /** IdentityID which needs to be Deleted.*/ private String mIdentityId; } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mMyIdentityList; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; /** * Maintaining DeleteIdentityRequest so that it can be later removed from * maintained cache. **/ private DeleteIdentityRequest identityToBeDeleted; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; mMyIdentityList = new ArrayList<Identity>(); mAvailableIdentityList = new ArrayList<Identity>(); mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { final ArrayList<Identity> availableIdentityList; synchronized(mAvailableIdentityList) { // make a shallow copy availableIdentityList = new ArrayList<Identity>(mAvailableIdentityList); } if ((availableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return availableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { final ArrayList<Identity> myIdentityList; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } if ((myIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return myIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = getMyThirdPartyChattableIdentities(); // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chattableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chattableIdentities; } /** * * Takes all third party identities that have a chat capability set to true. * * @return A list of chattable 3rd party identities the user is signed in to. If the retrieval identities failed the returned list will be empty. * */ public ArrayList<Identity> getMyThirdPartyChattableIdentities() { final ArrayList<Identity> chattableIdentities = new ArrayList<Identity>(); final ArrayList<Identity> myIdentityList; final int identityListSize; synchronized(mMyIdentityList) { // make a shallow copy myIdentityList = new ArrayList<Identity>(mMyIdentityList); } identityListSize = myIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = myIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue)) { chattableIdentities.add(identity); break; } } } return chattableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Delete the given social network. * * @param network Name of the identity, * @param identityId Id of identity. */ public final void addUiDeleteIdentityRequest(final String network, final String identityId) { LogUtils.logD("IdentityEngine.addUiRemoveIdentity()"); DeleteIdentityRequest data = new DeleteIdentityRequest(); data.mNetwork = network; data.mIdentityId = identityId; /**maintaining the sent object*/ setIdentityToBeDeleted(data); addUiRequestToQueue(ServiceUiRequest.DELETE_IDENTITY, data); } /** * Setting the DeleteIdentityRequest object. * * @param data */ private void setIdentityToBeDeleted(final DeleteIdentityRequest data) { identityToBeDeleted = data; } /** * Return the DeleteIdentityRequest object. * */ private DeleteIdentityRequest getIdentityToBeDeleted() { return identityToBeDeleted; } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; case DELETE_IDENTITY: executeDeleteIdentityRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to delete the identity as specified . (Request is not issued if there * is currently no connectivity). * * @param data bundled request data containing network and identityId. */ private void executeDeleteIdentityRequest(final Object data) { if (!isConnected()) { completeUiRequest(ServiceStatus.ERROR_NO_INTERNET); } newState(State.DELETE_IDENTITY); DeleteIdentityRequest reqData = (DeleteIdentityRequest) data; if (!setReqId(Identities.deleteIdentity(this, reqData.mNetwork, reqData.mIdentityId))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(DecodedResponse resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if ((null == resp) || (null == resp.mDataTypes)) { LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); return; } // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; case BaseDataType.IDENTITY_DELETION_DATA_TYPE: handleDeleteIdentity(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); } } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); + if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { // check if any chat identities were added to set them to "online" - Hashtable<String, String> presenceHash = new Hashtable<String, String>(); - List<String> cachedNetworkNames = new ArrayList<String>(); - for (Identity identity: mMyIdentityList) { - cachedNetworkNames.add(identity.mNetwork); - } mMyIdentityList.clear(); for (BaseDataType item : data) { Identity identity = (Identity)item; mMyIdentityList.add(identity); - if (!cachedNetworkNames.contains(identity.mNetwork)) { - presenceHash.put(identity.mNetwork, OnlineStatus.ONLINE.toString()); - } - } - if (!presenceHash.isEmpty()) { - EngineManager.getInstance().getPresenceEngine().setMyAvailability(presenceHash); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); + + LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response of request to delete the identity. The response * should be a status that whether the operation is succeeded or not. The * response will be a status result otherwise ERROR_UNEXPECTED_RESPONSE if * the response is not as expected. * * @param data * List of BaseDataTypes generated from Server response. */ private void handleDeleteIdentity(final List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus( BaseDataType.IDENTITY_DELETION_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { for (BaseDataType item : data) { if (item.getType() == BaseDataType.IDENTITY_DELETION_DATA_TYPE) { synchronized(mMyIdentityList) { // iterating through the subscribed identities for (Identity identity : mMyIdentityList) { if (identity.mIdentityId .equals(getIdentityToBeDeleted().mIdentityId)) { mMyIdentityList.remove(identity); break; } } } completeUiRequest(ServiceStatus.SUCCESS); return; } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } } completeUiRequest(errorStatus, bu); } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; synchronized (mAvailableIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mAvailableIdentityList); } } else { requestKey = KEY_MY_IDS; synchronized (mMyIdentityList) { // provide a shallow copy idBundle = new ArrayList<Identity>(mMyIdentityList); } } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } /** * * Retrieves the filter for the getAvailableIdentities and getMyIdentities * calls. * * @return The identities filter in form of a bundle. * */ private Bundle getIdentitiesFilter() { Bundle b = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); l.add(IdentityCapability.CapabilityID.get_own_status.name()); b.putStringArrayList("capability", l); return b; } @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); - } + } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } /** * Generate Map containing String capability filters for m supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, List<String>> prepareStringFilter(Bundle filter) { Map<String, List<String>> returnFilter = null; if (filter != null && filter.keySet().size() > 0) { returnFilter = new Hashtable<String, List<String>>(); for (String key : filter.keySet()) { returnFilter.put(key, filter.getStringArrayList(key)); } } else { returnFilter = null; } return returnFilter; } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ /** {@inheritDoc} */ @Override public final void onReset() { super.onReset(); mMyIdentityList.clear(); mAvailableIdentityList.clear(); mStatusList.clear(); mState = State.IDLE; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of Identity objects, can be NULL. * @return TRUE if the given Identity contains a Facebook account. */ public boolean isFacebookInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_FACEBOOK)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given Identity contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given Identity contains a Hyves account. */ public boolean isHyvesInThirdPartyAccountList() { if (mMyIdentityList != null) { synchronized(mMyIdentityList) { for (Identity identity : mMyIdentityList) { if (identity.mName.toLowerCase().contains(ThirdPartyAccount.SNS_TYPE_HYVES)) { return true; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Hyves not found in list"); return false; } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 980c618..6b9251a 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,914 +1,891 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.MePresenceCacheTable; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.ChatMessage; import com.vodafone360.people.datatypes.Conversation; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.PresenceList; import com.vodafone360.people.datatypes.PushAvailabilityEvent; import com.vodafone360.people.datatypes.PushChatMessageEvent; import com.vodafone360.people.datatypes.PushClosedConversationEvent; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.datatypes.SystemNotification.Tags; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Chat; import com.vodafone360.people.service.io.api.Presence; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, ITcpConnectionListener { /** Check every 24 hours **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private final List<TimelineSummaryItem> mFailedMessagesList; // (to, network) /** The list of Users still to be processed. **/ private List<User> mUsers = null; /** * This state indicates there are no more pending presence payload * information to be processed. **/ private static final int IDLE = 0; /** * This state indicates there are some pending presence payload information * to be processed. **/ private static final int UPDATE_PROCESSING_GOING_ON = 1; /** Timeout between each presence update processing. **/ private static final long UPDATE_PRESENCE_TIMEOUT_MILLS = 0; /** The page size i.e the number of presence updates processed at a time. **/ private static final int UPDATE_PRESENCE_PAGE_SIZE = 10; /** The number of pages after which the HandlerAgent is notified. **/ private static final int NOTIFY_AGENT_PAGE_INTERVAL = 5; /** The state of the presence Engine. **/ private int mState = IDLE; /** * Number of pages of presence Updates done. This is used to control when a * notification is sent to the UI. **/ private int mIterations = 0; /** * True if the engine runs for the 1st time. */ - private boolean firstRun = true; + private boolean mFirstRun = true; /** * * @param eventCallback * @param databaseHelper */ public PresenceEngine(IEngineEventCallback eventCallback, DatabaseHelper databaseHelper) { super(eventCallback); mEngineId = EngineId.PRESENCE_ENGINE; mDbHelper = databaseHelper; mSendMessagesHash = new Hashtable<String, ChatMessage>(); mFailedMessagesList = new ArrayList<TimelineSummaryItem>(); } @Override public void onCreate() { } @Override public void onDestroy() { if (mDbHelper != null && SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper) != null) { PresenceDbUtils.resetPresenceStatesAcceptForMe(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), mDbHelper); } EngineManager.getInstance().getLoginEngine().removeListener(this); } /** * Checks if the SyncMe and ContactSync Engines have both completed first time sync. * * @return true if both engines have completed first time sync */ private boolean isFirstTimeSyncComplete() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!isFirstTimeSyncComplete()) { LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"); return -1; } /** * need isUiRequestOutstanding() because currently the worker thread is * running and finishing before PresenceEngine.setNextRuntime is called */ if (isCommsResponseOutstanding() || isUiRequestOutstanding()) { LogUtils.logV("PresenceEngine getNextRunTime() comms response outstanding"); return 0; } - if (firstRun) { + if (mFirstRun) { getPresenceList(); initSetMyAvailabilityRequestAfterLogin(); - firstRun = false; + mFirstRun = false; } return getCurrentTimeout(); } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + getCurrentTimeout() + "]"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logV("PresenceEngine.run() handled processCommsInQueue()"); return; } if (processTimeout()) { LogUtils.logV("PresenceEngine.run() handled processTimeout()"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logV("PresenceEngine.run(): AgentState.DISCONNECTED"); setPresenceOffline(); } /** * and the getNextRunTime must check the uiRequestReady() function and * return 0 if it is true */ if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { return isUiRequestOutstanding(); } private User getMyAvailabilityStatusFromDatabase() { return PresenceDbUtils.getMeProfilePresenceStatus(mDbHelper); } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; - if (mLoggedIn) { - if (isFirstTimeSyncComplete()) { - getPresenceList(); - setTimeout(CHECK_FREQUENCY); - } - } else { - firstRun = true; + if (!mLoggedIn) { + mFirstRun = true; mFailedMessagesList.clear(); mSendMessagesHash.clear(); setPresenceOffline(); } } /*** * Set the Global presence status to offline. */ private synchronized void setPresenceOffline() { PresenceDbUtils.setPresenceOfflineInDatabase(mDbHelper); // We clear the mUsers of any pending presence updates because this // Offline presence update request should take the highest priority. mUsers = null; mState = IDLE; mEventCallback.getUiAgent().updatePresence(UiAgent.ALL_USERS); } @Override protected void onRequestComplete() { LogUtils.logI("PresenceEngine.onRequestComplete()"); } @Override protected void onTimeoutEvent() { LogUtils.logI("PresenceEngine.onTimeoutEvent()"); switch (mState) { case UPDATE_PROCESSING_GOING_ON: updatePresenceDatabaseNextPage(); break; case IDLE: default: - if (mLoggedIn) { - if (isFirstTimeSyncComplete()) { - getPresenceList(); - initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); - // Request to update the UI - setTimeout(CHECK_FREQUENCY); - } else { // check after 30 seconds - LogUtils.logE("Can't run PresenceEngine before the contact" - + " list is downloaded:3 - set next runtime in 30 seconds"); - setTimeout(CHECK_FREQUENCY / 20); - } - } +// if (mLoggedIn) { +// if (isFirstTimeSyncComplete()) { +// getPresenceList(); +// initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); +// // Request to update the UI +// setTimeout(CHECK_FREQUENCY); +// } else { // check after 30 seconds +// LogUtils.logE("Can't run PresenceEngine before the contact" +// + " list is downloaded:3 - set next runtime in 30 seconds"); +// setTimeout(CHECK_FREQUENCY / 20); +// } +// } + break; } } @Override protected void processCommsResponse(DecodedResponse resp) { handleServerResponse(resp.mDataTypes); } private void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg) { UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribedWithChat()) { uiAgent.sendUnsolicitedUiEvent(errorEvent, null); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users List of users that require updating. */ private synchronized void updatePresenceDatabase(List<User> users) { if (users == null || users.size() == 0) { LogUtils.logW("PresenceEngine.updatePresenceDatabase() users is NULL or zero size"); } else { if (mUsers == null) { mUsers = users; } else { // Doing an add one by one is not an efficient way but then // there is an issue in the addAll API. It crashes sometimes. // And the java code for the AddAll API seems to be erroneous. // More investigation is needed on this. for (User user : users) { mUsers.add(user); } } } mState = UPDATE_PROCESSING_GOING_ON; updatePresenceDatabaseNextPage(); } /** * This API makes the presence updates in pages of 10 with a timeout * after each page. The HandlerAgent is notified after every 10 pages. */ private synchronized void updatePresenceDatabaseNextPage(){ UiAgent uiAgent = mEventCallback.getUiAgent(); if(mUsers == null){ mState = IDLE; return; } int listSize = mUsers.size(); int start = 0; int end = UPDATE_PRESENCE_PAGE_SIZE; if(listSize == 0){ mState = IDLE; mUsers = null; return; } else if(listSize < end) { end = listSize; } List<User> userSubset = mUsers.subList(start, end); if ((userSubset != null)) { long idListeningTo = UiAgent.ALL_USERS; if (uiAgent != null) { idListeningTo = uiAgent.getLocalContactId(); } boolean updateUI = PresenceDbUtils.updateDatabase(userSubset, idListeningTo, mDbHelper); userSubset.clear(); // Send the update notification to UI for every UPDATE_PRESENCE_PAGE_SIZE*NOTIFY_AGENT_PAGE_INTERVAL updates. if (updateUI) { if (mUsers.size() == 0 || NOTIFY_AGENT_PAGE_INTERVAL == mIterations) { if (uiAgent != null) { uiAgent.updatePresence(idListeningTo); } mIterations = 0; } else { mIterations++; } } this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ - public void getPresenceList() { + synchronized public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Method used to set availability of me profile when user logs in. * This is primarily used for reacting to login/connection state changes. */ private void initSetMyAvailabilityRequestAfterLogin() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } String meProfileUserId = Long.toString(PresenceDbUtils.getMeProfileUserId(mDbHelper)); Hashtable<String, String> availability = new Hashtable<String, String>(); ArrayList<Identity> identityList = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if ((identityList.size() != 0)) { for (int i=0; i<identityList.size(); i++) { Identity myIdentity = identityList.get(i); - if(myIdentity.mNetwork.equals(SocialNetwork.GOOGLE.toString())) { - NetworkPresence networkPresence = new NetworkPresence(meProfileUserId, SocialNetwork.GOOGLE.ordinal(), OnlineStatus.ONLINE.ordinal()); - presenceList.add(networkPresence); - availability.put(SocialNetwork.GOOGLE.toString(), OnlineStatus.ONLINE.toString()); - } else if(myIdentity.mNetwork.equals(SocialNetwork.HYVES_NL.toString())) { - NetworkPresence networkPresence = new NetworkPresence(meProfileUserId, SocialNetwork.HYVES_NL.ordinal(), OnlineStatus.ONLINE.ordinal()); - presenceList.add(networkPresence); - availability.put(SocialNetwork.HYVES_NL.toString(), OnlineStatus.ONLINE.toString()); - } else if(myIdentity.mNetwork.equals(SocialNetwork.FACEBOOK_COM.toString())) { - NetworkPresence networkPresence = new NetworkPresence(meProfileUserId, SocialNetwork.FACEBOOK_COM.ordinal(), OnlineStatus.ONLINE.ordinal()); - presenceList.add(networkPresence); - availability.put(SocialNetwork.FACEBOOK_COM.toString(), OnlineStatus.ONLINE.toString()); - } else if(myIdentity.mNetwork.equals(SocialNetwork.MICROSOFT.toString())) { - NetworkPresence networkPresence = new NetworkPresence(meProfileUserId, SocialNetwork.MICROSOFT.ordinal(), OnlineStatus.ONLINE.ordinal()); - presenceList.add(networkPresence); - availability.put(SocialNetwork.MICROSOFT.toString(), OnlineStatus.ONLINE.toString()); - } else if(myIdentity.mNetwork.equals(SocialNetwork.MOBILE.toString())) { - NetworkPresence networkPresence = new NetworkPresence(meProfileUserId, SocialNetwork.MOBILE.ordinal(), OnlineStatus.ONLINE.ordinal()); - presenceList.add(networkPresence); - availability.put(SocialNetwork.MOBILE.toString(), OnlineStatus.ONLINE.toString()); - } + availability.put(myIdentity.mNetwork, OnlineStatus.ONLINE.toString()); } } User meUser = new User(); meUser.setLocalContactId(Long.valueOf(meProfileUserId)); meUser.setPayload(presenceList); updateMyPresenceInDatabase(meUser); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } // Get presences Hashtable<String, String> presenceList = getPresencesForStatus(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** * Changes the user's availability. * * @param status - Hashtable<String, String> of pairs <communityName, statusName>. */ public void setMyAvailability(Hashtable<String, String> presenceHash) { if (presenceHash == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceHash); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); MePresenceCacheTable.updateCache(me.getPayload(), mDbHelper.getWritableDatabase()); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } - - /** + + /** * Changes the user's availability. * * @param network - SocialNetwork to set presence on. * @param status - OnlineStatus presence status to set. */ public void setMyAvailability(SocialNetwork network, OnlineStatus status) { LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+ network + "=" + status); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); if (!isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.setMyAvailability(): skip - First time contact sync has not finished yet"); return; } String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); final NetworkPresence newPresence = new NetworkPresence(userId, network.ordinal(), status.ordinal()); presenceList.add(newPresence); User me = new User(userId, null); me.setPayload(presenceList); MePresenceCacheTable.updateCache(newPresence, mDbHelper.getWritableDatabase()); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now Hashtable<String, String> presenceHash = new Hashtable<String, String>(); presenceHash.put(network.toString(), status.toString()); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } @Override public void onConnectionStateChanged(int state) { if (mLoggedIn && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initializeAvailabilityFromDb(); break; case STATE_CONNECTING: case STATE_DISCONNECTED: + mFirstRun = true; setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * Initializes or re-initializes availability from the Database. * If there are cached presences then these will be used * instead of values from the presence table. */ private void initializeAvailabilityFromDb() { final User user = getMyAvailabilityStatusFromDatabase(); ArrayList<NetworkPresence> cachedPresences = MePresenceCacheTable.getCache(mDbHelper.getReadableDatabase()); if(cachedPresences != null) { user.setPayload(cachedPresences); } initSetMyAvailabilityRequest(user); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if(identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); for(Identity identity : identities) { presences.put(identity.mNetwork, statusString); } return presences; } @Override public void onReset() { // reset the engine as if it was just created super.onReset(); - firstRun = true; + mFirstRun = true; mLoggedIn = false; mIterations = 0; mState = IDLE; mUsers = null; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java index 9ab10cc..5ad8fc5 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,449 +1,449 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.interfaces; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import android.os.Bundle; import android.os.Handler; import android.os.Message; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.MainApplication; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.agent.NetworkAgentState; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.utils.LogUtils; /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback * @see com.vodafone360.people.service.interfaces.IPeopleService */ public class IPeopleServiceImpl implements IPeopleService, IEngineEventCallback { private final List<Handler> mUiEventCallbackList = new ArrayList<Handler>(); private IWorkerThreadControl mWorkerThreadControl; private RemoteService mService; private NetworkAgent mNetworkAgent; private UiAgent mHandlerAgent; private ApplicationCache mApplicationCache; /** * Initialises the object, creating the UiAgent. * * @param workerThreadControl Provides access to worker thread control * functions. * @param service Provides access to remote service functions (mainly used * to retrieve context). */ public IPeopleServiceImpl(IWorkerThreadControl workerThreadControl, RemoteService service) { mWorkerThreadControl = workerThreadControl; mService = service; mHandlerAgent = new UiAgent((MainApplication)service.getApplication(), service); mApplicationCache = ((MainApplication)service.getApplication()).getCache(); } /*** * Sets the ServiceAgent, as this needs to be called after the constructor. * * @param agent Handle to ServiceAgent. */ public void setNetworkAgent(NetworkAgent agent) { mNetworkAgent = agent; } /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#onUiEvent(UiEvent, * int, int, Object) */ @Override public void onUiEvent(ServiceUiRequest event, int arg1, int arg2, Object data) { synchronized (mUiEventCallbackList) { for (Handler handler : mUiEventCallbackList) { Message msg = handler.obtainMessage(event.ordinal(), data); msg.arg1 = arg1; msg.arg2 = arg2; if (!handler.sendMessage(msg)) { LogUtils.logE("IPeopleServiceImpl.onUiEvent() Sending msg FAILED"); } } } } /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#kickWorkerThread() */ @Override public void kickWorkerThread() { mWorkerThreadControl.kickWorkerThread(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#addEventCallback(Handler) */ @Override public void addEventCallback(Handler uiHandler) { synchronized (mUiEventCallbackList) { if (!mUiEventCallbackList.contains(uiHandler)) { mUiEventCallbackList.add(uiHandler); } } } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#removeEventCallback(Handler) */ @Override public void removeEventCallback(Handler uiHandler) { synchronized (mUiEventCallbackList) { mUiEventCallbackList.remove(uiHandler); } } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#checkForUpdates() */ @Override public void checkForUpdates() { EngineManager.getInstance().getUpgradeEngine().checkForUpdates(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMyThirdPartyIdentities() */ public ArrayList<Identity> getMyThirdPartyIdentities() { return EngineManager.getInstance().getIdentityEngine().getMyThirdPartyIdentities(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyIdentities() */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { return EngineManager.getInstance().getIdentityEngine().getAvailableThirdPartyIdentities(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyChattableIdentities() */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { return EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchPrivacyStatement() */ @Override public void fetchPrivacyStatement() { EngineManager.getInstance().getLoginEngine().addUiFetchPrivacyStatementRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchTermsOfService() */ @Override public void fetchTermsOfService() { EngineManager.getInstance().getLoginEngine().addUiFetchTermsOfServiceRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchUsernameState(String) */ @Override public void fetchUsernameState(String userName) { EngineManager.getInstance().getLoginEngine().addUiGetUsernameStateRequest(userName); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getLoginRequired() */ @Override public boolean getLoginRequired() { EngineManager manager = EngineManager.getInstance(); return manager.getLoginEngine().getLoginRequired(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getRoamingNotificationType() */ @Override public int getRoamingNotificationType() { return mService.getNetworkAgent().getRoamingNotificationType(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getRoamingDeviceSetting() */ @Override public boolean getRoamingDeviceSetting() { return mService.getNetworkAgent().getRoamingDeviceSetting(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#notifyDataSettingChanged(InternetAvail) */ @Override public void notifyDataSettingChanged(InternetAvail val) { mService.getNetworkAgent().notifyDataSettingChanged(val); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#logon(LoginDetails) */ @Override public void logon(LoginDetails loginDetails) { EngineManager manager = EngineManager.getInstance(); manager.getLoginEngine().addUiLoginRequest(loginDetails); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#register(RegistrationDetails) */ @Override public void register(RegistrationDetails details) { EngineManager.getInstance().getLoginEngine().addUiRegistrationRequest(details); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setNewUpdateFrequency() */ @Override public void setNewUpdateFrequency() { EngineManager.getInstance().getUpgradeEngine().setNewUpdateFrequency(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setShowRoamingNotificationAgain(boolean) */ @Override public void setShowRoamingNotificationAgain(boolean showAgain) { mService.getNetworkAgent().setShowRoamingNotificationAgain(showAgain); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startContactSync() */ @Override public void startContactSync() { EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); EngineManager.getInstance().getContactSyncEngine().addUiStartFullSync(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startBackgroundContactSync(long) */ @Override public void startBackgroundContactSync(long delay) { EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); EngineManager.getInstance().getContactSyncEngine().addUiStartServerSync(delay); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#pingUserActivity() */ @Override public void pingUserActivity() { EngineManager.getInstance().getContactSyncEngine().pingUserActivity(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#validateIdentityCredentials(boolean, * String, String, String, Bundle) */ @Override public void validateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { EngineManager.getInstance().getIdentityEngine().addUiValidateIdentityCredentials(dryRun, network, username, password, identityCapabilityStatus); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startStatusesSync() */ @Override public void startStatusesSync() { EngineManager.getInstance().getActivitiesEngine().addStatusesSyncRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getNetworkAgentState() */ @Override public NetworkAgentState getNetworkAgentState() { return mNetworkAgent.getNetworkAgentState(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setNetowrkAgentState(NetworkAgentState) */ @Override public void setNetworkAgentState(NetworkAgentState state) { mNetworkAgent.setNetworkAgentState(state); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getPresenceList(long) */ @Override public void getPresenceList(long contactId) { - EngineManager.getInstance().getPresenceEngine().getPresenceList(); +// EngineManager.getInstance().getPresenceEngine().getPresenceList(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(OnlineStatus) */ @Override public void setAvailability(OnlineStatus status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(SocialNetwork, OnlineStatus) */ @Override public void setAvailability(SocialNetwork network, OnlineStatus status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(network, status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(Hashtable<String, String> status) */ @Override public void setAvailability(Hashtable<String, String> status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#subscribe(Handler, * long, boolean) */ @Override public void subscribe(Handler handler, Long contactId, boolean chat) { mHandlerAgent.subscribe(handler, contactId, chat); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#unsubscribe(Handler) */ @Override public void unsubscribe(Handler handler) { mHandlerAgent.unsubscribe(handler); } /** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#getUiAgent() */ @Override public UiAgent getUiAgent() { return mHandlerAgent; } /** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#getApplicationCache() */ @Override public ApplicationCache getApplicationCache() { return mApplicationCache; } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#sendMessage(long, * String, int) */ @Override public void sendMessage(long localContactId, String body, int networkId) { EngineManager.getInstance().getPresenceEngine() .sendMessage(localContactId, body, networkId); } @Override public void setIdentityStatus(String network, String identityId, boolean identityStatus) { EngineManager.getInstance().getIdentityEngine().addUiSetIdentityStatus(network, identityId, identityStatus); } @Override public void getStatuses() { EngineManager.getInstance().getActivitiesEngine().addStatusesSyncRequest(); } @Override public void getMoreTimelines() { EngineManager.getInstance().getActivitiesEngine().addOlderTimelinesRequest(); } @Override public void getOlderStatuses() { EngineManager.getInstance().getActivitiesEngine().addGetOlderStatusesRequest(); } @Override public void uploadMeProfile() { EngineManager.getInstance().getSyncMeEngine().addUpdateMeProfileContactRequest(); } @Override public void uploadMyStatus(String statusText) { EngineManager.getInstance().getSyncMeEngine().addUpdateMyStatusRequest(statusText); } @Override public void downloadMeProfileFirstTime() { EngineManager.getInstance().getSyncMeEngine().addGetMeProfileContactFirstTimeRequest(); } @Override public void updateChatNotification(long localContactId) { mHandlerAgent.updateChat(localContactId, false); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#deleteIdentity(String,String) */ @Override public void deleteIdentity(final String network, final String identityId) { EngineManager.getInstance().getIdentityEngine() .addUiDeleteIdentityRequest(network, identityId); } } \ No newline at end of file
360/360-Engine-for-Android
743cecceaff333bfd2416208a978ed1485f95e7d
Fix for PAND-2304: Error during first sync - data connection is off by default
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index a837a33..8dbde0a 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,1015 +1,1018 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.accounts.AccountManager; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.OperationApplicationException; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.provider.ContactsContract; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.Settings; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Event; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.Website; import android.text.TextUtils; import android.util.SparseArray; import com.vodafone360.people.R; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.VCardHelper.Name; import com.vodafone360.people.datatypes.VCardHelper.Organisation; import com.vodafone360.people.datatypes.VCardHelper.PostalAddress; +import com.vodafone360.people.service.SyncAdapter; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * The implementation of the NativeContactsApi for the Android 2.X platform. */ public class NativeContactsApi2 extends NativeContactsApi { /** * Convenience Projection to fetch only a Raw Contact's ID and Native * Account Type */ private static final String[] CONTACTID_PROJECTION = new String[] { RawContacts._ID, RawContacts.ACCOUNT_TYPE }; /** * Raw ID Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_RAW_ID = 0; /** * Account Type Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_ACCOUNT_TYPE = 1; /** * Group ID Projection */ private static final String[] GROUPID_PROJECTION = new String[] { Groups._ID }; /** * Vendor specific account. Only used in 2.x API. */ private static Account sPhoneAccount = null; /** * Regular expression for a date that can be handled by the People Client at * present. Matches the following cases: N-n-n n-n-N Where: - 'n' * corresponds to one or two digits - 'N' corresponds to two or 4 digits */ private static final String COMPLETE_DATE_REGEX = "(?:^\\d{2,4}-\\d{1,2}-\\d{1,2}$|^\\d{1,2}-\\d{1,2}-\\d{2,4}$)"; /** * 'My Contacts' System group where clause */ private static final String MY_CONTACTS_GROUP_WHERE_CLAUSE = Groups.SYSTEM_ID + "=\"Contacts\""; /** * Selection where clause for a NULL Account */ private static final String NULL_ACCOUNT_WHERE_CLAUSE = RawContacts.ACCOUNT_NAME + " IS NULL AND " + RawContacts.ACCOUNT_TYPE + " IS NULL"; /** * Selection where clause for an Organization detail. */ private static final String ORGANIZATION_DETAIL_WHERE_CLAUSE = RawContacts.Data.MIMETYPE + "=\"" + Organization.CONTENT_ITEM_TYPE + "\""; /** * The list of Uri that need to be listened to for contacts changes on * native side. */ private static final Uri[] sUri = { ContactsContract.RawContacts.CONTENT_URI, ContactsContract.Data.CONTENT_URI }; /** * Holds mapping from a NAB type (MIME) to a VCard Key */ private static final HashMap<String, Integer> sFromNabContentTypeToKeyMap; /** * Holds mapping from a VCard Key to a NAB type (MIME) */ private static final SparseArray<String> sFromKeyToNabContentTypeArray; static { sFromNabContentTypeToKeyMap = new HashMap<String, Integer>(9, 1); sFromNabContentTypeToKeyMap.put(StructuredName.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NAME); sFromNabContentTypeToKeyMap.put(Nickname.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NICKNAME); sFromNabContentTypeToKeyMap.put(Phone.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_PHONE); sFromNabContentTypeToKeyMap.put(Email.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_EMAIL); sFromNabContentTypeToKeyMap.put(StructuredPostal.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ADDRESS); sFromNabContentTypeToKeyMap.put(Organization.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ORG); sFromNabContentTypeToKeyMap.put(Website.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_URL); sFromNabContentTypeToKeyMap.put(Note.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NOTE); sFromNabContentTypeToKeyMap.put(Event.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_DATE); // sFromNabContentTypeToKeyMap.put(Photo.CONTENT_ITEM_TYPE, ContactChange.KEY_PHOTO); sFromKeyToNabContentTypeArray = new SparseArray<String>(10); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NAME, StructuredName.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NICKNAME, Nickname.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_PHONE, Phone.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_EMAIL, Email.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ADDRESS, StructuredPostal.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ORG, Organization.CONTENT_ITEM_TYPE); // Special case: VCARD_TITLE maps to the same NAB type as sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_TITLE, Organization.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_URL, Website.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NOTE, Note.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_DATE, Event.CONTENT_ITEM_TYPE); // sFromKeyToNabContentTypeArray.append(ContactChange.KEY_PHOTO, Photo.CONTENT_ITEM_TYPE); } /** * The observer registered by the upper layer. */ private ContactsObserver mAbstractedObserver; /** * Content values used for writing to NAB. */ private final ContentValues mValues = new ContentValues(); /** * The content observers that listens for native contacts changes. */ private final ContentObserver[] mContentObservers = new ContentObserver[sUri.length]; /** * Array of row ID in the groups table to the "My Contacts" System Group. * The reason for this being an array is because there may be multiple * "My Contacts" groups (Platform Bug!?). */ private long[] mMyContactsGroupRowIds = null; /** * Arguably another example where Organization and Title force us into extra * effort. We use this value to pass the correct detail ID when an 'add * detail' is done for one the two although the other is already present. * Make sure to reset this value for every UpdateContact operation */ private long mExistingOrganizationId = ContactChange.INVALID_ID; /** * Flag to check if we have already read a Birthday detail */ private boolean mHaveReadBirthday = false; /** * Yield value for our ContentProviderOperations. */ private boolean mYield = true; /** * Batch used for Contact Writing operations. */ private BatchOperation mBatch = new BatchOperation(); /** * Inner class for applying batches. TODO: Move to own class if batches * become supported in other areas */ private class BatchOperation { // List for storing the batch mOperations ArrayList<ContentProviderOperation> mOperations; /** * Default constructor */ public BatchOperation() { mOperations = new ArrayList<ContentProviderOperation>(); } /** * Current size of the batch * * @return Size of the batch */ public int size() { return mOperations.size(); } /** * Adds a new operation to the batch * * @param cpo The */ public void add(ContentProviderOperation cpo) { mOperations.add(cpo); } /** * Clears all operations in the batch Effectively resets the batch. */ public void clear() { mOperations.clear(); } public ContentProviderResult[] execute() { ContentProviderResult[] resultArray = null; if (mOperations.size() > 0) { // Apply the mOperations to the content provider try { resultArray = mCr.applyBatch(ContactsContract.AUTHORITY, mOperations); } catch (final OperationApplicationException e1) { LogUtils.logE("storing contact data failed", e1); } catch (final RemoteException e2) { LogUtils.logE("storing contact data failed", e2); } mOperations.clear(); } return resultArray; } } /** * Convenience interface to map the generic DATA column names to the People * profile detail column names. */ private interface PeopleProfileColumns { /** * 360 People profile MIME Type */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/com.vodafone360.people.profile"; /** * 360 People Contact's profile ID (Corresponds to Contact's Internal * Contact ID) */ public static final String DATA_PID = Data.DATA1; /** * 360 People Contact profile Summary */ public static final String DATA_SUMMARY = Data.DATA2; /** * 360 People Contact profile detail */ public static final String DATA_DETAIL = Data.DATA3; } /** * This class holds a native content observer that will be notified in case * of changes on the registered URI. */ private class NativeContentObserver extends ContentObserver { public NativeContentObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { LogUtils.logI("NativeContactsApi2.NativeContentObserver.onChange(" + selfChange + ")"); mAbstractedObserver.onChange(); } } /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { LogUtils.logI("NativeContactsApi2.registerObserver()"); if (mAbstractedObserver != null) { throw new RuntimeException( "Only one observer at a time supported... Please unregister first."); } mAbstractedObserver = observer; final ContentResolver cr = mContext.getContentResolver(); for (int i = 0; i < mContentObservers.length; i++) { mContentObservers[i] = new NativeContentObserver(); cr.registerContentObserver(sUri[i], true, mContentObservers[i]); } } /** * @see NativeContactsApi#unregisterObserver(ContactsObserver) */ @Override public void unregisterObserver() { LogUtils.logI("NativeContactsApi2.unregisterObserver()"); if (mCr != null) { mAbstractedObserver = null; for (int i = 0; i < mContentObservers.length; i++) { if (mContentObservers[i] != null) { mCr.unregisterContentObserver(mContentObservers[i]); mContentObservers[i] = null; } } } } /** * @see NativeContactsApi#initialize() */ @Override protected void initialize() { // perform here any one time initialization sPhoneAccount = getVendorSpecificAccount(); } /** * @see NativeContactsApi#getAccounts() */ @Override public Account[] getAccounts() { AccountManager accountManager = AccountManager.get(mContext); final android.accounts.Account[] accounts2xApi = accountManager.getAccounts(); Account[] accounts = null; if (accounts2xApi.length > 0) { accounts = new Account[accounts2xApi.length]; for (int i = 0; i < accounts2xApi.length; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } } return accounts; } /** * Reads vendor specific accounts from settings and through accountmanager. * Some phones with custom ui like sense have additional account that we * have to take care of. This method tryes to read them * * @return Account object if vendor specific account is found, null * otherwise */ public Account getVendorSpecificAccount() { // first read the settings String[] PROJECTION = { Settings.ACCOUNT_NAME, Settings.ACCOUNT_TYPE, Settings.UNGROUPED_VISIBLE }; // Get a cursor with all people Cursor cursor = mCr.query(Settings.CONTENT_URI, PROJECTION, null, null, null); // Got no cursor? Return with null! if (null == cursor) { return null; } try { String[] values = new String[cursor.getCount()]; for (int i = 0; i < values.length; i++) { cursor.moveToNext(); if (isVendorSpecificAccount(cursor.getString(1))) { return new Account(cursor.getString(0), cursor.getString(1)); } } } catch (Exception exc) { return null; } CursorUtils.closeCursor(cursor); // nothing found in the settings? try accountmanager Account[] accounts = getAccounts(); if (accounts == null) { return null; } for (Account account : accounts) { if (isVendorSpecificAccount(account.getType())) { return account; } } return null; } /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override public Account[] getAccountsByType(int type) { switch (type) { // people and google type lead to the same block the difference is // then handled inside in two if statements. // Otherwise we would have a lot of redundant code, case PEOPLE_ACCOUNT_TYPE: case GOOGLE_ACCOUNT_TYPE: { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts2xApi = null; // For people account set the people account type string... if (PEOPLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); } // .. and for google the same only with google string. if (GOOGLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(GOOGLE_ACCOUNT_TYPE_STRING); } final int numAccounts = accounts2xApi.length; if (numAccounts > 0) { Account[] accounts = new Account[numAccounts]; for (int i = 0; i < numAccounts; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } return accounts; } else { return null; } } case PHONE_ACCOUNT_TYPE: { if (sPhoneAccount == null) { return null; } return new Account[] { sPhoneAccount }; } default: return null; } } /** * @see NativeContactsApi#addPeopleAccount(String) */ @Override public boolean addPeopleAccount(String username) { boolean isAdded = false; try { android.accounts.Account account = new android.accounts.Account(username, PEOPLE_ACCOUNT_TYPE_STRING); AccountManager accountMan = AccountManager.get(mContext); isAdded = accountMan.addAccountExplicitly(account, null, null); if (isAdded) { if (VersionUtils.isHtcSenseDevice(mContext)) { createSettingsEntryForAccount(username); requestSyncAdapterInitialization(account); - } + } + // Need to do our Sync Adapter initialization logic here + SyncAdapter.initialize(account, ContactsContract.AUTHORITY); } } catch (Exception ex) { LogUtils.logE("People Account creation failed because of exception:\n", ex); } if (isAdded) { // Updating MyContacts Group IDs here for now because it needs to be // done one time just before first time sync. // In the future, this code may change if we modify // the way we retrieve contact IDs. fetchMyContactsGroupRowIds(); } return isAdded; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { return getPeopleAccount() != null; } /** * @see NativeContactsApi#removePeopleAccount() */ @Override public void removePeopleAccount() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); if (accounts != null && accounts.length > 0) { accountMan.removeAccount(accounts[0], null, null); } } /** * @see NativeContactsApi#getContactIds(Account) */ @Override public long[] getContactIds(Account account) { // Need to construct a where clause if (account != null) { final StringBuffer clauseBuffer = new StringBuffer(); clauseBuffer.append(RawContacts.ACCOUNT_NAME); clauseBuffer.append("=\""); clauseBuffer.append(account.getName()); clauseBuffer.append("\" AND "); clauseBuffer.append(RawContacts.ACCOUNT_TYPE); clauseBuffer.append("=\""); clauseBuffer.append(account.getType()); clauseBuffer.append('\"'); return getContactIds(clauseBuffer.toString()); } else { return getContactIds(NULL_ACCOUNT_WHERE_CLAUSE); } } /** * @see NativeContactsApi#getContact(long) */ @Override public ContactChange[] getContact(long nabContactId) { // Reset the boolean flags mHaveReadOrganization = false; mHaveReadBirthday = false; final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, nabContactId); final Uri dataUri = Uri.withAppendedPath(rawContactUri, RawContacts.Data.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(dataUri, null, null, null, null); try { if (cursor != null && cursor.getCount() > 0) { final List<ContactChange> ccList = new ArrayList<ContactChange>(); while (cursor.moveToNext()) { readDetail(cursor, ccList, nabContactId); } return ccList.toArray(new ContactChange[ccList.size()]); } } finally { CursorUtils.closeCursor(cursor); } return null; } /** * @see NativeContactsApi#addContact(Account, ContactChange[]) */ @Override public ContactChange[] addContact(Account account, ContactChange[] ccList) { // Make sure to reset all the member variables we need mYield = true; mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mValues.clear(); mBatch.clear(); mValues.put(RawContacts.ACCOUNT_TYPE, account.getType()); mValues.put(RawContacts.ACCOUNT_NAME, account.getName()); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI)).withYieldAllowed(mYield) .withValues(mValues); mBatch.add(builder.build()); // according to the calling method ccList here has at least 1 element, ccList[0] is not null final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc != null) { final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } putDetail(cc); addValuesToBatch(ContactChange.INVALID_ID); } } // Special case for the organization/title if it was flagged in the // putDetail call putOrganization(ccList); addValuesToBatch(ContactChange.INVALID_ID); // Add 360 profile detail addProfileAction(ccList[0].getInternalContactId()); // Execute the batch and Generate ID changes from it return executeNewContactBatch(ccList); } /** * @see NativeContactsApi#updateContact(ContactChange[]) */ @Override public ContactChange[] updateContact(ContactChange[] ccList) { if (ccList == null || ccList.length == 0) { LogUtils.logW("NativeContactsApi2.updateContact() nothing to update - empty ccList!"); return null; } // Make sure to reset all the member variables we need mYield = true; mBatch.clear(); mValues.clear(); mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mExistingOrganizationId = ContactChange.INVALID_ID; final long nabContactId = ccList[0].getNabContactId(); if (nabContactId == ContactChange.INVALID_ID) { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update request because of invalid NAB Contact ID. Internal Contact ID is " + ccList[0].getInternalContactId()); return null; } final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } switch (cc.getType()) { case ContactChange.TYPE_ADD_DETAIL: putDetail(cc); addValuesToBatch(nabContactId); // not a new contact break; case ContactChange.TYPE_UPDATE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { putDetail(cc); addUpdateValuesToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update to detail for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; case ContactChange.TYPE_DELETE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { addDeleteDetailToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring detail deletion for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; default: break; } } updateOrganization(ccList, nabContactId); // Execute the batch and Generate ID changes from it return executeUpdateContactBatch(ccList); } /** * @see NativeContactsApi#removeContact(long) */ @Override public void removeContact(long nabContactId) { mCr.delete(addCallerIsSyncAdapterParameter(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId)), null, null); } /** * @see NativeContactsApi#getMasterSyncAutomatically */ @Override public boolean getMasterSyncAutomatically() { return ContentResolver.getMasterSyncAutomatically(); } /** * @see NativeContactsApi#setSyncable(boolean) */ @Override public void setSyncable(boolean syncable) { android.accounts.Account account = getPeopleAccount(); if(account != null) { ContentResolver. setIsSyncable(account, ContactsContract.AUTHORITY, syncable ? 1 : 0); } } /** * @see NativeContactsApi#setSyncAutomatically(boolean) */ @Override public void setSyncAutomatically(boolean syncAutomatically) { android.accounts.Account account = getPeopleAccount(); if(account != null) { ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, syncAutomatically); if(syncAutomatically) { // Kick start sync ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); } else { // Cancel ongoing just in case ContentResolver.cancelSync(account, ContactsContract.AUTHORITY); } } } /** * @see NativeContactsApi#isKeySupported(int) */ @Override public boolean isKeySupported(int key) { // Only supported if in the SparseArray return sFromKeyToNabContentTypeArray.indexOfKey(key) >= 0; } /** * Inner (private) method for getting contact ids. Allows a cleaner * separation the public API method. * * @param selection The where clause for the operation * @return An array containing the Contact IDs that have been found */ private long[] getContactIds(final String selection) { // Store ids in a temporary array because of possible null values long[] tempIds = null; int idCount = 0; final Cursor cursor = mCr.query(RawContacts.CONTENT_URI, CONTACTID_PROJECTION, selection, null, null); if (cursor == null) { return null; } try { final int cursorCount = cursor.getCount(); if (cursorCount > 0) { tempIds = new long[cursorCount]; while (cursor.moveToNext()) { final long id = cursor.getLong(CONTACTID_PROJECTION_RAW_ID); final String accountType = cursor.getString(CONTACTID_PROJECTION_ACCOUNT_TYPE); // TODO: Remove hardcoding (if statement) if (TextUtils.isEmpty(accountType) || accountType.equals(NativeContactsApi.PEOPLE_ACCOUNT_TYPE_STRING) || isVendorSpecificAccount(accountType)) { //PAND-2125 || isContactInMyContactsGroup(id)) { tempIds[idCount] = id; idCount++; } } } } finally { CursorUtils.closeCursor(cursor); } if (idCount > 0) { // Here we copy the array to strip any eventual nulls at the end of // the tempIds array final long[] ids = new long[idCount]; System.arraycopy(tempIds, 0, ids, 0, idCount); return ids; } return null; } /** * Fetches the IDs corresponding to the "My Contacts" System Group The * reason why we return an array is because there may be multiple * "My Contacts" groups. * * @return Array containing all IDs of the "My Contacts" group or null if * none exist */ private void fetchMyContactsGroupRowIds() { final Cursor cursor = mCr.query(Groups.CONTENT_URI, GROUPID_PROJECTION, MY_CONTACTS_GROUP_WHERE_CLAUSE, null, null); if (cursor == null) { return; } try { final int count = cursor.getCount(); if (count > 0) { mMyContactsGroupRowIds = new long[count]; for (int i = 0; i < count; i++) { cursor.moveToNext(); mMyContactsGroupRowIds[i] = cursor.getLong(0); } } } finally { CursorUtils.closeCursor(cursor); } } /** * Checks if a Contact is in the "My Contacts" System Group * * @param nabContactId ID of the Contact to check * @return true if the Contact is in the Group, false if not */ /** * PAND-2125 * The decision has been made to stop the import of Google contacts on 2.x devices. * From now on, we will only import native addressbook contacts. */ /* private boolean isContactInMyContactsGroup(long nabContactId) { boolean belongs = false; if (mMyContactsGroupRowIds != null) { final Uri dataUri = Uri.withAppendedPath(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId), RawContacts.Data.CONTENT_DIRECTORY); // build query containing row ID values final StringBuilder sb = new StringBuilder(); sb.append(MY_CONTACTS_MULTI_GROUP_MEMBERSHIP); final int rowIdCount = mMyContactsGroupRowIds.length; for (int i = 0; i < rowIdCount; i++) { sb.append(mMyContactsGroupRowIds[i]); if (i < rowIdCount - 1) { sb.append(','); } } sb.append(')'); final Cursor cursor = mCr.query(dataUri, null, sb.toString(), null, null); try { belongs = cursor != null && cursor.getCount() > 0; } finally { CursorUtils.closeCursor(cursor); } } return belongs; } */ /** * Reads a Contact Detail from a Cursor into the supplied Contact Change * List. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to read Detail into * @param nabContactId NAB ID of the Contact */ private void readDetail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String mimetype = CursorUtils.getString(cursor, Data.MIMETYPE); final Integer key = sFromNabContentTypeToKeyMap.get(mimetype); if (key != null) { switch (key.intValue()) { case ContactChange.KEY_VCARD_NAME: readName(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_NICKNAME: readNickname(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_PHONE: readPhone(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_EMAIL: readEmail(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ADDRESS: readAddress(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ORG: // Only one Organization can be read (CAB limitation!) if (!mHaveReadOrganization) { readOrganization(cursor, ccList, nabContactId); } break; case ContactChange.KEY_VCARD_URL: readWebsite(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_DATE: if (!mHaveReadBirthday) { readBirthday(cursor, ccList, nabContactId); } break; default: // The default case is also a valid key final String value = CursorUtils.getString(cursor, Data.DATA1); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Data._ID); final ContactChange cc = new ContactChange(key, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } break; } } } /** * Reads an name detail as a {@link ContactChange} from the provided cursor. * For this type of detail we need to use a VCARD (semicolon separated) * value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readName(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using display name only to check if there is a valid name to read final String displayName = CursorUtils.getString(cursor, StructuredName.DISPLAY_NAME); if (!TextUtils.isEmpty(displayName)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredName._ID); // VCard Helper data type (CAB) final Name name = new Name(); // NAB: Given name -> CAB: First name name.firstname = CursorUtils.getString(cursor, StructuredName.GIVEN_NAME); // NAB: Family name -> CAB: Surname name.surname = CursorUtils.getString(cursor, StructuredName.FAMILY_NAME); // NAB: Prefix -> CAB: Title name.title = CursorUtils.getString(cursor, StructuredName.PREFIX); // NAB: Middle name -> CAB: Middle name name.midname = CursorUtils.getString(cursor, StructuredName.MIDDLE_NAME); // NAB: Suffix -> CAB: Suffixes name.suffixes = CursorUtils.getString(cursor, StructuredName.SUFFIX); // NOTE: Ignoring Phonetics (DATA7, DATA8 and DATA9)! // TODO: Need to get middle name and concatenate into value final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NAME, VCardHelper .makeName(name), ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an nickname detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readNickname(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Nickname.NAME); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Nickname._ID); /* * TODO: Decide what to do with nickname: Can only have one in VF360 * but NAB Allows more than one! diff --git a/src/com/vodafone360/people/service/SyncAdapter.java b/src/com/vodafone360/people/service/SyncAdapter.java index d0c5c1f..e706f3d 100644 --- a/src/com/vodafone360/people/service/SyncAdapter.java +++ b/src/com/vodafone360/people/service/SyncAdapter.java @@ -1,303 +1,304 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import android.accounts.Account; import android.accounts.AccountManager; import android.content.AbstractThreadedSyncAdapter; import android.content.BroadcastReceiver; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SyncResult; import android.content.SyncStatusObserver; import android.os.Bundle; import android.os.Handler; import android.provider.ContactsContract; import com.vodafone360.people.MainApplication; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.utils.LogUtils; /** * SyncAdapter implementation which basically just ties in with * the old Contacts Sync Engine code for the moment and waits for the sync to be finished. * In the future we may want to improve this, particularly if the sync * is actually be done in this thread which would also enable disable sync altogether. */ public class SyncAdapter extends AbstractThreadedSyncAdapter implements IContactSyncObserver { // TODO: RE-ENABLE SYNC VIA SYSTEM // /** // * Direct access to Sync Engine stored for convenience // */ // private final ContactSyncEngine mSyncEngine = EngineManager.getInstance().getContactSyncEngine(); // // /** // * Boolean used to remember if we have requested a sync. // * Useful to ignore events // */ // private boolean mPerformSyncRequested = false; // /** * Delay when checking our Sync Setting when there is a authority auto-sync setting change. * This waiting time is necessary because in case it is our sync adapter authority setting * that changes we cannot query in the callback because the value is not yet changed! */ private static final int SYNC_SETTING_CHECK_DELAY = 2000; /** * Same as ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS * The reason we have this is just because the constant is not publicly defined before 2.2. */ private static final int SYNC_OBSERVER_TYPE_SETTINGS = 1; /** * Application object instance */ private final MainApplication mApplication; /** * Broadcast receiver used to listen for changes in the Master Auto Sync setting * intent: com.android.sync.SYNC_CONN_STATUS_CHANGED */ private final BroadcastReceiver mAutoSyncChangeBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { actOnAutoSyncSettings(); } }; /** * Observer for the global sync status setting. * There is no known way to only observe our sync adapter's setting. */ private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() { @Override public void onStatusChanged(int which) { mHandler.postDelayed(mRunnable, SYNC_SETTING_CHECK_DELAY); } }; /** * Handler used to post to a runnable in order to wait * for a short time before checking the sync adapter * authority sync setting after a global change occurs. */ private final Handler mHandler = new Handler(); /** * Runnable used to post to a runnable in order to wait * for a short time before checking the sync adapter * authority sync setting after a global change occurs. * The reason we use this kind of mechanism is because: * a) There is an intent(com.android.sync.SYNC_CONN_STATUS_CHANGED) * we can listen to for the Master Auto-sync but, * b) The authority auto-sync observer pattern using ContentResolver * listens to EVERY sync adapter setting on the device AND * when the callback is received the value is not yet changed so querying for it is useless. */ private final Runnable mRunnable = new Runnable() { @Override public void run() { actOnAutoSyncSettings(); } }; public SyncAdapter(Context context, MainApplication application) { - // No automatic initialization (false) - super(context, false); + // Automatically initialized (true) due to PAND-2304 + super(context, true); mApplication = application; context.registerReceiver(mAutoSyncChangeBroadcastReceiver, new IntentFilter( "com.android.sync.SYNC_CONN_STATUS_CHANGED")); ContentResolver.addStatusChangeListener( SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver); - // Necessary in case of Application udpate + // Necessary in case of Application update forceSyncSettingsInCaseOfAppUpdate(); // Register for sync event callbacks // TODO: RE-ENABLE SYNC VIA SYSTEM // mSyncEngine.addEventCallback(this); } /** * {@inheritDoc} */ @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { if(extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false)) { - initializeSyncAdapter(account, authority); + initialize(account, authority); return; } actOnAutoSyncSettings(); // TODO: RE-ENABLE SYNC VIA SYSTEM // try { // synchronized(this) { // mPerformSyncRequested = true; // if(!mSyncEngine.isSyncing()) { // mSyncEngine.startFullSync(); // } // // while(mSyncEngine.isSyncing()) { // wait(POOLING_WAIT_INTERVAL); // } // mPerformSyncRequested = false; // } // } catch (InterruptedException e) { // e.printStackTrace(); // } } /** * @see IContactSyncObserver#onContactSyncStateChange(Mode, State, State) */ @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { // TODO: RE-ENABLE SYNC VIA SYSTEM // synchronized(this) { // /* // * This check is done so that we can also update the native UI // * when the client devices to sync on it own // */ // if(!mPerformSyncRequested && // mode != Mode.NONE) { // mPerformSyncRequested = true; // Account account = new Account( // LoginPreferences.getUsername(), // NativeContactsApi2.PEOPLE_ACCOUNT_TYPE); // ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); // } // } } /** * @see IContactSyncObserver#onProgressEvent(State, int) */ @Override public void onProgressEvent(State currentState, int percent) { // Nothing to do } /** * @see IContactSyncObserver#onSyncComplete(ServiceStatus) */ @Override public void onSyncComplete(ServiceStatus status) { // Nothing to do } /** * Initializes Sync settings for this Sync Adapter * @param account The account associated with the initialization * @param authority The authority of the content */ - private void initializeSyncAdapter(Account account, String authority) { - ContentResolver.setIsSyncable(account, authority, 1); + public static void initialize(Account account, String authority) { + ContentResolver.setIsSyncable(account, authority, 1); // > 0 means syncable ContentResolver.setSyncAutomatically(account, authority, true); } /** * Checks if this Sync Adapter is allowed to Sync Automatically * Basically just checking if the Master and its own Auto-sync are on. * The Master Auto-sync takes precedence over the authority Auto-sync. * @return true if the settings are enabled, false otherwise */ private boolean canSyncAutomatically() { Account account = getPeopleAccount(); if (account == null) { // There's no account in the system anyway so // just say true to avoid any issues with the application. return true; } boolean masterSyncAuto = ContentResolver.getMasterSyncAutomatically(); boolean syncAuto = ContentResolver.getSyncAutomatically(account, ContactsContract.AUTHORITY); - LogUtils.logD("SyncAdapter.canSyncAutomatically() [masterSync=" + masterSyncAuto + ", syncAuto=" + syncAuto + "]"); + LogUtils.logD("SyncAdapter.canSyncAutomatically() [masterSync=" + + masterSyncAuto + ", syncAuto=" + syncAuto + "]"); return masterSyncAuto && syncAuto; } /** * Sets the application data connection setting depending on whether or not * the Sync Adapter is allowed to Sync Automatically. * If Automatic Sync is enabled then connection is to online ("always connect") * Otherwise connection is set to offline ("manual connect") */ private synchronized void actOnAutoSyncSettings() { if(canSyncAutomatically()) { // Enable data connection mApplication.setInternetAvail(InternetAvail.ALWAYS_CONNECT, false); } else { // Disable data connection mApplication.setInternetAvail(InternetAvail.MANUAL_CONNECT, false); } } /** * This method is essentially needed to force the sync settings * to a consistent state in case of an Application Update. * This is because old versions of the client do not set * the sync adapter to syncable for the contacts authority. */ private void forceSyncSettingsInCaseOfAppUpdate() { NativeContactsApi nabApi = NativeContactsApi.getInstance(); nabApi.setSyncable(true); nabApi.setSyncAutomatically( mApplication.getInternetAvail() == InternetAvail.ALWAYS_CONNECT); } /** * Gets the first People Account found on the device or * null if none is found. * Beware! This method is basically duplicate code from * NativeContactsApi2.getPeopleAccount(). * Duplicating the code was found to be cleanest way to acess the functionality. * @return The Android People account found or null */ private Account getPeopleAccount() { android.accounts.Account[] accounts = AccountManager.get(mApplication).getAccountsByType(NativeContactsApi.PEOPLE_ACCOUNT_TYPE_STRING); if (accounts != null && accounts.length > 0) { Account ret = new Account(accounts[0].name, accounts[0].type); return ret; } return null; } }
360/360-Engine-for-Android
e0f31bc9ba6f2bcb689e61517f6fa12af5ab567e
Synchronized ResponseQueue which could have lead to an effect very similar to the stuck socket effect.
diff --git a/src/com/vodafone360/people/service/io/ResponseQueue.java b/src/com/vodafone360/people/service/io/ResponseQueue.java index 5414d36..fb49b16 100644 --- a/src/com/vodafone360/people/service/io/ResponseQueue.java +++ b/src/com/vodafone360/people/service/io/ResponseQueue.java @@ -1,276 +1,277 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.LogUtils; /** * Queue of responses received from server. These may be either responses to * requests issued by the People client or unsolicited ('Push') messages. The * content of these Responses will have already been decoded by the * DecoderThread and converted to data-types understood by the People Client. */ public class ResponseQueue { /** * The list of responses held by this queue. An array-list of Responses. */ private final List<DecodedResponse> mResponses = new ArrayList<DecodedResponse>(); /** * The engine manager holding the various engines to cross check where * responses belong to. */ private EngineManager mEngMgr = null; /** * Class encapsulating a decoded response from the server A Response * contains; a request id which should match a request id from a request * issued by the People Client (responses to non-RPG requests or * non-solicited messages will not have a request id), the request data, a * list of decoded BaseDataTypes generated from the response content and an * engine id informing the framework which engine the response should be * routed to. */ public static class DecodedResponse { public static enum ResponseType { /** An unknown response in case anything went wrong. */ UNKNOWN, /** A response for a request that timed out. */ SERVER_ERROR, /** A response that timed out before it arrived from the server. */ TIMED_OUT_RESPONSE, /** Represents a push message that was pushed by the server */ PUSH_MESSAGE, /** The response type for available identities. */ GET_AVAILABLE_IDENTITIES_RESPONSE, /** The response type for my identities. */ GET_MY_IDENTITIES_RESPONSE, /** The response type for set identity capability */ SET_IDENTITY_CAPABILITY_RESPONSE, /** The response type for validate identity credentials */ VALIDATE_IDENTITY_CREDENTIALS_RESPONSE, /** The response type for get activities calls. */ GET_ACTIVITY_RESPONSE, /** The response type for get session by credentials calls. */ LOGIN_RESPONSE, /** The response type for bulkupdate contacts calls. */ BULKUPDATE_CONTACTS_RESPONSE, /** The response type for get contacts changes calls. */ GET_CONTACTCHANGES_RESPONSE, /** The response type for get get me calls. */ GETME_RESPONSE, /** The response type for get contact group relation calls. */ GET_CONTACT_GROUP_RELATIONS_RESPONSE, /** The response type for get groups calls. */ GET_GROUPS_RESPONSE, /** The response type for add contact calls. */ ADD_CONTACT_RESPONSE, /** The response type for signup user crypted calls. */ SIGNUP_RESPONSE, /** The response type for get public key calls. */ RETRIEVE_PUBLIC_KEY_RESPONSE, /** The response type for delete contacts calls. */ DELETE_CONTACT_RESPONSE, /** The response type for delete contact details calls. */ DELETE_CONTACT_DETAIL_RESPONSE, /** The response type for get presence calls. */ GET_PRESENCE_RESPONSE, /** The response type for create conversation calls. */ CREATE_CONVERSATION_RESPONSE, /** The response type for get t&cs. */ GET_T_AND_C_RESPONSE, /** The response type for get privacy statement. */ GET_PRIVACY_STATEMENT_RESPONSE, /** The response type for removing the identity. */ DELETE_IDENTITY_RESPONSE; // TODO add more types here and remove them from the BaseDataType. Having them in ONE location is better than in dozens!!! } /** The type of the response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ private int mResponseType; /** The request ID the response came in for. */ public Integer mReqId; /** The response items (e.g. identities of a getAvailableIdentities call) to store for the response. */ public List<BaseDataType> mDataTypes = new ArrayList<BaseDataType>(); /** The ID of the engine the response should be worked off in. */ public EngineId mSource; /** * Constructs a response object with request ID, the data and the engine * ID the response belongs to. * * @param reqId The corresponding request ID for the response. * @param data The data of the response. * @param source The originating engine ID. * @param responseType The response type. Values can be found in Response.ResponseType. * */ public DecodedResponse(Integer reqId, List<BaseDataType> data, EngineId source, final int responseType) { mReqId = reqId; mDataTypes = data; mSource = source; mResponseType = responseType; } /** * The response type for this response. The types are defined in Response.ResponseType. * * @return The response type of this response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ public int getResponseType() { return mResponseType; } } /** * Protected constructor to highlight the singleton nature of this class. */ protected ResponseQueue() { } /** * Gets an instance of the ResponseQueue as part of the singleton pattern. * * @return The instance of ResponseQueue. */ public static ResponseQueue getInstance() { return ResponseQueueHolder.rQueue; } /** * Use Initialization on demand holder pattern */ private static class ResponseQueueHolder { private static final ResponseQueue rQueue = new ResponseQueue(); } /** * Adds a response item to the queue. * * @param reqId The request ID to add the response for. * @param data The response data to add to the queue. * @param source The corresponding engine that fired off the request for the * response. */ public void addToResponseQueue(final DecodedResponse response) { synchronized (QueueManager.getInstance().lock) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.UNKNOWN_DATA_TYPE, response.mDataTypes); if (status == ServiceStatus.ERROR_INVALID_SESSION) { EngineManager em = EngineManager.getInstance(); if (em != null) { LogUtils.logE("Logging out the current user because of invalide session"); em.getLoginEngine().logoutAndRemoveUser(); return; } } - mResponses.add(response); + synchronized (mResponses) { + mResponses.add(response); + } Request request = RequestQueue.getInstance().removeRequest(response.mReqId); if (request != null) { // we suppose the response being handled by the same engine // that issued the request with the given id response.mSource = request.mEngineId; } mEngMgr = EngineManager.getInstance(); if (mEngMgr != null) { mEngMgr.onCommsInMessage(response.mSource); } } } /** * Retrieves the next response from the response list if there is one and it is equal to the * passed engine ID. * * @param source The originating engine id that requested this response. * @return Response The first response that matches the given engine or null * if no response was found. */ public DecodedResponse getNextResponse(EngineId source) { DecodedResponse resp = null; - Iterator<DecodedResponse> iterator = mResponses.iterator(); - while (iterator.hasNext()) { - resp = iterator.next(); - - if ((null != resp) && (resp.mSource == source)) { - // remove response if the source engine is equal to the response's engine - iterator.remove(); - - if (source != null) { - LogUtils.logV("ResponseQueue.getNextResponse() Returning a response to engine[" - + source.name() + "]"); - } - - return resp; - } else if ((null == resp) || (null == resp.mSource)) { - LogUtils.logE("Either the response or its source was null. Response: " + resp); - } + synchronized (mResponses) { + Iterator<DecodedResponse> iterator = mResponses.iterator(); + + while (iterator.hasNext()) { + resp = iterator.next(); + + if ((null != resp) && (resp.mSource == source)) { + // remove response if the source engine is equal to the response's engine + iterator.remove(); + + if (source != null) { + LogUtils.logV("ResponseQueue.getNextResponse() Returning a response to engine[" + + source.name() + "]"); + } + + return resp; + } else if ((null == resp) || (null == resp.mSource)) { + LogUtils.logE("Either the response or its source was null. Response: " + resp); + } + } } return null; } - /** - * Get number of items currently in the response queue. - * - * @return number of items currently in the response queue. - */ - private int responseCount() { - return mResponses.size(); - } - /** * Test if we have response for the specified request id. * * @param reqId Request ID. * @return true If we have a response for this ID. */ protected synchronized boolean responseExists(int reqId) { boolean exists = false; - for (int i = 0; i < responseCount(); i++) { - if (mResponses.get(i).mReqId != null && mResponses.get(i).mReqId.intValue() == reqId) { - exists = true; - break; - } + + synchronized (mResponses) { + int responseCount = mResponses.size(); + + for (int i = 0; i < responseCount; i++) { + if (mResponses.get(i).mReqId != null && mResponses.get(i).mReqId.intValue() == reqId) { + exists = true; + break; + } + } } return exists; } }
360/360-Engine-for-Android
49525b9f5783f42d774bffb7b2defb64db0ece98
Removed comments. See code review.
diff --git a/src/com/vodafone360/people/database/tables/ActivitiesTable.java b/src/com/vodafone360/people/database/tables/ActivitiesTable.java index 43a011b..6bfd8dd 100644 --- a/src/com/vodafone360/people/database/tables/ActivitiesTable.java +++ b/src/com/vodafone360/people/database/tables/ActivitiesTable.java @@ -361,1025 +361,1025 @@ public abstract class ActivitiesTable { append(Field.TITLE).append(SqlUtils.COMMA). append(Field.DESCRIPTION).append(SqlUtils.COMMA). append(Field.PREVIEW_URL).append(SqlUtils.COMMA). append(Field.STORE).append(SqlUtils.COMMA). append(Field.FLAG).append(SqlUtils.COMMA). append(Field.PARENT_ACTIVITY).append(SqlUtils.COMMA). append(Field.HAS_CHILDREN).append(SqlUtils.COMMA). append(Field.VISIBILITY).append(SqlUtils.COMMA). append(Field.MORE_INFO).append(SqlUtils.COMMA). append(Field.CONTACT_ID).append(SqlUtils.COMMA). append(Field.USER_ID).append(SqlUtils.COMMA). append(Field.CONTACT_NAME).append(SqlUtils.COMMA). append(Field.LOCAL_CONTACT_ID).append(SqlUtils.COMMA). append(Field.CONTACT_NETWORK).append(SqlUtils.COMMA). append(Field.CONTACT_ADDRESS).append(SqlUtils.COMMA). append(Field.CONTACT_AVATAR_URL).append(SqlUtils.COMMA). append(Field.INCOMING); return StringBufferPool.toStringThenRelease(fullQuery); } /** * Fetches activities information from a cursor at the current position. The * {@link #getFullQueryList()} method should be used to make the query. * * @param cursor The cursor returned by the query * @param activityItem An empty activity object that will be filled with the * result * @param activityContact An empty activity contact object that will be * filled */ public static void getQueryData(final Cursor cursor, final ActivityItem activityItem, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityItem. **/ activityItem.localActivityId = SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); activityItem.activityId = SqlUtils.setLong(cursor, Field.ACTIVITY_ID.toString(), null); activityItem.time = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); activityItem.type = SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); activityItem.uri = SqlUtils.setString(cursor, Field.URI.toString()); activityItem.title = SqlUtils.setString(cursor, Field.TITLE.toString()); activityItem.description = SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); activityItem.previewUrl = SqlUtils.setString(cursor, Field.PREVIEW_URL.toString()); activityItem.store = SqlUtils.setString(cursor, Field.STORE.toString()); activityItem.activityFlags = SqlUtils.setInt(cursor, Field.FLAG.toString(), null); activityItem.parentActivity = SqlUtils.setLong(cursor, Field.PARENT_ACTIVITY.toString(), null); activityItem.hasChildren = SqlUtils.setBoolean(cursor, Field.HAS_CHILDREN.toString(), activityItem.hasChildren); activityItem.visibilityFlags = SqlUtils.setInt(cursor, Field.VISIBILITY.toString(), null); // TODO: Field MORE_INFO is not used, consider deleting. /** Populate ActivityContact. **/ getQueryData(cursor, activityContact); } /** * Fetches activities information from a cursor at the current position. The * {@link #getFullQueryList()} method should be used to make the query. * * @param cursor The cursor returned by the query. * @param activityContact An empty activity contact object that will be * filled */ public static void getQueryData(final Cursor cursor, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityContact. **/ activityContact.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); activityContact.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); activityContact.mName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); activityContact.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); activityContact.mNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); activityContact.mAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); activityContact.mAvatarUrl = SqlUtils.setString(cursor, Field.CONTACT_AVATAR_URL.toString()); } /*** * Provides a ContentValues object that can be used to update the table. * * @param item The source activity item * @param contactIdx The index of the contact to use for the update, or null * to exclude contact specific information. * @return ContentValues for use in an SQL update or insert. * @note Items that are NULL will be not modified in the database. */ private static ContentValues fillUpdateData(final ActivityItem item, final Integer contactIdx) { DatabaseHelper.trace(false, "DatabaseHelper.fillUpdateData()"); ContentValues activityItemValues = new ContentValues(); ActivityContact ac = null; if (contactIdx != null) { ac = item.contactList.get(contactIdx); } activityItemValues.put(Field.ACTIVITY_ID.toString(), item.activityId); activityItemValues.put(Field.TIMESTAMP.toString(), item.time); if (item.type != null) { activityItemValues.put(Field.TYPE.toString(), item.type.getTypeCode()); } if (item.uri != null) { activityItemValues.put(Field.URI.toString(), item.uri); } /** TODO: Not sure if we need this. **/ // activityItemValues.put(Field.INCOMING.toString(), false); activityItemValues.put(Field.TITLE.toString(), item.title); activityItemValues.put(Field.DESCRIPTION.toString(), item.description); if (item.previewUrl != null) { activityItemValues.put(Field.PREVIEW_URL.toString(), item.previewUrl); } if (item.store != null) { activityItemValues.put(Field.STORE.toString(), item.store); } if (item.activityFlags != null) { activityItemValues.put(Field.FLAG.toString(), item.activityFlags); } if (item.parentActivity != null) { activityItemValues.put(Field.PARENT_ACTIVITY.toString(), item.parentActivity); } if (item.hasChildren != null) { activityItemValues.put(Field.HAS_CHILDREN.toString(), item.hasChildren); } if (item.visibilityFlags != null) { activityItemValues.put(Field.VISIBILITY.toString(), item.visibilityFlags); } if (ac != null) { activityItemValues.put(Field.CONTACT_ID.toString(), ac.mContactId); activityItemValues.put(Field.USER_ID.toString(), ac.mUserId); activityItemValues.put(Field.CONTACT_NAME.toString(), ac.mName); activityItemValues.put(Field.LOCAL_CONTACT_ID.toString(), ac.mLocalContactId); if (ac.mNetwork != null) { activityItemValues.put(Field.CONTACT_NETWORK.toString(), ac.mNetwork); } if (ac.mAddress != null) { activityItemValues.put(Field.CONTACT_ADDRESS.toString(), ac.mAddress); } if (ac.mAvatarUrl != null) { activityItemValues.put(Field.CONTACT_AVATAR_URL.toString(), ac.mAvatarUrl); } } return activityItemValues; } /** * Fetches a list of status items from the given time stamp. * * @param timeStamp Time stamp in milliseconds * @param readableDb Readable SQLite database * @return A cursor (use one of the {@link #getQueryData} methods to read * the data) */ public static Cursor fetchStatusEventList(final long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchStatusEventList()"); return readableDb.rawQuery("SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + " & " + ActivityItem.STATUS_ITEM + ") AND " + Field.TIMESTAMP + " > " + timeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); } /** * Returns a list of activity IDs already synced, in reverse chronological * order Fetches from the given timestamp. * * @param actIdList An empty list which will be filled with the result * @param timeStamp The time stamp to start the fetch * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus fetchActivitiesIds(final List<Long> actIdList, final Long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchActivitiesIds()"); Cursor cursor = null; try { long queryTimeStamp; if (timeStamp != null) { queryTimeStamp = timeStamp; } else { queryTimeStamp = 0; } cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.TIMESTAMP + " >= " + queryTimeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); while (cursor.moveToNext()) { actIdList.add(cursor.getLong(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchActivitiesIds()" + "Unable to fetch group list", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Adds a list of activities to table. The activities added will be grouped * in the database, based on local contact Id, name or contact address (see * {@link #removeContactGroup(Long, String, Long, int, * TimelineNativeTypes[], SQLiteDatabase)} * for more information on how the grouping works. * * @param actList The list of activities * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus addActivities(final List<ActivityItem> actList, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addActivities()"); SQLiteStatement statement = ContactsTable.fetchLocalFromServerIdStatement(writableDb); for (ActivityItem activity : actList) { try { writableDb.beginTransaction(); if (activity.contactList != null) { int clistSize = activity.contactList.size(); for (int i = 0; i < clistSize; i++) { final ActivityContact activityContact = activity.contactList.get(i); activityContact.mLocalContactId = ContactsTable.fetchLocalFromServerId( activityContact.mContactId, statement); if (activityContact.mLocalContactId == null) { // Just skip activities for which we don't have a corresponding contact // in the database anymore otherwise they will be shown as "Blank name". // This is the same on the web but we could use the provided name instead. continue; } int latestStatusVal = removeContactGroup( activityContact.mLocalContactId, activityContact.mName, activity.time, activity.activityFlags, null, writableDb); ContentValues cv = fillUpdateData(activity, i); cv.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); activity.localActivityId = writableDb.insertOrThrow(TABLE_NAME, null, cv); } } else { activity.localActivityId = writableDb.insertOrThrow( TABLE_NAME, null, fillUpdateData(activity, null)); } if ((activity.localActivityId != null) && (activity.localActivityId < 0)) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } if(statement != null) { statement.close(); statement = null; } return ServiceStatus.SUCCESS; } /** * Deletes all activities from the table. * * @param flag Can be a bitmap of: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * <li>NULL - to delete all activities</li> * </ul> * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteActivities(final Integer flag, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteActivities()"); try { String whereClause = null; if (flag != null) { whereClause = Field.FLAG + "&" + flag; } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } public static ServiceStatus fetchNativeIdsFromLocalContactId(List<Integer > nativeItemIdList, final long localContactId, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNativeIdsFromLocalContactId()"); Cursor cursor = null; try { cursor = readableDb.rawQuery("SELECT " + Field.NATIVE_ITEM_ID + " FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + " = " + localContactId, null); while (cursor.moveToNext()) { nativeItemIdList.add(cursor.getInt(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchNativeIdsFromLocalContactId()" + "Unable to fetch list of NativeIds from localcontactId", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Deletes specified timeline activity from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivity(final Context context, final TimelineSummaryItem timelineItem, final SQLiteDatabase writableDb, final SQLiteDatabase readableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteTimelineActivity()"); try { List<Integer > nativeItemIdList = new ArrayList<Integer>() ; //Delete from Native Database if(timelineItem.mNativeThreadId != null) { //Sms Native Database final Uri smsUri = Uri.parse("content://sms"); context.getContentResolver().delete(smsUri , "thread_id=" + timelineItem.mNativeThreadId, null); //Mms Native Database final Uri mmsUri = Uri.parse("content://mms"); context.getContentResolver().delete(mmsUri, "thread_id=" + timelineItem.mNativeThreadId, null); } else { // For CallLogs if(timelineItem.mLocalContactId != null) { fetchNativeIdsFromLocalContactId(nativeItemIdList, timelineItem.mLocalContactId, readableDb); if(nativeItemIdList.size() > 0) { //CallLog Native Database for(Integer nativeItemId : nativeItemIdList) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + nativeItemId, null); } } } else if ((TextUtils.isEmpty(timelineItem.mContactName)) && // we have an unknown caller (null == timelineItem.mContactId)) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + timelineItem.mNativeItemId, null); } else { if(timelineItem.mContactAddress != null) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls.NUMBER + "='" + timelineItem.mContactAddress+"'", null); } } } String whereClause = null; //Delete from People Client database if(timelineItem.mLocalContactId != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } else if(timelineItem.mContactAddress != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } else if ((TextUtils.isEmpty(timelineItem.mContactName)) && // we have an unknown caller (null == timelineItem.mContactId)) { whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.NATIVE_ITEM_ID + "=" + timelineItem.mNativeItemId; } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } /** * Deletes all the timeline activities for a particular contact from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivities(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.deleteTimelineActivities()"); Cursor cursor = null; try { TimelineNativeTypes[] typeList = null; //For CallLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); //For SmsLog/MmsLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); //For ChatLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * * Deletes one or more timeline items for a contact for the given types. * * @param context The app context to open the transaction in. * @param latestTimelineItem The latest item from the timeline to get the belonging contact from. * @param writableDb The database to write to. * @param readableDb The database to read from. * @param typeList The list of types to delete timeline events for. * * @return Returns a success if the transaction was successful, an error otherwise. * */ private static ServiceStatus deleteTimeLineActivitiesByType(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb, TimelineNativeTypes[] typeList) { Cursor cursor = null; TimelineSummaryItem timelineItem = null; try { - if ((TextUtils.isEmpty(latestTimelineItem.mContactName)) && + if ((!TextUtils.isEmpty(latestTimelineItem.mContactName)) && (latestTimelineItem.mContactId != null)) { cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { return deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } } else { // contact id and name are null or empty, so it is an unknown contact return deleteTimelineActivity(context, latestTimelineItem, writableDb, readableDb); } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * Fetches timeline events grouped by local contact ID, name or contact * address. Events returned will be in reverse-chronological order. If a * native type list is provided the result will be filtered by the list. * * @param minTimeStamp Only timeline events from this date will be returned * @param nativeTypes A list of native types to filter the result, or null * to return all. * @param readableDb Readable SQLite database * @return A cursor containing the result. The * {@link #getTimelineData(Cursor)} method should be used for * reading the cursor. */ public static Cursor fetchTimelineEventList(final Long minTimeStamp, final TimelineNativeTypes[] nativeTypes, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchTimelineEventList() " + "minTimeStamp[" + minTimeStamp + "]"); try { int andVal = 1; String typesQuery = " AND "; if (nativeTypes != null) { typesQuery += DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), nativeTypes, "OR"); typesQuery += " AND "; andVal = 2; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + Field.TIMESTAMP + " > " + minTimeStamp + " AND (" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") ORDER BY " + Field.TIMESTAMP + " DESC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchLastUpdateTime() " + "Unable to fetch timeline event list", e); return null; } } /** * Adds a list of timeline events to the database. Each event is grouped by * contact and grouped by contact + native type. * * @param itemList List of timeline events * @param isCallLog true to group all activities with call logs, false to * group with messaging * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error */ public static ServiceStatus addTimelineEvents( final ArrayList<TimelineSummaryItem> itemList, final boolean isCallLog, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addTimelineEvents()"); TimelineNativeTypes[] activityTypes; if (isCallLog) { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; } else { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; } for (TimelineSummaryItem item : itemList) { try { writableDb.beginTransaction(); if (findNativeActivity(item, writableDb)) { continue; } int latestStatusVal = 0; if (!TextUtils.isEmpty(item.mContactName) || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, activityTypes, writableDb); } else { // unknown contact latestStatusVal = 1; } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM); values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } item.mLocalActivityId = writableDb.insert(TABLE_NAME, null, values); if (item.mLocalActivityId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "ERROR_DATABASE_CORRUPT - Unable to add " + "timeline list to database"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /** * The method returns the ROW_ID i.e. the INTEGER PRIMARY KEY AUTOINCREMENT * field value for the inserted row, i.e. LOCAL_ID. * * @param item TimelineSummaryItem. * @param read - TRUE if the chat message is outgoing or gets into the * timeline history view for a contact with LocalContactId. * @param writableDb Writable SQLite database. * @return LocalContactID or -1 if the row was not inserted. */ public static long addChatTimelineEvent(final TimelineSummaryItem item, final boolean read, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addChatTimelineEvent()"); try { writableDb.beginTransaction(); int latestStatusVal = 0; if (item.mContactName != null || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }, writableDb); } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); /** Chat message body. **/ values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); if (read) { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); } else { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | 0); } values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); /** Conversation ID for chat message. **/ // values.put(Field.URI.toString(), item.conversationId); // 0 for incoming, 1 for outgoing if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } final long itemId = writableDb.insert(TABLE_NAME, null, values); if (itemId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() - " + "Unable to add timeline list to database, index<0:" + itemId); return -1; } writableDb.setTransactionSuccessful(); return itemId; } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return -1; } finally { writableDb.endTransaction(); } } /** * Clears the grouping of an activity in the database, if the given activity * is newer. This is so that only the latest activity is returned for a * particular group. Each activity is associated with two groups: * <ol> * <li>All group - Grouped by contact only</li> * <li>Native group - Grouped by contact and native type (call log or * messaging)</li> * </ol> * The group to be removed is determined by the activityTypes parameter. * Grouping must also work for timeline events that are not associated with * a contact. The following fields are used to do identify a contact for the * grouping (in order of priority): * <ol> * <li>localContactId - If it not null</li> * <li>name - If this is a valid telephone number, the match will be done to * ensure that the same phone number written in different ways will be * included in the group. See {@link #fetchNameWhereClause(Long, String)} * for more information.</li> * </ol> * * @param localContactId Local contact Id or NULL if the activity is not * associated with a contact. * @param name Name of contact or contact address (telephone number, email, * etc). * @param newUpdateTime The time that the given activity has occurred * @param flag Bitmap of types including: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * </ul> * @param activityTypes A list of native types to include in the grouping. * Currently, only two groups are supported (see above). If this * parameter is null the contact will be added to the * "all group", otherwise the contact is added to the native * group. * @param writableDb Writable SQLite database * @return The latest contact status value which should be added to the * current activities grouping. */ private static int removeContactGroup(final Long localContactId, final String name, final Long newUpdateTime, final int flag, final TimelineNativeTypes[] activityTypes, final SQLiteDatabase writableDb) { String whereClause = ""; int andVal = 1; if (activityTypes != null) { whereClause = DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), activityTypes, "OR"); whereClause += " AND "; andVal = 2; } String nameWhereClause = fetchNameWhereClause(localContactId, name); if (nameWhereClause == null) { return 0; } whereClause += nameWhereClause; Long prevTime = null; Long prevLocalId = null; Integer prevLatestContactStatus = null; Cursor cursor = null; try { cursor = writableDb.rawQuery("SELECT " + Field.TIMESTAMP + "," + Field.LOCAL_ACTIVITY_ID + "," + Field.LATEST_CONTACT_STATUS + " FROM " + TABLE_NAME + " WHERE " + whereClause + " AND " + "(" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") AND (" + Field.FLAG + "&" + flag + ") ORDER BY " + Field.TIMESTAMP + " DESC", null); if (cursor.moveToFirst()) { prevTime = cursor.getLong(0); prevLocalId = cursor.getLong(1); prevLatestContactStatus = cursor.getInt(2); } } catch (SQLException e) { return 0; } finally { CloseUtils.close(cursor); } if (prevTime != null && newUpdateTime != null) { if (newUpdateTime >= prevTime) { ContentValues cv = new ContentValues(); cv.put(Field.LATEST_CONTACT_STATUS.toString(), prevLatestContactStatus & (~andVal)); if (writableDb.update(TABLE_NAME, cv, Field.LOCAL_ACTIVITY_ID + "=" + prevLocalId, null) <= 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "Unable to update timeline as the latest"); return 0; } return andVal; } else { return 0; } } return andVal; } /** * Checks if an activity exists in the database. * * @param item The native SMS item to check against our client activities DB table. * * @return true if the activity was found, false otherwise * */ private static boolean findNativeActivity(TimelineSummaryItem item, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.findNativeActivity()"); Cursor cursor = null; boolean result = false; try { final String[] args = { Integer.toString(item.mNativeItemId), Integer.toString(item.mNativeItemType), Long.toString(item.mTimestamp) }; cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_ID + "=? AND " + Field.NATIVE_ITEM_TYPE + "=?" + " AND " + Field.TIMESTAMP + "=?", args); if (cursor.moveToFirst()) { result = true; } } finally { CloseUtils.close(cursor); } return result; } /** * Returns a string which can be added to the where clause in an SQL query * on the activities table, to filter the result for a specific contact or * name. The clause will prioritise in the following way: * <ol> * <li>Use localContactId - If it not null</li> * <li>Use name - If this is a valid telephone number, the match will be * done to ensure that the same phone number written in different ways will * be included in the group. * </ol> * * @param localContactId The local contact ID, or null if the contact does * not exist in the People database. * @param name A string containing the name, or a telephone number/email * identifying the contact. * @return The where clause string */ private static String fetchNameWhereClause(final Long localContactId, final String name) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNameWhereClause()"); if (localContactId != null) { return Field.LOCAL_CONTACT_ID + "=" + localContactId; } if (name == null) { return "1=1"; // we need to return something that evaluates to true as this method is called after a SQL AND-operator } final String searchName = DatabaseUtils.sqlEscapeString(name); if (PhoneNumberUtils.isWellFormedSmsAddress(name)) { return "(PHONE_NUMBERS_EQUAL(" + Field.CONTACT_NAME + "," + searchName + ") OR "+ Field.CONTACT_NAME + "=" + searchName+")"; } else { return Field.CONTACT_NAME + "=" + searchName; } } /** * Returns the timeline summary data from the current location of the given * cursor. The cursor can be obtained using * {@link #fetchTimelineEventList(Long, TimelineNativeTypes[], * SQLiteDatabase)} or * {@link #fetchTimelineEventsForContact(Long, Long, String, * TimelineNativeTypes[], SQLiteDatabase)}. * * @param cursor Cursor in the required position. * @return A filled out TimelineSummaryItem object */ public static TimelineSummaryItem getTimelineData(final Cursor cursor) { DatabaseHelper.trace(false, "DatabaseHelper.getTimelineData()"); TimelineSummaryItem item = new TimelineSummaryItem(); item.mLocalActivityId = SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); item.mTimestamp = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); item.mContactName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); if (!cursor.isNull( cursor.getColumnIndex(Field.CONTACT_AVATAR_URL.toString()))) { item.mHasAvatar = true; } item.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); item.mTitle = SqlUtils.setString(cursor, Field.TITLE.toString()); item.mDescription = SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); item.mContactNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); item.mNativeItemType = SqlUtils.setInt(cursor, Field.NATIVE_ITEM_TYPE.toString(), null); item.mNativeItemId = SqlUtils.setInt(cursor, Field.NATIVE_ITEM_ID.toString(), null); item.mType = SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); item.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); item.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); item.mNativeThreadId = SqlUtils.setInt(cursor, Field.NATIVE_THREAD_ID.toString(), null); item.mContactAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); item.mIncoming = SqlUtils.setTimelineSummaryItemType(cursor, Field.INCOMING.toString()); return item; } /** * Fetches timeline events for a specific contact identified by local * contact ID, name or address. Events returned will be in * reverse-chronological order. If a native type list is provided the result * will be filtered by the list. * * @param timeStamp Only events from this time will be returned * @param localContactId The local contact ID if the contact is in the * People database, or null. * @param name The name or address of the contact (required if local contact * ID is NULL). * @param nativeTypes A list of required native types to filter the result, * or null to return all timeline events for the contact. * @param readableDb Readable SQLite database * @param networkName The name of the network the contacts belongs to * (required in order to provide appropriate chat messages * filtering) If the parameter is null messages from all networks * will be returned. The values are the * SocialNetwork.VODAFONE.toString(), * SocialNetwork.GOOGLE.toString(), or * SocialNetwork.MICROSOFT.toString() results. * @return The cursor that can be read using * {@link #getTimelineData(Cursor)}. */ public static Cursor fetchTimelineEventsForContact(final Long timeStamp, final Long localContactId, final String name, final TimelineNativeTypes[] nativeTypes, final String networkName, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "fetchTimelineEventsForContact()"); try { String typesQuery = " AND ";
360/360-Engine-for-Android
9753e787a8a44077a8e8d447efcfe7acea95fd96
PAND-2081 fix the widget crash at start-up
diff --git a/src/com/vodafone360/people/engine/presence/NetworkPresence.java b/src/com/vodafone360/people/engine/presence/NetworkPresence.java index a9fa995..1a67f8a 100644 --- a/src/com/vodafone360/people/engine/presence/NetworkPresence.java +++ b/src/com/vodafone360/people/engine/presence/NetworkPresence.java @@ -1,179 +1,206 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import com.vodafone360.people.utils.ThirdPartyAccount; /** * A wrapper for the user presence state on certain web or IM account */ public class NetworkPresence { private String mUserId; private int mNetworkId; private int mOnlineStatusId; /** * Constructor with parameters. * * @param mNetworkId - the ordinal of the network name in the overall * hardcoded network list. * @param mOnlineStatusId - the ordinal of user presence status in the * overall hardcoded statuses list specifically for this web * account */ public NetworkPresence(String userId, int networkId, int onlineStatusId) { super(); this.mUserId = userId; this.mNetworkId = networkId; this.mOnlineStatusId = onlineStatusId; } /** * @return the ordinal of the network name on the overall hardcoded network * list. */ public int getNetworkId() { return mNetworkId; } /** * @return the ordinal of the online status name on the overall hardcoded * status list. */ public int getOnlineStatusId() { return mOnlineStatusId; } /** * @return user account name on Nowplus or other social network */ public String getUserId() { return mUserId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mNetworkId; result = prime * result + mOnlineStatusId; result = prime * result + ((mUserId == null) ? 0 : mUserId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NetworkPresence other = (NetworkPresence)obj; if (mNetworkId != other.mNetworkId) return false; if (mOnlineStatusId != other.mOnlineStatusId) return false; if (mUserId == null) { if (other.mUserId != null) return false; } else if (!mUserId.equals(other.mUserId)) return false; return true; } @Override public String toString() { return "NetworkPresence [mNetworkId=" + mNetworkId + ", mOnlineStatusId=" + mOnlineStatusId + ", mUserId=" + mUserId + "]"; } /** * Hard coded networks with enable IM list */ public static enum SocialNetwork { FACEBOOK_COM("facebook.com"), HYVES_NL("hyves.nl"), GOOGLE("google"), MICROSOFT("microsoft"), MOBILE("mobile"), PC("pc"), VODAFONE("vodafone"); // the aggregated status for "pc" and "mobile" // only used by - UI - Contact Profile View private String mSocialNetwork; // / The name of the field as it appears // in the database private SocialNetwork(String field) { mSocialNetwork = field; } - + + @Override public String toString() { return mSocialNetwork; } + /** + * This method returns the SocialNetwork object based on the underlying string. + * @param value - the String containing the SocialNetwork name. + * @return SocialNetwork object for the provided string. + */ public static SocialNetwork getValue(String value) { try { return valueOf(value.replace('.', '_').toUpperCase()); } catch (Exception e) { return null; } } + /** + * This method returns the SocialNetwork object based on index in the SocialNetwork enum. + * This method should be called to get the SocialNetwork object by networkId + * index from {@code}NetworkPresence. + * @param index - integer index. + * @return SocialNetwork object for the provided index. + */ public static SocialNetwork getPresenceValue(int index) { if (index == VODAFONE.ordinal()) return MOBILE; return values()[index]; } + /** + * This method returns the SocialNetwork object based on index in the SocialNetwork enum. + * This method should be called to get the SocialNetwork for a chat network id index. + * @param index - integer index. + * @return SocialNetwork object for the provided index. + */ public static SocialNetwork getChatValue(int index) { if (index == MOBILE.ordinal() || index == PC.ordinal() || index == VODAFONE.ordinal()) return VODAFONE; return values()[index]; } + /** + * This method returns the SocialNetwork object based on the provided + * string. + * This method should be called to get the SocialNetwork objects for UI purposes, i.e. + * it returns Vodafone rather than MOBILE or PC if "pc" and "mobile" are passed in. + * @param index - integer index. + * @return SocialNetwork object for the provided underlying string. + */ public static SocialNetwork getNetworkBasedOnString(String sns) { if (sns != null) { if (sns.contains(ThirdPartyAccount.SNS_TYPE_FACEBOOK)) { return FACEBOOK_COM; } else if (sns.contains(ThirdPartyAccount.SNS_TYPE_HYVES)) { return HYVES_NL; } else if (ThirdPartyAccount.isWindowsLive(sns)) { return MICROSOFT; } else if (sns.contains(ThirdPartyAccount.SNS_TYPE_GOOGLE)) { return GOOGLE; } else if (sns.contains(ThirdPartyAccount.SNS_TYPE_TWITTER)) { return PC; } else if (ThirdPartyAccount.isVodafone(sns)) { return VODAFONE; } } return null; } } }
360/360-Engine-for-Android
41e3653f418b697eefe6fd15ef0f13d06f6e1d89
PAND-2081 fix the widget crash at start-up
diff --git a/src/com/vodafone360/people/engine/presence/NetworkPresence.java b/src/com/vodafone360/people/engine/presence/NetworkPresence.java index 9fa3840..a9fa995 100644 --- a/src/com/vodafone360/people/engine/presence/NetworkPresence.java +++ b/src/com/vodafone360/people/engine/presence/NetworkPresence.java @@ -1,179 +1,179 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import com.vodafone360.people.utils.ThirdPartyAccount; /** * A wrapper for the user presence state on certain web or IM account */ public class NetworkPresence { private String mUserId; private int mNetworkId; private int mOnlineStatusId; /** * Constructor with parameters. * * @param mNetworkId - the ordinal of the network name in the overall * hardcoded network list. * @param mOnlineStatusId - the ordinal of user presence status in the * overall hardcoded statuses list specifically for this web * account */ public NetworkPresence(String userId, int networkId, int onlineStatusId) { super(); this.mUserId = userId; this.mNetworkId = networkId; this.mOnlineStatusId = onlineStatusId; } /** * @return the ordinal of the network name on the overall hardcoded network * list. */ public int getNetworkId() { return mNetworkId; } /** * @return the ordinal of the online status name on the overall hardcoded * status list. */ public int getOnlineStatusId() { return mOnlineStatusId; } /** * @return user account name on Nowplus or other social network */ public String getUserId() { return mUserId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mNetworkId; result = prime * result + mOnlineStatusId; result = prime * result + ((mUserId == null) ? 0 : mUserId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NetworkPresence other = (NetworkPresence)obj; if (mNetworkId != other.mNetworkId) return false; if (mOnlineStatusId != other.mOnlineStatusId) return false; if (mUserId == null) { if (other.mUserId != null) return false; } else if (!mUserId.equals(other.mUserId)) return false; return true; } @Override public String toString() { return "NetworkPresence [mNetworkId=" + mNetworkId + ", mOnlineStatusId=" + mOnlineStatusId + ", mUserId=" + mUserId + "]"; } /** * Hard coded networks with enable IM list */ public static enum SocialNetwork { FACEBOOK_COM("facebook.com"), HYVES_NL("hyves.nl"), GOOGLE("google"), MICROSOFT("microsoft"), MOBILE("mobile"), PC("pc"), VODAFONE("vodafone"); // the aggregated status for "pc" and "mobile" // only used by - UI - Contact Profile View private String mSocialNetwork; // / The name of the field as it appears // in the database private SocialNetwork(String field) { mSocialNetwork = field; } public String toString() { return mSocialNetwork; } - protected static SocialNetwork getValue(String value) { + public static SocialNetwork getValue(String value) { try { return valueOf(value.replace('.', '_').toUpperCase()); } catch (Exception e) { return null; } } public static SocialNetwork getPresenceValue(int index) { if (index == VODAFONE.ordinal()) return MOBILE; return values()[index]; } public static SocialNetwork getChatValue(int index) { if (index == MOBILE.ordinal() || index == PC.ordinal() || index == VODAFONE.ordinal()) return VODAFONE; return values()[index]; } public static SocialNetwork getNetworkBasedOnString(String sns) { if (sns != null) { if (sns.contains(ThirdPartyAccount.SNS_TYPE_FACEBOOK)) { return FACEBOOK_COM; } else if (sns.contains(ThirdPartyAccount.SNS_TYPE_HYVES)) { return HYVES_NL; } else if (ThirdPartyAccount.isWindowsLive(sns)) { return MICROSOFT; } else if (sns.contains(ThirdPartyAccount.SNS_TYPE_GOOGLE)) { return GOOGLE; } else if (sns.contains(ThirdPartyAccount.SNS_TYPE_TWITTER)) { return PC; } else if (ThirdPartyAccount.isVodafone(sns)) { return VODAFONE; } } return null; } } }
360/360-Engine-for-Android
06ea814e0ff5adbb8e6da5cd0270eb14b0329541
small refactorings, removed logging, removed unused imports
diff --git a/src/com/vodafone360/people/database/tables/ActivitiesTable.java b/src/com/vodafone360/people/database/tables/ActivitiesTable.java index bf86ad1..43a011b 100644 --- a/src/com/vodafone360/people/database/tables/ActivitiesTable.java +++ b/src/com/vodafone360/people/database/tables/ActivitiesTable.java @@ -286,1026 +286,1024 @@ public abstract class ActivitiesTable { && mContactId.equals(item.mContactId) && mUserId.equals(item.mUserId) && mNativeThreadId.equals(item.mNativeThreadId) && mContactAddress.equals(item.mContactAddress) && mIncoming.equals(item.mIncoming); } }; /** Number of milliseconds in a day. **/ private static final int NUMBER_OF_MS_IN_A_DAY = 24 * 60 * 60 * 1000; /** Number of milliseconds in a second. **/ private static final int NUMBER_OF_MS_IN_A_SECOND = 1000; /*** * Private constructor to prevent instantiation. */ private ActivitiesTable() { // Do nothing. } /** * Create Activities Table. * * @param writeableDb A writable SQLite database. */ public static void create(final SQLiteDatabase writeableDb) { DatabaseHelper.trace(true, "DatabaseHelper.create()"); writeableDb.execSQL("CREATE TABLE " + TABLE_NAME + " (" + Field.LOCAL_ACTIVITY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.ACTIVITY_ID + " LONG, " + Field.TIMESTAMP + " LONG, " + Field.TYPE + " TEXT, " + Field.URI + " TEXT, " + Field.TITLE + " TEXT, " + Field.DESCRIPTION + " TEXT, " + Field.PREVIEW_URL + " TEXT, " + Field.STORE + " TEXT, " + Field.FLAG + " INTEGER, " + Field.PARENT_ACTIVITY + " LONG, " + Field.HAS_CHILDREN + " INTEGER, " + Field.VISIBILITY + " INTEGER, " + Field.MORE_INFO + " TEXT, " + Field.CONTACT_ID + " LONG, " + Field.USER_ID + " LONG, " + Field.CONTACT_NAME + " TEXT, " + Field.LOCAL_CONTACT_ID + " LONG, " + Field.CONTACT_NETWORK + " TEXT, " + Field.CONTACT_ADDRESS + " TEXT, " + Field.CONTACT_AVATAR_URL + " TEXT, " + Field.LATEST_CONTACT_STATUS + " INTEGER, " + Field.NATIVE_ITEM_TYPE + " INTEGER, " + Field.NATIVE_ITEM_ID + " INTEGER, " + Field.NATIVE_THREAD_ID + " INTEGER, " + Field.INCOMING + " INTEGER);"); writeableDb.execSQL("CREATE INDEX " + TABLE_INDEX_NAME + " ON " + TABLE_NAME + " ( " + Field.TIMESTAMP + " )"); } /** * Fetches a comma separated list of table fields which can be used in an * SQL SELECT statement as the query projection. One of the * {@link #getQueryData} methods can used to fetch data from the cursor. * * @return SQL string */ private static String getFullQueryList() { DatabaseHelper.trace(false, "DatabaseHelper.getFullQueryList()"); final StringBuffer fullQuery = StringBufferPool.getStringBuffer(); fullQuery.append(Field.LOCAL_ACTIVITY_ID).append(SqlUtils.COMMA). append(Field.ACTIVITY_ID).append(SqlUtils.COMMA). append(Field.TIMESTAMP).append(SqlUtils.COMMA). append(Field.TYPE).append(SqlUtils.COMMA). append(Field.URI).append(SqlUtils.COMMA). append(Field.TITLE).append(SqlUtils.COMMA). append(Field.DESCRIPTION).append(SqlUtils.COMMA). append(Field.PREVIEW_URL).append(SqlUtils.COMMA). append(Field.STORE).append(SqlUtils.COMMA). append(Field.FLAG).append(SqlUtils.COMMA). append(Field.PARENT_ACTIVITY).append(SqlUtils.COMMA). append(Field.HAS_CHILDREN).append(SqlUtils.COMMA). append(Field.VISIBILITY).append(SqlUtils.COMMA). append(Field.MORE_INFO).append(SqlUtils.COMMA). append(Field.CONTACT_ID).append(SqlUtils.COMMA). append(Field.USER_ID).append(SqlUtils.COMMA). append(Field.CONTACT_NAME).append(SqlUtils.COMMA). append(Field.LOCAL_CONTACT_ID).append(SqlUtils.COMMA). append(Field.CONTACT_NETWORK).append(SqlUtils.COMMA). append(Field.CONTACT_ADDRESS).append(SqlUtils.COMMA). append(Field.CONTACT_AVATAR_URL).append(SqlUtils.COMMA). append(Field.INCOMING); return StringBufferPool.toStringThenRelease(fullQuery); } /** * Fetches activities information from a cursor at the current position. The * {@link #getFullQueryList()} method should be used to make the query. * * @param cursor The cursor returned by the query * @param activityItem An empty activity object that will be filled with the * result * @param activityContact An empty activity contact object that will be * filled */ public static void getQueryData(final Cursor cursor, final ActivityItem activityItem, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityItem. **/ activityItem.localActivityId = SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); activityItem.activityId = SqlUtils.setLong(cursor, Field.ACTIVITY_ID.toString(), null); activityItem.time = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); activityItem.type = SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); activityItem.uri = SqlUtils.setString(cursor, Field.URI.toString()); activityItem.title = SqlUtils.setString(cursor, Field.TITLE.toString()); activityItem.description = SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); activityItem.previewUrl = SqlUtils.setString(cursor, Field.PREVIEW_URL.toString()); activityItem.store = SqlUtils.setString(cursor, Field.STORE.toString()); activityItem.activityFlags = SqlUtils.setInt(cursor, Field.FLAG.toString(), null); activityItem.parentActivity = SqlUtils.setLong(cursor, Field.PARENT_ACTIVITY.toString(), null); activityItem.hasChildren = SqlUtils.setBoolean(cursor, Field.HAS_CHILDREN.toString(), activityItem.hasChildren); activityItem.visibilityFlags = SqlUtils.setInt(cursor, Field.VISIBILITY.toString(), null); // TODO: Field MORE_INFO is not used, consider deleting. /** Populate ActivityContact. **/ getQueryData(cursor, activityContact); } /** * Fetches activities information from a cursor at the current position. The * {@link #getFullQueryList()} method should be used to make the query. * * @param cursor The cursor returned by the query. * @param activityContact An empty activity contact object that will be * filled */ public static void getQueryData(final Cursor cursor, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityContact. **/ activityContact.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); activityContact.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); activityContact.mName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); activityContact.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); activityContact.mNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); activityContact.mAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); activityContact.mAvatarUrl = SqlUtils.setString(cursor, Field.CONTACT_AVATAR_URL.toString()); } /*** * Provides a ContentValues object that can be used to update the table. * * @param item The source activity item * @param contactIdx The index of the contact to use for the update, or null * to exclude contact specific information. * @return ContentValues for use in an SQL update or insert. * @note Items that are NULL will be not modified in the database. */ private static ContentValues fillUpdateData(final ActivityItem item, final Integer contactIdx) { DatabaseHelper.trace(false, "DatabaseHelper.fillUpdateData()"); ContentValues activityItemValues = new ContentValues(); ActivityContact ac = null; if (contactIdx != null) { ac = item.contactList.get(contactIdx); } activityItemValues.put(Field.ACTIVITY_ID.toString(), item.activityId); activityItemValues.put(Field.TIMESTAMP.toString(), item.time); if (item.type != null) { activityItemValues.put(Field.TYPE.toString(), item.type.getTypeCode()); } if (item.uri != null) { activityItemValues.put(Field.URI.toString(), item.uri); } /** TODO: Not sure if we need this. **/ // activityItemValues.put(Field.INCOMING.toString(), false); activityItemValues.put(Field.TITLE.toString(), item.title); activityItemValues.put(Field.DESCRIPTION.toString(), item.description); if (item.previewUrl != null) { activityItemValues.put(Field.PREVIEW_URL.toString(), item.previewUrl); } if (item.store != null) { activityItemValues.put(Field.STORE.toString(), item.store); } if (item.activityFlags != null) { activityItemValues.put(Field.FLAG.toString(), item.activityFlags); } if (item.parentActivity != null) { activityItemValues.put(Field.PARENT_ACTIVITY.toString(), item.parentActivity); } if (item.hasChildren != null) { activityItemValues.put(Field.HAS_CHILDREN.toString(), item.hasChildren); } if (item.visibilityFlags != null) { activityItemValues.put(Field.VISIBILITY.toString(), item.visibilityFlags); } if (ac != null) { activityItemValues.put(Field.CONTACT_ID.toString(), ac.mContactId); activityItemValues.put(Field.USER_ID.toString(), ac.mUserId); activityItemValues.put(Field.CONTACT_NAME.toString(), ac.mName); activityItemValues.put(Field.LOCAL_CONTACT_ID.toString(), ac.mLocalContactId); if (ac.mNetwork != null) { activityItemValues.put(Field.CONTACT_NETWORK.toString(), ac.mNetwork); } if (ac.mAddress != null) { activityItemValues.put(Field.CONTACT_ADDRESS.toString(), ac.mAddress); } if (ac.mAvatarUrl != null) { activityItemValues.put(Field.CONTACT_AVATAR_URL.toString(), ac.mAvatarUrl); } } return activityItemValues; } /** * Fetches a list of status items from the given time stamp. * * @param timeStamp Time stamp in milliseconds * @param readableDb Readable SQLite database * @return A cursor (use one of the {@link #getQueryData} methods to read * the data) */ public static Cursor fetchStatusEventList(final long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchStatusEventList()"); return readableDb.rawQuery("SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + " & " + ActivityItem.STATUS_ITEM + ") AND " + Field.TIMESTAMP + " > " + timeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); } /** * Returns a list of activity IDs already synced, in reverse chronological * order Fetches from the given timestamp. * * @param actIdList An empty list which will be filled with the result * @param timeStamp The time stamp to start the fetch * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus fetchActivitiesIds(final List<Long> actIdList, final Long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchActivitiesIds()"); Cursor cursor = null; try { long queryTimeStamp; if (timeStamp != null) { queryTimeStamp = timeStamp; } else { queryTimeStamp = 0; } cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.TIMESTAMP + " >= " + queryTimeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); while (cursor.moveToNext()) { actIdList.add(cursor.getLong(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchActivitiesIds()" + "Unable to fetch group list", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Adds a list of activities to table. The activities added will be grouped * in the database, based on local contact Id, name or contact address (see * {@link #removeContactGroup(Long, String, Long, int, * TimelineNativeTypes[], SQLiteDatabase)} * for more information on how the grouping works. * * @param actList The list of activities * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus addActivities(final List<ActivityItem> actList, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addActivities()"); SQLiteStatement statement = ContactsTable.fetchLocalFromServerIdStatement(writableDb); for (ActivityItem activity : actList) { try { writableDb.beginTransaction(); if (activity.contactList != null) { int clistSize = activity.contactList.size(); for (int i = 0; i < clistSize; i++) { final ActivityContact activityContact = activity.contactList.get(i); activityContact.mLocalContactId = ContactsTable.fetchLocalFromServerId( activityContact.mContactId, statement); if (activityContact.mLocalContactId == null) { // Just skip activities for which we don't have a corresponding contact // in the database anymore otherwise they will be shown as "Blank name". // This is the same on the web but we could use the provided name instead. continue; } int latestStatusVal = removeContactGroup( activityContact.mLocalContactId, activityContact.mName, activity.time, activity.activityFlags, null, writableDb); ContentValues cv = fillUpdateData(activity, i); cv.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); activity.localActivityId = writableDb.insertOrThrow(TABLE_NAME, null, cv); } } else { activity.localActivityId = writableDb.insertOrThrow( TABLE_NAME, null, fillUpdateData(activity, null)); } if ((activity.localActivityId != null) && (activity.localActivityId < 0)) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } if(statement != null) { statement.close(); statement = null; } return ServiceStatus.SUCCESS; } /** * Deletes all activities from the table. * * @param flag Can be a bitmap of: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * <li>NULL - to delete all activities</li> * </ul> * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteActivities(final Integer flag, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteActivities()"); try { String whereClause = null; if (flag != null) { whereClause = Field.FLAG + "&" + flag; } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } public static ServiceStatus fetchNativeIdsFromLocalContactId(List<Integer > nativeItemIdList, final long localContactId, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNativeIdsFromLocalContactId()"); Cursor cursor = null; try { cursor = readableDb.rawQuery("SELECT " + Field.NATIVE_ITEM_ID + " FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + " = " + localContactId, null); while (cursor.moveToNext()) { nativeItemIdList.add(cursor.getInt(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchNativeIdsFromLocalContactId()" + "Unable to fetch list of NativeIds from localcontactId", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Deletes specified timeline activity from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivity(final Context context, final TimelineSummaryItem timelineItem, final SQLiteDatabase writableDb, final SQLiteDatabase readableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteTimelineActivity()"); try { List<Integer > nativeItemIdList = new ArrayList<Integer>() ; //Delete from Native Database if(timelineItem.mNativeThreadId != null) { //Sms Native Database final Uri smsUri = Uri.parse("content://sms"); context.getContentResolver().delete(smsUri , "thread_id=" + timelineItem.mNativeThreadId, null); //Mms Native Database final Uri mmsUri = Uri.parse("content://mms"); context.getContentResolver().delete(mmsUri, "thread_id=" + timelineItem.mNativeThreadId, null); } else { // For CallLogs if(timelineItem.mLocalContactId != null) { fetchNativeIdsFromLocalContactId(nativeItemIdList, timelineItem.mLocalContactId, readableDb); if(nativeItemIdList.size() > 0) { //CallLog Native Database for(Integer nativeItemId : nativeItemIdList) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + nativeItemId, null); } } } else if ((TextUtils.isEmpty(timelineItem.mContactName)) && // we have an unknown caller (null == timelineItem.mContactId)) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + timelineItem.mNativeItemId, null); } else { if(timelineItem.mContactAddress != null) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls.NUMBER + "='" + timelineItem.mContactAddress+"'", null); } } } String whereClause = null; //Delete from People Client database if(timelineItem.mLocalContactId != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } else if(timelineItem.mContactAddress != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } else if ((TextUtils.isEmpty(timelineItem.mContactName)) && // we have an unknown caller (null == timelineItem.mContactId)) { whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.NATIVE_ITEM_ID + "=" + timelineItem.mNativeItemId; } - -LogUtils.logE("-------------------------------------------------- " + whereClause); if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } /** * Deletes all the timeline activities for a particular contact from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivities(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.deleteTimelineActivities()"); Cursor cursor = null; try { TimelineNativeTypes[] typeList = null; //For CallLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); //For SmsLog/MmsLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); //For ChatLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * * Deletes one or more timeline items for a contact for the given types. * * @param context The app context to open the transaction in. * @param latestTimelineItem The latest item from the timeline to get the belonging contact from. * @param writableDb The database to write to. * @param readableDb The database to read from. * @param typeList The list of types to delete timeline events for. * * @return Returns a success if the transaction was successful, an error otherwise. * */ private static ServiceStatus deleteTimeLineActivitiesByType(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb, TimelineNativeTypes[] typeList) { Cursor cursor = null; TimelineSummaryItem timelineItem = null; try { if ((TextUtils.isEmpty(latestTimelineItem.mContactName)) && (latestTimelineItem.mContactId != null)) { cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { return deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } } else { // contact id and name are null or empty, so it is an unknown contact return deleteTimelineActivity(context, latestTimelineItem, writableDb, readableDb); } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * Fetches timeline events grouped by local contact ID, name or contact * address. Events returned will be in reverse-chronological order. If a * native type list is provided the result will be filtered by the list. * * @param minTimeStamp Only timeline events from this date will be returned * @param nativeTypes A list of native types to filter the result, or null * to return all. * @param readableDb Readable SQLite database * @return A cursor containing the result. The * {@link #getTimelineData(Cursor)} method should be used for * reading the cursor. */ public static Cursor fetchTimelineEventList(final Long minTimeStamp, final TimelineNativeTypes[] nativeTypes, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchTimelineEventList() " + "minTimeStamp[" + minTimeStamp + "]"); try { int andVal = 1; String typesQuery = " AND "; if (nativeTypes != null) { typesQuery += DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), nativeTypes, "OR"); typesQuery += " AND "; andVal = 2; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + Field.TIMESTAMP + " > " + minTimeStamp + " AND (" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") ORDER BY " + Field.TIMESTAMP + " DESC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchLastUpdateTime() " + "Unable to fetch timeline event list", e); return null; } } /** * Adds a list of timeline events to the database. Each event is grouped by * contact and grouped by contact + native type. * * @param itemList List of timeline events * @param isCallLog true to group all activities with call logs, false to * group with messaging * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error */ public static ServiceStatus addTimelineEvents( final ArrayList<TimelineSummaryItem> itemList, final boolean isCallLog, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addTimelineEvents()"); TimelineNativeTypes[] activityTypes; if (isCallLog) { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; } else { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; } for (TimelineSummaryItem item : itemList) { try { writableDb.beginTransaction(); if (findNativeActivity(item, writableDb)) { continue; } int latestStatusVal = 0; if (!TextUtils.isEmpty(item.mContactName) || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, activityTypes, writableDb); } else { // unknown contact latestStatusVal = 1; } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM); values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } item.mLocalActivityId = writableDb.insert(TABLE_NAME, null, values); if (item.mLocalActivityId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "ERROR_DATABASE_CORRUPT - Unable to add " + "timeline list to database"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /** * The method returns the ROW_ID i.e. the INTEGER PRIMARY KEY AUTOINCREMENT * field value for the inserted row, i.e. LOCAL_ID. * * @param item TimelineSummaryItem. * @param read - TRUE if the chat message is outgoing or gets into the * timeline history view for a contact with LocalContactId. * @param writableDb Writable SQLite database. * @return LocalContactID or -1 if the row was not inserted. */ public static long addChatTimelineEvent(final TimelineSummaryItem item, final boolean read, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addChatTimelineEvent()"); try { writableDb.beginTransaction(); int latestStatusVal = 0; if (item.mContactName != null || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }, writableDb); } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); /** Chat message body. **/ values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); if (read) { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); } else { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | 0); } values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); /** Conversation ID for chat message. **/ // values.put(Field.URI.toString(), item.conversationId); // 0 for incoming, 1 for outgoing if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } final long itemId = writableDb.insert(TABLE_NAME, null, values); if (itemId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() - " + "Unable to add timeline list to database, index<0:" + itemId); return -1; } writableDb.setTransactionSuccessful(); return itemId; } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return -1; } finally { writableDb.endTransaction(); } } /** * Clears the grouping of an activity in the database, if the given activity * is newer. This is so that only the latest activity is returned for a * particular group. Each activity is associated with two groups: * <ol> * <li>All group - Grouped by contact only</li> * <li>Native group - Grouped by contact and native type (call log or * messaging)</li> * </ol> * The group to be removed is determined by the activityTypes parameter. * Grouping must also work for timeline events that are not associated with * a contact. The following fields are used to do identify a contact for the * grouping (in order of priority): * <ol> * <li>localContactId - If it not null</li> * <li>name - If this is a valid telephone number, the match will be done to * ensure that the same phone number written in different ways will be * included in the group. See {@link #fetchNameWhereClause(Long, String)} * for more information.</li> * </ol> * * @param localContactId Local contact Id or NULL if the activity is not * associated with a contact. * @param name Name of contact or contact address (telephone number, email, * etc). * @param newUpdateTime The time that the given activity has occurred * @param flag Bitmap of types including: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * </ul> * @param activityTypes A list of native types to include in the grouping. * Currently, only two groups are supported (see above). If this * parameter is null the contact will be added to the * "all group", otherwise the contact is added to the native * group. * @param writableDb Writable SQLite database * @return The latest contact status value which should be added to the * current activities grouping. */ private static int removeContactGroup(final Long localContactId, final String name, final Long newUpdateTime, final int flag, final TimelineNativeTypes[] activityTypes, final SQLiteDatabase writableDb) { String whereClause = ""; int andVal = 1; if (activityTypes != null) { whereClause = DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), activityTypes, "OR"); whereClause += " AND "; andVal = 2; } String nameWhereClause = fetchNameWhereClause(localContactId, name); if (nameWhereClause == null) { return 0; } whereClause += nameWhereClause; Long prevTime = null; Long prevLocalId = null; Integer prevLatestContactStatus = null; Cursor cursor = null; try { cursor = writableDb.rawQuery("SELECT " + Field.TIMESTAMP + "," + Field.LOCAL_ACTIVITY_ID + "," + Field.LATEST_CONTACT_STATUS + " FROM " + TABLE_NAME + " WHERE " + whereClause + " AND " + "(" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") AND (" + Field.FLAG + "&" + flag + ") ORDER BY " + Field.TIMESTAMP + " DESC", null); if (cursor.moveToFirst()) { prevTime = cursor.getLong(0); prevLocalId = cursor.getLong(1); prevLatestContactStatus = cursor.getInt(2); } } catch (SQLException e) { return 0; } finally { CloseUtils.close(cursor); } if (prevTime != null && newUpdateTime != null) { if (newUpdateTime >= prevTime) { ContentValues cv = new ContentValues(); cv.put(Field.LATEST_CONTACT_STATUS.toString(), prevLatestContactStatus & (~andVal)); if (writableDb.update(TABLE_NAME, cv, Field.LOCAL_ACTIVITY_ID + "=" + prevLocalId, null) <= 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "Unable to update timeline as the latest"); return 0; } return andVal; } else { return 0; } } return andVal; } /** * Checks if an activity exists in the database. * * @param item The native SMS item to check against our client activities DB table. * * @return true if the activity was found, false otherwise * */ private static boolean findNativeActivity(TimelineSummaryItem item, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.findNativeActivity()"); Cursor cursor = null; boolean result = false; try { final String[] args = { Integer.toString(item.mNativeItemId), Integer.toString(item.mNativeItemType), Long.toString(item.mTimestamp) }; cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_ID + "=? AND " + Field.NATIVE_ITEM_TYPE + "=?" + " AND " + Field.TIMESTAMP + "=?", args); if (cursor.moveToFirst()) { result = true; } } finally { CloseUtils.close(cursor); } return result; } /** * Returns a string which can be added to the where clause in an SQL query * on the activities table, to filter the result for a specific contact or * name. The clause will prioritise in the following way: * <ol> * <li>Use localContactId - If it not null</li> * <li>Use name - If this is a valid telephone number, the match will be * done to ensure that the same phone number written in different ways will * be included in the group. * </ol> * * @param localContactId The local contact ID, or null if the contact does * not exist in the People database. * @param name A string containing the name, or a telephone number/email * identifying the contact. * @return The where clause string */ private static String fetchNameWhereClause(final Long localContactId, final String name) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNameWhereClause()"); if (localContactId != null) { return Field.LOCAL_CONTACT_ID + "=" + localContactId; } if (name == null) { return "1=1"; // we need to return something that evaluates to true as this method is called after a SQL AND-operator } final String searchName = DatabaseUtils.sqlEscapeString(name); if (PhoneNumberUtils.isWellFormedSmsAddress(name)) { return "(PHONE_NUMBERS_EQUAL(" + Field.CONTACT_NAME + "," + searchName + ") OR "+ Field.CONTACT_NAME + "=" + searchName+")"; } else { return Field.CONTACT_NAME + "=" + searchName; } } /** * Returns the timeline summary data from the current location of the given * cursor. The cursor can be obtained using * {@link #fetchTimelineEventList(Long, TimelineNativeTypes[], * SQLiteDatabase)} or diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 5bd1360..36d9fd2 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,563 +1,562 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.identities; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import android.os.Bundle; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Identities; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.transport.ConnectionManager; -import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; /** * Engine responsible for handling retrieval and validation of Identities (e.g. * 3rd party/web accounts). The Identities engine can fetch a list of available * accounts, and set required capabilities and validate credentials for * specified accounts. */ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { /** * States for IdentitiesEngine. States are based on the requests that the * engine needs to handle. */ private enum State { IDLE, FETCHING_IDENTITIES, VALIDATING_IDENTITY_CREDENTIALS, SETTING_IDENTITY_STATUS, GETTING_MY_IDENTITIES, GETTING_MY_CHATABLE_IDENTITIES, DELETE_IDENTITY } /** * Mutex for thread synchronisation */ private final Object mMutex = new Object(); /** * Container class for Identity Capability Status request. Consists of a * network, identity id and a filter containing the required capabilities. */ private static class IdentityStatusRequest { private String mNetwork; private String mIdentityId; private String mIdentityStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setIdentityStatus(String status) { mIdentityStatus = status; } } /** * Container class encapsulating an Identity validation request containing: * dry-run flag, network, user-name, password, set of required capabilities. */ private static class IdentityValidateCredentialsRequest { /** Performs a dry run if true. */ private boolean mDryRun; /** Network to sign into. */ private String mNetwork; /** Username to sign into identity with. */ private String mUserName; /** Password to sign into identity with. */ private String mPassword; private Map<String, Boolean> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } /** * * Container class for Delete Identity request. Consist network and identity id. * */ private static class DeleteIdentityRequest { /** Network to delete.*/ private String mNetwork; /** IdentityID which needs to be Deleted.*/ private String mIdentityId; } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mMyIdentityList; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; /** * Maintaining DeleteIdentityRequest so that it can be later removed from * maintained cache. **/ private DeleteIdentityRequest identityToBeDeleted; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; mMyIdentityList = new ArrayList<Identity>(); mAvailableIdentityList = new ArrayList<Identity>(); mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { if ((mAvailableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return mMyIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = getMyThirdPartyChattableIdentities(); // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chattableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chattableIdentities; } /** * * Takes all third party identities that have a chat capability set to true. * * @return A list of chattable 3rd party identities the user is signed in to. If the retrieval identities failed the returned list will be empty. * */ public ArrayList<Identity> getMyThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = new ArrayList<Identity>(); int identityListSize = mMyIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = mMyIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue)) { chattableIdentities.add(identity); break; } } } return chattableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Delete the given social network. * * @param network Name of the identity, * @param identityId Id of identity. */ public final void addUiDeleteIdentityRequest(final String network, final String identityId) { LogUtils.logD("IdentityEngine.addUiRemoveIdentity()"); DeleteIdentityRequest data = new DeleteIdentityRequest(); data.mNetwork = network; data.mIdentityId = identityId; /**maintaining the sent object*/ setIdentityToBeDeleted(data); addUiRequestToQueue(ServiceUiRequest.DELETE_IDENTITY, data); } /** * Setting the DeleteIdentityRequest object. * * @param data */ private void setIdentityToBeDeleted(final DeleteIdentityRequest data) { identityToBeDeleted = data; } /** * Return the DeleteIdentityRequest object. * */ private DeleteIdentityRequest getIdentityToBeDeleted() { return identityToBeDeleted; } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; case DELETE_IDENTITY: executeDeleteIdentityRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to delete the identity as specified . (Request is not issued if there * is currently no connectivity). * * @param data bundled request data containing network and identityId. */ private void executeDeleteIdentityRequest(final Object data) { if (!isConnected()) { completeUiRequest(ServiceStatus.ERROR_NO_INTERNET); } newState(State.DELETE_IDENTITY); DeleteIdentityRequest reqData = (DeleteIdentityRequest) data; if (!setReqId(Identities.deleteIdentity(this, reqData.mNetwork, reqData.mIdentityId))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(DecodedResponse resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if ((null == resp) || (null == resp.mDataTypes)) { LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); return; } // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; case BaseDataType.IDENTITY_DELETION_DATA_TYPE: handleDeleteIdentity(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); } } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); }
360/360-Engine-for-Android
daf682cffb36418e5efbddd287b20f0897d777d6
fixes for pand 2038. contextual menu not showing for unknown contacts.
diff --git a/src/com/vodafone360/people/database/DatabaseHelper.java b/src/com/vodafone360/people/database/DatabaseHelper.java index 0ca5b0f..8879385 100644 --- a/src/com/vodafone360/people/database/DatabaseHelper.java +++ b/src/com/vodafone360/people/database/DatabaseHelper.java @@ -661,1025 +661,1025 @@ public class DatabaseHelper extends SQLiteOpenHelper { } /*** * Modifies a setting in the database. * * @param setting A {@link PersistSetting} object which is populated with an * option set to a value. * @return SUCCESS or a suitable error code * @see #fetchOption(com.vodafone360.people.service.PersistSettings.Option) */ public ServiceStatus setOption(PersistSettings setting) { ServiceStatus mStatus = StateTable.setOption(setting, getWritableDatabase()); if (ServiceStatus.SUCCESS == mStatus) { fireSettingChangedEvent(setting); } return mStatus; } /*** * Removes all groups from the database. * * @return SUCCESS or a suitable error code */ public ServiceStatus deleteAllGroups() { SQLiteDatabase mDb = getWritableDatabase(); ServiceStatus mStatus = GroupsTable.deleteAllGroups(mDb); if (ServiceStatus.SUCCESS == mStatus) { mStatus = GroupsTable.populateSystemGroups(mContext, mDb); } return mStatus; } /*** * Fetches Avatar URLs from the database for all contacts which have an * Avatar and have not yet been loaded. * * @param thumbInfoList An empty list where the {@link ThumbnailInfo} * objects will be stored containing the URLs * @param firstIndex The 0-based index of the first item to fetch from the * database * @param count The maximum number of items to fetch * @return SUCCESS or a suitable error code * @see ThumbnailInfo * @see #fetchThumbnailUrlCount() */ public ServiceStatus fetchThumbnailUrls(List<ThumbnailInfo> thumbInfoList, int firstIndex, int count) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.fetchThumbnailUrls() firstIndex[" + firstIndex + "] " + "count[" + count + "]"); } Cursor mCursor = null; try { thumbInfoList.clear(); mCursor = getReadableDatabase().rawQuery( "SELECT " + ContactDetailsTable.TABLE_NAME + "." + ContactDetailsTable.Field.LOCALCONTACTID + "," + Field.STRINGVAL + " FROM " + ContactDetailsTable.TABLE_NAME + " INNER JOIN " + ContactSummaryTable.TABLE_NAME + " WHERE " + ContactDetailsTable.TABLE_NAME + "." + ContactDetailsTable.Field.LOCALCONTACTID + "=" + ContactSummaryTable.TABLE_NAME + "." + ContactSummaryTable.Field.LOCALCONTACTID + " AND " + ContactSummaryTable.Field.PICTURELOADED + " =0 " + " AND " + ContactDetailsTable.Field.KEY + "=" + ContactDetail.DetailKeys.PHOTO.ordinal() + " LIMIT " + firstIndex + "," + count, null); ArrayList<String> urls = new ArrayList<String>(); ThumbnailInfo mThumbnailInfo = null; while (mCursor.moveToNext()) { mThumbnailInfo = new ThumbnailInfo(); if (!mCursor.isNull(0)) { mThumbnailInfo.localContactId = mCursor.getLong(0); } mThumbnailInfo.photoServerUrl = mCursor.getString(1); if (!urls.contains(mThumbnailInfo.photoServerUrl)) { urls.add(mThumbnailInfo.photoServerUrl); thumbInfoList.add(mThumbnailInfo); } } // LogUtils.logWithName("THUMBNAILS:","urls:\n" + urls); return ServiceStatus.SUCCESS; } catch (SQLException e) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(mCursor); } } /*** * Fetches Avatar URLs from the database for all contacts from contactList * which have an Avatar and have not yet been loaded. * * @param thumbInfoList An empty list where the {@link ThumbnailInfo} * objects will be stored containing the URLs * @param contactList list of contacts to fetch the thumbnails for * @return SUCCESS or a suitable error code * @see ThumbnailInfo * @see #fetchThumbnailUrlCount() */ public ServiceStatus fetchThumbnailUrlsForContacts(List<ThumbnailInfo> thumbInfoList, final List<Long> contactList) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.fetchThumbnailUrls()"); } StringBuilder localContactIdList = new StringBuilder(); localContactIdList.append("("); Long localContactId = -1l; for (Long contactId : contactList) { if (localContactId != -1) { localContactIdList.append(","); } localContactId = contactId; localContactIdList.append(contactId); } localContactIdList.append(")"); Cursor cursor = null; try { thumbInfoList.clear(); cursor = getReadableDatabase().rawQuery( "SELECT " + ContactDetailsTable.TABLE_NAME + "." + ContactDetailsTable.Field.LOCALCONTACTID + "," + ContactDetailsTable.Field.STRINGVAL + " FROM " + ContactDetailsTable.TABLE_NAME + " INNER JOIN " + ContactSummaryTable.TABLE_NAME + " WHERE " + ContactDetailsTable.TABLE_NAME + "." + ContactDetailsTable.Field.LOCALCONTACTID + " in " + localContactIdList.toString() + " AND " + ContactSummaryTable.Field.PICTURELOADED + " =0 " + " AND " + ContactDetailsTable.Field.KEY + "=" + ContactDetail.DetailKeys.PHOTO.ordinal(), null); ArrayList<String> urls = new ArrayList<String>(); ThumbnailInfo mThumbnailInfo = null; while (cursor.moveToNext()) { mThumbnailInfo = new ThumbnailInfo(); if (!cursor .isNull(cursor .getColumnIndexOrThrow(ContactDetailsTable.Field.LOCALCONTACTID .toString()))) { mThumbnailInfo.localContactId = cursor.getLong(cursor .getColumnIndexOrThrow(ContactDetailsTable.Field.LOCALCONTACTID .toString())); } mThumbnailInfo.photoServerUrl = cursor.getString(cursor .getColumnIndexOrThrow(ContactDetailsTable.Field.STRINGVAL.toString())); // TODO: Investigate if this is really needed if (!urls.contains(mThumbnailInfo.photoServerUrl)) { urls.add(mThumbnailInfo.photoServerUrl); thumbInfoList.add(mThumbnailInfo); } } return ServiceStatus.SUCCESS; } catch (SQLException e) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } } /** * Fetches the list of all the contactIds for which the Thumbnail still needs to * be downloaded. Firstly, the list of all the contactIds whose picture_loaded * flag is set to false is retrieved from the ContactSummaryTable. Then these contactids * are further filtered based on whether they have a photo URL assigned to them * in the ContactDetails table. * @param contactIdList An empty list where the retrieved contact IDs are stored. * @return SUCCESS or a suitable error code */ public ServiceStatus fetchContactIdsWithThumbnails(List<Long> contactIdList) { SQLiteDatabase db = getReadableDatabase(); Cursor cr = null; try { String sql = "SELECT " + ContactSummaryTable.Field.LOCALCONTACTID + " FROM " + ContactSummaryTable.TABLE_NAME + " WHERE " + ContactSummaryTable.Field.PICTURELOADED + " =0 AND " + ContactSummaryTable.Field.LOCALCONTACTID + " IN (SELECT " + ContactDetailsTable.Field.LOCALCONTACTID + " FROM " + ContactDetailsTable.TABLE_NAME + " WHERE " + ContactDetailsTable.Field.KEY + "=" + ContactDetail.DetailKeys.PHOTO.ordinal() + ")"; cr = db.rawQuery(sql, null); Long localContactId = -1L; while (cr.moveToNext()) { if (!cr .isNull(cr .getColumnIndexOrThrow(ContactDetailsTable.Field.LOCALCONTACTID .toString()))) { localContactId = cr.getLong(cr .getColumnIndexOrThrow(ContactDetailsTable.Field.LOCALCONTACTID .toString())); contactIdList.add(localContactId); } } return ServiceStatus.SUCCESS; } catch (SQLException e) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cr); } } /*** * Fetches the number of Contact Avatars which have not yet been loaded. * * @return The number of Avatars * @see ThumbnailInfo * @see #fetchThumbnailUrls(List, int, int) */ public int fetchThumbnailUrlCount() { trace(false, "DatabaseHelper.fetchThumbnailUrlCount()"); Cursor mCursor = null; try { mCursor = getReadableDatabase().rawQuery( "SELECT COUNT(" + ContactSummaryTable.Field.SUMMARYID + ") FROM " + ContactSummaryTable.TABLE_NAME + " WHERE " + ContactSummaryTable.Field.PICTURELOADED + " =0 ", null); if (mCursor.moveToFirst()) { if (!mCursor.isNull(0)) { return mCursor.getInt(0); } } return 0; } catch (SQLException e) { return 0; } finally { CloseUtils.close(mCursor); } } /*** * Modifies the Me Profile Avatar Changed Flag. When this flag is set to * true, it indicates that the avatar needs to be synchronised with the * server. * * @param avatarChanged true to set the flag, false to clear the flag * @return SUCCESS or a suitable error code */ public ServiceStatus modifyMeProfileAvatarChangedFlag(boolean avatarChanged) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.modifyMeProfileAvatarChangedFlag() avatarChanged[" + avatarChanged + "]"); } if (avatarChanged == mMeProfileAvatarChangedFlag) { return ServiceStatus.SUCCESS; } ServiceStatus mResult = StateTable.modifyMeProfileChangedFlag(avatarChanged, getWritableDatabase()); if (ServiceStatus.SUCCESS == mResult) { mMeProfileAvatarChangedFlag = avatarChanged; } return mResult; } /*** * Fetches a cursor which can be used to iterate through the main contact * list. * <p> * The ContactSummaryTable.getQueryData static method can be used on the * cursor returned by this method to create a ContactSummary object. * * @param groupFilterId The local ID of a group to filter, or null if no * filter is required * @param constraint A search string to filter the contact name, or null if * no filter is required * @return The cursor result */ public synchronized Cursor openContactSummaryCursor(Long groupFilterId, CharSequence constraint) { return ContactSummaryTable.openContactSummaryCursor(groupFilterId, constraint, SyncMeDbUtils.getMeProfileLocalContactId(this), getReadableDatabase()); } public synchronized Cursor openContactsCursor() { return ContactsTable.openContactsCursor(getReadableDatabase()); } /*** * Fetches a contact from the database by its localContactId. The method * {@link #fetchBaseContact(long, Contact)} should be used if the contact * details properties are not required. * * @param localContactId Local ID of the contact to fetch. * @param contact Empty {@link Contact} object which will be populated with * data. * @return SUCCESS or a suitable ServiceStatus error code. */ public synchronized ServiceStatus fetchContact(long localContactId, Contact contact) { SQLiteDatabase db = getReadableDatabase(); ServiceStatus status = fetchBaseContact(localContactId, contact, db); if (ServiceStatus.SUCCESS != status) { return status; } status = ContactDetailsTable.fetchContactDetails(localContactId, contact.details, db); if (ServiceStatus.SUCCESS != status) { return status; } return ServiceStatus.SUCCESS; } /*** * Fetches a contact detail from the database. * * @param localDetailId The local ID of the detail to fetch * @param detail A empty {@link ContactDetail} object which will be filled * with the data * @return SUCCESS or a suitable error code */ public synchronized ServiceStatus fetchContactDetail(long localDetailId, ContactDetail detail) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.fetchContactDetail() localDetailId[" + localDetailId + "]"); } Cursor mCursor = null; try { try { String[] args = { String.format("%d", localDetailId) }; mCursor = getReadableDatabase() .rawQuery( ContactDetailsTable .getQueryStringSql(ContactDetailsTable.Field.DETAILLOCALID + " = ?"), args); } catch (SQLiteException e) { LogUtils.logE("DatabaseHelper.fetchContactDetail() Unable to fetch contact detail", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } if (!mCursor.moveToFirst()) { return ServiceStatus.ERROR_NOT_FOUND; } detail.copy(ContactDetailsTable.getQueryData(mCursor)); return ServiceStatus.SUCCESS; } finally { CloseUtils.close(mCursor); } } /*** * Searches the database for a contact with a given phone number. * * @param phoneNumber The telephone number to find * @param contact An empty Contact object which will be filled if a contact * is found * @param phoneDetail An empty {@link ContactDetail} object which will be * filled with the matching phone number detail * @return SUCCESS or a suitable error code */ public synchronized ServiceStatus fetchContactInfo(String phoneNumber, Contact contact, ContactDetail phoneDetail) { ServiceStatus mStatus = ContactDetailsTable.fetchContactInfo(phoneNumber, phoneDetail, null, getReadableDatabase()); if (ServiceStatus.SUCCESS != mStatus) { return mStatus; } return fetchContact(phoneDetail.localContactID, contact); } /*** * Puts a contact into a group. * * @param localContactId The local Id of the contact * @param groupId The local group Id * @return SUCCESS or a suitable error code * @see #deleteContactFromGroup(long, long) */ public ServiceStatus addContactToGroup(long localContactId, long groupId) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.addContactToGroup() localContactId[" + localContactId + "] " + "groupId[" + groupId + "]"); } SQLiteDatabase mDb = getWritableDatabase(); List<Long> groupIds = new ArrayList<Long>(); ContactGroupsTable.fetchContactGroups(localContactId, groupIds, mDb); if (groupIds.contains(groupId)) { // group is already in db than it's ok return ServiceStatus.SUCCESS; } boolean syncToServer = true; boolean mIsMeProfile = false; if (SyncMeDbUtils.getMeProfileLocalContactId(this) != null && SyncMeDbUtils.getMeProfileLocalContactId(this).longValue() == localContactId) { mIsMeProfile = true; syncToServer = false; } Contact mContact = new Contact(); ServiceStatus mStatus = fetchContact(localContactId, mContact); if (ServiceStatus.SUCCESS != mStatus) { return mStatus; } try { mDb.beginTransaction(); if (!ContactGroupsTable.addContactToGroup(localContactId, groupId, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } if (syncToServer) { if (!ContactChangeLogTable.addGroupRel(localContactId, mContact.contactID, groupId, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } if (syncToServer && !mIsMeProfile) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); } return ServiceStatus.SUCCESS; } /*** * Removes a group from a contact. * * @param localContactId The local Id of the contact * @param groupId The local group Id * @return SUCCESS or a suitable error code * @see #addContactToGroup(long, long) */ public ServiceStatus deleteContactFromGroup(long localContactId, long groupId) { if (Settings.ENABLED_DATABASE_TRACE) trace(false, "DatabaseHelper.deleteContactFromGroup() localContactId[" + localContactId + "] groupId[" + groupId + "]"); boolean syncToServer = true; boolean meProfile = false; if (SyncMeDbUtils.getMeProfileLocalContactId(this) != null && SyncMeDbUtils.getMeProfileLocalContactId(this).longValue() == localContactId) { meProfile = true; syncToServer = false; } Contact mContact = new Contact(); ServiceStatus mStatus = fetchContact(localContactId, mContact); if (ServiceStatus.SUCCESS != mStatus) { return mStatus; } if (mContact.contactID == null) { return ServiceStatus.ERROR_NOT_READY; } SQLiteDatabase mDb = getWritableDatabase(); try { mDb.beginTransaction(); boolean mResult = ContactGroupsTable.deleteContactFromGroup(localContactId, groupId, mDb); if (mResult && syncToServer) { if (!ContactChangeLogTable.deleteGroupRel(localContactId, mContact.contactID, groupId, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } if (syncToServer && !meProfile) { fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, false); } return ServiceStatus.SUCCESS; } /*** * Removes all the status or timeline activities from the database. Note: * Only called from tests. * * @param flag The type of activity to delete or null to delete all * @return SUCCESS or a suitable error code * @see #addActivities(List) * @see #addTimelineEvents(ArrayList, boolean) * @see #fetchActivitiesIds(List, Long) * @see #fetchTimelineEvents(Long, * com.vodafone360.people.database.tables.ActivitiesTable.TimelineNativeTypes[]) */ public ServiceStatus deleteActivities(Integer flag) { if (Settings.ENABLED_DATABASE_TRACE) trace(false, "DatabaseHelper.deleteActivities() flag[" + flag + "]"); ServiceStatus mStatus = ActivitiesTable.deleteActivities(flag, getWritableDatabase()); if (ServiceStatus.SUCCESS == mStatus) { if (flag == null || flag.intValue() == ActivityItem.TIMELINE_ITEM) { StateTable.modifyLatestPhoneCallTime(System.currentTimeMillis(), getWritableDatabase()); } } fireDatabaseChangedEvent(DatabaseChangeType.ACTIVITIES, true); return mStatus; } /*** * Removes the selected timeline activity from the database. * * @param mApplication The MainApplication * @param timelineItem TimelineSummaryItem to be deleted * @return SUCCESS or a suitable error code */ public ServiceStatus deleteTimelineActivity(MainApplication mApplication, TimelineSummaryItem timelineItem, boolean isTimelineAll) { if (Settings.ENABLED_DATABASE_TRACE) trace(false, "DatabaseHelper.deleteTimelineActivity()"); ServiceStatus mStatus = ServiceStatus.SUCCESS; - if (isTimelineAll == true) { + if (isTimelineAll) { mStatus = ActivitiesTable.deleteTimelineActivities(mContext, timelineItem, getWritableDatabase(), getReadableDatabase()); } else { mStatus = ActivitiesTable.deleteTimelineActivity(mContext, timelineItem, getWritableDatabase(), getReadableDatabase()); } if (mStatus == ServiceStatus.SUCCESS) { // Update Notifications in the Notification Bar IPeopleService peopleService = mApplication.getServiceInterface(); long localContactId = 0L; if (timelineItem.mLocalContactId != null) { localContactId = timelineItem.mLocalContactId; } peopleService.updateChatNotification(localContactId); } fireDatabaseChangedEvent(DatabaseChangeType.ACTIVITIES, true); return mStatus; } /** * Add a list of new activities to the Activities table. * * @param activityList contains the list of activity item * @return SUCCESS or a suitable error code * @see #deleteActivities(Integer) * @see #addTimelineEvents(ArrayList, boolean) */ public ServiceStatus addActivities(List<ActivityItem> activityList) { SQLiteDatabase writableDb = getWritableDatabase(); ServiceStatus mStatus = ActivitiesTable.addActivities(activityList, writableDb); ActivitiesTable.cleanupActivityTable(writableDb); fireDatabaseChangedEvent(DatabaseChangeType.ACTIVITIES, true); return mStatus; } /*** * Fetches a list of activity IDs from a given time. * * @param activityIdList an empty list to be populated * @param timeStamp The oldest time that should be included in the list * @return SUCCESS or a suitable error code * @see #fetchTimelineEvents(Long, * com.vodafone360.people.database.tables.ActivitiesTable.TimelineNativeTypes[]) */ public synchronized ServiceStatus fetchActivitiesIds(List<Long> activityIdList, Long timeStamp) { if (Settings.ENABLED_DATABASE_TRACE) { trace(false, "DatabaseHelper.fetchActivitiesIds() timeStamp[" + timeStamp + "]"); } activityIdList.clear(); ActivitiesTable.fetchActivitiesIds(activityIdList, timeStamp, getReadableDatabase()); return ServiceStatus.SUCCESS; } /*** * Fetches timeline events from a given time. * * @param timeStamp The oldest time that should be included in the list * @param types A list of required timeline types (or an empty list for all) * @return SUCCESS or a suitable error code * @see #addTimelineEvents(ArrayList, boolean) * @see #fetchActivitiesIds(List, Long) */ public synchronized Cursor fetchTimelineEvents(Long timeStamp, ActivitiesTable.TimelineNativeTypes[] types) { return ActivitiesTable.fetchTimelineEventList(timeStamp, types, getReadableDatabase()); } /*** * Fetches fires a database change event to the listeners. * * @param type The type of database change (contacts, activity, etc) * @param isExternal true if this change came from the server, false if the * change is from the client * @see #addEventCallback(Handler) * @see #removeEventCallback(Handler) * @see #fireSettingChangedEvent(PersistSettings) */ public void fireDatabaseChangedEvent(DatabaseHelper.DatabaseChangeType type, boolean isExternal) { DbEventType event = new DbEventType(); event.ordinal = type.ordinal(); event.isExternal = isExternal; synchronized (mDbEvents) { if (mDbEvents.size() == 0) { // Creating a DbEventTimerTask every time because of preemptive-ness DbEventTimerTask dbEventTask = new DbEventTimerTask(); mDbEventTimer.schedule(dbEventTask, DATABASE_EVENT_DELAY); } if (!mDbEvents.contains(event)) { mDbEvents.add(event); } } } /*** * Add a database change listener. The listener will be notified each time * the database is changed. * * @param uiHandler The handler which will be notified * @see #fireDatabaseChangedEvent(DatabaseChangeType, boolean) * @see #fireSettingChangedEvent(PersistSettings) */ public synchronized void addEventCallback(Handler uiHandler) { if (!mUiEventCallbackList.contains(uiHandler)) { mUiEventCallbackList.add(uiHandler); } } /*** * Removes a database change listener. This must be called before UI * activities are destroyed. * * @param uiHandler The handler which will be notified * @see #addEventCallback(Handler) */ public synchronized void removeEventCallback(Handler uiHandler) { if (mUiEventCallbackList != null) { mUiEventCallbackList.remove(uiHandler); } } /*** * Internal function to fire a setting changed event to listeners. * * @param setting The setting that has changed with the new data * @see #addEventCallback(Handler) * @see #removeEventCallback(Handler) * @see #fireDatabaseChangedEvent(DatabaseChangeType, boolean) */ private synchronized void fireSettingChangedEvent(PersistSettings setting) { fireEventToUi(ServiceUiRequest.SETTING_CHANGED_EVENT, 0, 0, setting); } /*** * Internal function to send an event to all the listeners. * * @param event The type of event * @param arg1 This value depends on the type of event * @param arg2 This value depends on the type of event * @param data This value depends on the type of event * @see #fireDatabaseChangedEvent(DatabaseChangeType, boolean) * @see #fireSettingChangedEvent(PersistSettings) */ private void fireEventToUi(ServiceUiRequest event, int arg1, int arg2, Object data) { for (Handler mHandler : mUiEventCallbackList) { Message mMessage = mHandler.obtainMessage(event.ordinal(), data); mMessage.arg1 = arg1; mMessage.arg2 = arg2; mHandler.sendMessage(mMessage); } } /*** * Function used by the contact sync engine to add a list of contacts to the * database. * * @param contactList The list of contacts received from the server * @param syncToServer true if the contacts need to be sent to the server * @param syncToNative true if the contacts need to be added to the native * phonebook * @return SUCCESS or a suitable error code * @see #addContact(Contact) */ public ServiceStatus syncAddContactList(List<Contact> contactList, boolean syncToServer, boolean syncToNative) { if (Settings.ENABLED_DATABASE_TRACE) trace(false, "DatabaseHelper.syncAddContactList() syncToServer[" + syncToServer + "] syncToNative[" + syncToNative + "]"); if (!Settings.ENABLE_SERVER_CONTACT_SYNC) { syncToServer = false; } if (!Settings.ENABLE_UPDATE_NATIVE_CONTACTS) { syncToNative = false; } String contactDetailFriendyName = null; SQLiteDatabase mDb = getWritableDatabase(); for (Contact mContact : contactList) { mContact.deleted = null; mContact.localContactID = null; if (syncToNative) { mContact.nativeContactId = null; } if (syncToServer) { mContact.contactID = null; mContact.updated = null; mContact.synctophone = true; } try { mDb.beginTransaction(); ServiceStatus mStatus = ContactsTable.addContact(mContact, mDb); if (ServiceStatus.SUCCESS != mStatus) { LogUtils .logE("DatabaseHelper.syncAddContactList() Unable to add contact to contacts table, due to a database error"); return mStatus; } List<ContactDetail.DetailKeys> orderList = new ArrayList<ContactDetail.DetailKeys>(); for (int i = 0; i < mContact.details.size(); i++) { final ContactDetail detail = mContact.details.get(i); detail.localContactID = mContact.localContactID; detail.localDetailID = null; if (syncToServer) { detail.unique_id = null; } if (detail.order != null && (detail.order.equals(ContactDetail.ORDER_PREFERRED))) { if (orderList.contains(detail.key)) { detail.order = ContactDetail.ORDER_NORMAL; } else { orderList.add(detail.key); } } mStatus = ContactDetailsTable.addContactDetail(detail, syncToServer, (syncToNative && mContact.synctophone), mDb); if (ServiceStatus.SUCCESS != mStatus) { LogUtils .logE("DatabaseHelper.syncAddContactList() Unable to add contact detail (for new contact), due to a database error. Contact ID[" + mContact.localContactID + "]"); return mStatus; } // getting name for timeline updates if (detail.key == ContactDetail.DetailKeys.VCARD_NAME) { VCardHelper.Name name = detail.getName(); if (name != null) { contactDetailFriendyName = name.toString(); } } } // AA: added the check to make sure that contacts with empty // contact // details are not stored if (!mContact.details.isEmpty()) { mStatus = ContactSummaryTable.addContact(mContact, mDb); if (ServiceStatus.SUCCESS != mStatus) { return mStatus; } } if (mContact.groupList != null) { for (Long groupId : mContact.groupList) { if (groupId != -1 && !ContactGroupsTable.addContactToGroup(mContact.localContactID, groupId, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } } } if (mContact.sources != null) { for (String source : mContact.sources) { if (!ContactSourceTable.addContactSource(mContact.localContactID, source, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } } } if (syncToServer) { if (mContact.groupList != null) { for (Long mGroupId : mContact.groupList) { if (!ContactChangeLogTable.addGroupRel(mContact.localContactID, mContact.contactID, mGroupId, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } } } } // updating timeline for (ContactDetail detail : mContact.details) { // we already have name, don't need to get it again if (detail.key != ContactDetail.DetailKeys.VCARD_NAME) { detail.localContactID = mContact.localContactID; detail.nativeContactId = mContact.nativeContactId; updateTimelineNames(detail, contactDetailFriendyName, mContact.contactID, mDb); } } // Update the summary with the new contact mStatus = updateNameAndStatusInSummary(mDb, mContact.localContactID); if (ServiceStatus.SUCCESS != mStatus) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /*** * Function used by the contact sync engine to modify a list of contacts in * the database. * * @param contactList The list of contacts received from the server * @param syncToServer true if the contacts need to be sent to the server * @param syncToNative true if the contacts need to be modified in the * native phonebook * @return SUCCESS or a suitable error code */ public ServiceStatus syncModifyContactList(List<Contact> contactList, boolean syncToServer, boolean syncToNative) { if (Settings.ENABLED_DATABASE_TRACE) trace(false, "DatabaseHelper.syncModifyContactList() syncToServer[" + syncToServer + "] syncToNative[" + syncToNative + "]"); if (!Settings.ENABLE_SERVER_CONTACT_SYNC) { syncToServer = false; } if (!Settings.ENABLE_UPDATE_NATIVE_CONTACTS) { syncToNative = false; } String contactDetailFriendyName = null; SQLiteDatabase mDb = getWritableDatabase(); for (Contact mContact : contactList) { if (syncToServer) { mContact.updated = null; } try { mDb.beginTransaction(); ServiceStatus mStatus = ContactsTable.modifyContact(mContact, mDb); if (ServiceStatus.SUCCESS != mStatus) { LogUtils .logE("DatabaseHelper.syncModifyContactList() Unable to modify contact, due to a database error"); return mStatus; } mStatus = ContactSummaryTable.modifyContact(mContact, mDb); if (ServiceStatus.SUCCESS != mStatus) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } if (mContact.groupList != null) { mStatus = ContactGroupsTable.modifyContact(mContact, mDb); if (ServiceStatus.SUCCESS != mStatus) { return mStatus; } } if (mContact.sources != null) { if (!ContactSourceTable.deleteAllContactSources(mContact.localContactID, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } for (String source : mContact.sources) { if (!ContactSourceTable.addContactSource(mContact.localContactID, source, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } } } // updating timeline events // getting name for (ContactDetail detail : mContact.details) { if (detail.key == ContactDetail.DetailKeys.VCARD_NAME) { VCardHelper.Name name = detail.getName(); if (name != null) { contactDetailFriendyName = name.toString(); } } } // updating phone no for (ContactDetail detail : mContact.details) { detail.localContactID = mContact.localContactID; detail.nativeContactId = mContact.nativeContactId; updateTimelineNames(detail, contactDetailFriendyName, mContact.contactID, mDb); } // END updating timeline events // Update the summary with the new contact mStatus = updateNameAndStatusInSummary(mDb, mContact.localContactID); if (ServiceStatus.SUCCESS != mStatus) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /*** * Function used by the contact sync engine to delete a list of contacts * from the database. * * @param contactIdList The list of contact IDs received from the server (at * least localId should be set) * @param syncToServer true if the contacts need to be deleted from the * server * @param syncToNative true if the contacts need to be deleted from the * native phonebook * @return SUCCESS or a suitable error code * @see #deleteContact(long) */ public ServiceStatus syncDeleteContactList(List<ContactsTable.ContactIdInfo> contactIdList, boolean syncToServer, boolean syncToNative) { if (Settings.ENABLED_DATABASE_TRACE) trace(false, "DatabaseHelper.syncDeleteContactList() syncToServer[" + syncToServer + "] syncToNative[" + syncToNative + "]"); if (!Settings.ENABLE_SERVER_CONTACT_SYNC) { syncToServer = false; } if (!Settings.ENABLE_UPDATE_NATIVE_CONTACTS) { syncToNative = false; } SQLiteDatabase mDb = getWritableDatabase(); for (ContactsTable.ContactIdInfo mInfo : contactIdList) { try { mDb.beginTransaction(); if (syncToNative && mInfo.mergedLocalId == null) { if (!NativeChangeLogTable.addDeletedContactChange(mInfo.localId, mInfo.nativeId, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } } if (syncToServer) { if (!ContactChangeLogTable.addDeletedContactChange(mInfo.localId, mInfo.serverId, syncToServer, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } } if (!ContactGroupsTable.deleteContact(mInfo.localId, mDb)) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } if (SyncMeDbUtils.getMeProfileLocalContactId(this) != null && SyncMeDbUtils.getMeProfileLocalContactId(this).longValue() == mInfo.localId) { ServiceStatus status = StateTable.modifyMeProfileID(null, mDb); if (ServiceStatus.SUCCESS != status) { return status; } SyncMeDbUtils.setMeProfileId(null); PresenceDbUtils.resetMeProfileIds(); } ServiceStatus mStatus = ContactSummaryTable.deleteContact(mInfo.localId, mDb); if (ServiceStatus.SUCCESS != mStatus) { return mStatus; } mStatus = ContactDetailsTable.deleteDetailByContactId(mInfo.localId, mDb); if (ServiceStatus.SUCCESS != mStatus && ServiceStatus.ERROR_NOT_FOUND != mStatus) { return mStatus; } mStatus = ContactsTable.deleteContact(mInfo.localId, mDb); if (ServiceStatus.SUCCESS != mStatus) { return mStatus; } if (!deleteThumbnail(mInfo.localId)) LogUtils.logE("Not able to delete thumbnail for: " + mInfo.localId); // timeline ActivitiesTable.removeTimelineContactData(mInfo.localId, mDb); mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /*** * Function used by the contact sync engine to merge contacts which are * marked as duplicate by the server. This involves moving native * information from one contact to the other, before deleting it. * * @param contactIdList The list of contact IDs (localId, serverId and * mergedLocalId should be set) * @return SUCCESS or a suitable error code */ public ServiceStatus syncMergeContactList(List<ContactsTable.ContactIdInfo> contactIdList) { if (Settings.ENABLED_DATABASE_TRACE) trace(false, "DatabaseHelper.syncMergeContactList()"); List<ContactDetail> detailInfoList = new ArrayList<ContactDetail>(); SQLiteDatabase writableDb = getWritableDatabase(); SQLiteStatement contactStatement = null, contactSummaryStatement = null, contactFetchNativeIdStatement = null; try { contactStatement = ContactsTable.mergeContactStatement(writableDb); contactSummaryStatement = ContactSummaryTable.mergeContactStatement(writableDb); contactFetchNativeIdStatement = ContactsTable .fetchNativeFromLocalIdStatement(writableDb); writableDb.beginTransaction(); for (int i = 0; i < contactIdList.size(); i++) { ContactsTable.ContactIdInfo contactIdInfo = contactIdList.get(i); if (contactIdInfo.mergedLocalId != null) { contactIdInfo.nativeId = ContactsTable.fetchNativeFromLocalId( contactIdInfo.localId, contactFetchNativeIdStatement); LogUtils .logI("DatabaseHelper.syncMergeContactList - Copying native Ids from duplicate to original contact: Dup ID " + contactIdInfo.localId diff --git a/src/com/vodafone360/people/database/tables/ActivitiesTable.java b/src/com/vodafone360/people/database/tables/ActivitiesTable.java index d13f41b..bf86ad1 100644 --- a/src/com/vodafone360/people/database/tables/ActivitiesTable.java +++ b/src/com/vodafone360/people/database/tables/ActivitiesTable.java @@ -247,1140 +247,1155 @@ public abstract class ActivitiesTable { final StringBuilder sb = new StringBuilder("TimeLineSummaryItem [mLocalActivityId["); sb.append(mLocalActivityId); sb.append("], mTimestamp["); sb.append(mTimestamp); sb.append("], mContactName["); sb.append(mContactName); sb.append("], mHasAvatar["); sb.append(mHasAvatar); sb.append("], mType["); sb.append(mType); sb.append("], mLocalContactId["); sb.append(mLocalContactId); sb.append("], mContactNetwork["); sb.append(mContactNetwork); sb.append("], mTitle["); sb.append(mTitle); sb.append("], mDescription["); sb.append(mDescription); sb.append("], mNativeItemType["); sb.append(mNativeItemType); sb.append("], mNativeItemId["); sb.append(mNativeItemId); sb.append("], mContactId["); sb.append(mContactId); sb.append("], mUserId["); sb.append(mUserId); sb.append("], mNativeThreadId["); sb.append(mNativeThreadId); sb.append("], mContactAddress["); sb.append(mContactAddress); sb.append("], mIncoming["); sb.append(mIncoming); sb.append("]]");; return sb.toString(); } @Override public final boolean equals(final Object object) { if (TimelineSummaryItem.class != object.getClass()) { return false; } TimelineSummaryItem item = (TimelineSummaryItem) object; return mLocalActivityId.equals(item.mLocalActivityId) && mTimestamp.equals(item.mTimestamp) && mContactName.equals(item.mContactName) && mHasAvatar == item.mHasAvatar && mType.equals(item.mType) && mLocalContactId.equals(item.mLocalContactId) && mContactNetwork.equals(item.mContactNetwork) && mTitle.equals(item.mTitle) && mDescription.equals(item.mDescription) && mNativeItemType.equals(item.mNativeItemType) && mNativeItemId.equals(item.mNativeItemId) && mContactId.equals(item.mContactId) && mUserId.equals(item.mUserId) && mNativeThreadId.equals(item.mNativeThreadId) && mContactAddress.equals(item.mContactAddress) && mIncoming.equals(item.mIncoming); } }; /** Number of milliseconds in a day. **/ private static final int NUMBER_OF_MS_IN_A_DAY = 24 * 60 * 60 * 1000; /** Number of milliseconds in a second. **/ private static final int NUMBER_OF_MS_IN_A_SECOND = 1000; /*** * Private constructor to prevent instantiation. */ private ActivitiesTable() { // Do nothing. } /** * Create Activities Table. * * @param writeableDb A writable SQLite database. */ public static void create(final SQLiteDatabase writeableDb) { DatabaseHelper.trace(true, "DatabaseHelper.create()"); writeableDb.execSQL("CREATE TABLE " + TABLE_NAME + " (" + Field.LOCAL_ACTIVITY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.ACTIVITY_ID + " LONG, " + Field.TIMESTAMP + " LONG, " + Field.TYPE + " TEXT, " + Field.URI + " TEXT, " + Field.TITLE + " TEXT, " + Field.DESCRIPTION + " TEXT, " + Field.PREVIEW_URL + " TEXT, " + Field.STORE + " TEXT, " + Field.FLAG + " INTEGER, " + Field.PARENT_ACTIVITY + " LONG, " + Field.HAS_CHILDREN + " INTEGER, " + Field.VISIBILITY + " INTEGER, " + Field.MORE_INFO + " TEXT, " + Field.CONTACT_ID + " LONG, " + Field.USER_ID + " LONG, " + Field.CONTACT_NAME + " TEXT, " + Field.LOCAL_CONTACT_ID + " LONG, " + Field.CONTACT_NETWORK + " TEXT, " + Field.CONTACT_ADDRESS + " TEXT, " + Field.CONTACT_AVATAR_URL + " TEXT, " + Field.LATEST_CONTACT_STATUS + " INTEGER, " + Field.NATIVE_ITEM_TYPE + " INTEGER, " + Field.NATIVE_ITEM_ID + " INTEGER, " + Field.NATIVE_THREAD_ID + " INTEGER, " + Field.INCOMING + " INTEGER);"); writeableDb.execSQL("CREATE INDEX " + TABLE_INDEX_NAME + " ON " + TABLE_NAME + " ( " + Field.TIMESTAMP + " )"); } /** * Fetches a comma separated list of table fields which can be used in an * SQL SELECT statement as the query projection. One of the * {@link #getQueryData} methods can used to fetch data from the cursor. * * @return SQL string */ private static String getFullQueryList() { DatabaseHelper.trace(false, "DatabaseHelper.getFullQueryList()"); final StringBuffer fullQuery = StringBufferPool.getStringBuffer(); fullQuery.append(Field.LOCAL_ACTIVITY_ID).append(SqlUtils.COMMA). append(Field.ACTIVITY_ID).append(SqlUtils.COMMA). append(Field.TIMESTAMP).append(SqlUtils.COMMA). append(Field.TYPE).append(SqlUtils.COMMA). append(Field.URI).append(SqlUtils.COMMA). append(Field.TITLE).append(SqlUtils.COMMA). append(Field.DESCRIPTION).append(SqlUtils.COMMA). append(Field.PREVIEW_URL).append(SqlUtils.COMMA). append(Field.STORE).append(SqlUtils.COMMA). append(Field.FLAG).append(SqlUtils.COMMA). append(Field.PARENT_ACTIVITY).append(SqlUtils.COMMA). append(Field.HAS_CHILDREN).append(SqlUtils.COMMA). append(Field.VISIBILITY).append(SqlUtils.COMMA). append(Field.MORE_INFO).append(SqlUtils.COMMA). append(Field.CONTACT_ID).append(SqlUtils.COMMA). append(Field.USER_ID).append(SqlUtils.COMMA). append(Field.CONTACT_NAME).append(SqlUtils.COMMA). append(Field.LOCAL_CONTACT_ID).append(SqlUtils.COMMA). append(Field.CONTACT_NETWORK).append(SqlUtils.COMMA). append(Field.CONTACT_ADDRESS).append(SqlUtils.COMMA). append(Field.CONTACT_AVATAR_URL).append(SqlUtils.COMMA). append(Field.INCOMING); return StringBufferPool.toStringThenRelease(fullQuery); } /** * Fetches activities information from a cursor at the current position. The * {@link #getFullQueryList()} method should be used to make the query. * * @param cursor The cursor returned by the query * @param activityItem An empty activity object that will be filled with the * result * @param activityContact An empty activity contact object that will be * filled */ public static void getQueryData(final Cursor cursor, final ActivityItem activityItem, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityItem. **/ activityItem.localActivityId = SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); activityItem.activityId = SqlUtils.setLong(cursor, Field.ACTIVITY_ID.toString(), null); activityItem.time = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); activityItem.type = SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); activityItem.uri = SqlUtils.setString(cursor, Field.URI.toString()); activityItem.title = SqlUtils.setString(cursor, Field.TITLE.toString()); activityItem.description = SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); activityItem.previewUrl = SqlUtils.setString(cursor, Field.PREVIEW_URL.toString()); activityItem.store = SqlUtils.setString(cursor, Field.STORE.toString()); activityItem.activityFlags = SqlUtils.setInt(cursor, Field.FLAG.toString(), null); activityItem.parentActivity = SqlUtils.setLong(cursor, Field.PARENT_ACTIVITY.toString(), null); activityItem.hasChildren = SqlUtils.setBoolean(cursor, Field.HAS_CHILDREN.toString(), activityItem.hasChildren); activityItem.visibilityFlags = SqlUtils.setInt(cursor, Field.VISIBILITY.toString(), null); // TODO: Field MORE_INFO is not used, consider deleting. /** Populate ActivityContact. **/ getQueryData(cursor, activityContact); } /** * Fetches activities information from a cursor at the current position. The * {@link #getFullQueryList()} method should be used to make the query. * * @param cursor The cursor returned by the query. * @param activityContact An empty activity contact object that will be * filled */ public static void getQueryData(final Cursor cursor, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityContact. **/ activityContact.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); activityContact.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); activityContact.mName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); activityContact.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); activityContact.mNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); activityContact.mAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); activityContact.mAvatarUrl = SqlUtils.setString(cursor, Field.CONTACT_AVATAR_URL.toString()); } /*** * Provides a ContentValues object that can be used to update the table. * * @param item The source activity item * @param contactIdx The index of the contact to use for the update, or null * to exclude contact specific information. * @return ContentValues for use in an SQL update or insert. * @note Items that are NULL will be not modified in the database. */ private static ContentValues fillUpdateData(final ActivityItem item, final Integer contactIdx) { DatabaseHelper.trace(false, "DatabaseHelper.fillUpdateData()"); ContentValues activityItemValues = new ContentValues(); ActivityContact ac = null; if (contactIdx != null) { ac = item.contactList.get(contactIdx); } activityItemValues.put(Field.ACTIVITY_ID.toString(), item.activityId); activityItemValues.put(Field.TIMESTAMP.toString(), item.time); if (item.type != null) { activityItemValues.put(Field.TYPE.toString(), item.type.getTypeCode()); } if (item.uri != null) { activityItemValues.put(Field.URI.toString(), item.uri); } /** TODO: Not sure if we need this. **/ // activityItemValues.put(Field.INCOMING.toString(), false); activityItemValues.put(Field.TITLE.toString(), item.title); activityItemValues.put(Field.DESCRIPTION.toString(), item.description); if (item.previewUrl != null) { activityItemValues.put(Field.PREVIEW_URL.toString(), item.previewUrl); } if (item.store != null) { activityItemValues.put(Field.STORE.toString(), item.store); } if (item.activityFlags != null) { activityItemValues.put(Field.FLAG.toString(), item.activityFlags); } if (item.parentActivity != null) { activityItemValues.put(Field.PARENT_ACTIVITY.toString(), item.parentActivity); } if (item.hasChildren != null) { activityItemValues.put(Field.HAS_CHILDREN.toString(), item.hasChildren); } if (item.visibilityFlags != null) { activityItemValues.put(Field.VISIBILITY.toString(), item.visibilityFlags); } if (ac != null) { activityItemValues.put(Field.CONTACT_ID.toString(), ac.mContactId); activityItemValues.put(Field.USER_ID.toString(), ac.mUserId); activityItemValues.put(Field.CONTACT_NAME.toString(), ac.mName); activityItemValues.put(Field.LOCAL_CONTACT_ID.toString(), ac.mLocalContactId); if (ac.mNetwork != null) { activityItemValues.put(Field.CONTACT_NETWORK.toString(), ac.mNetwork); } if (ac.mAddress != null) { activityItemValues.put(Field.CONTACT_ADDRESS.toString(), ac.mAddress); } if (ac.mAvatarUrl != null) { activityItemValues.put(Field.CONTACT_AVATAR_URL.toString(), ac.mAvatarUrl); } } return activityItemValues; } /** * Fetches a list of status items from the given time stamp. * * @param timeStamp Time stamp in milliseconds * @param readableDb Readable SQLite database * @return A cursor (use one of the {@link #getQueryData} methods to read * the data) */ public static Cursor fetchStatusEventList(final long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchStatusEventList()"); return readableDb.rawQuery("SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + " & " + ActivityItem.STATUS_ITEM + ") AND " + Field.TIMESTAMP + " > " + timeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); } /** * Returns a list of activity IDs already synced, in reverse chronological * order Fetches from the given timestamp. * * @param actIdList An empty list which will be filled with the result * @param timeStamp The time stamp to start the fetch * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus fetchActivitiesIds(final List<Long> actIdList, final Long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchActivitiesIds()"); Cursor cursor = null; try { long queryTimeStamp; if (timeStamp != null) { queryTimeStamp = timeStamp; } else { queryTimeStamp = 0; } cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.TIMESTAMP + " >= " + queryTimeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); while (cursor.moveToNext()) { actIdList.add(cursor.getLong(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchActivitiesIds()" + "Unable to fetch group list", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Adds a list of activities to table. The activities added will be grouped * in the database, based on local contact Id, name or contact address (see * {@link #removeContactGroup(Long, String, Long, int, * TimelineNativeTypes[], SQLiteDatabase)} * for more information on how the grouping works. * * @param actList The list of activities * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus addActivities(final List<ActivityItem> actList, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addActivities()"); SQLiteStatement statement = ContactsTable.fetchLocalFromServerIdStatement(writableDb); for (ActivityItem activity : actList) { try { writableDb.beginTransaction(); if (activity.contactList != null) { int clistSize = activity.contactList.size(); for (int i = 0; i < clistSize; i++) { final ActivityContact activityContact = activity.contactList.get(i); activityContact.mLocalContactId = ContactsTable.fetchLocalFromServerId( activityContact.mContactId, statement); if (activityContact.mLocalContactId == null) { // Just skip activities for which we don't have a corresponding contact // in the database anymore otherwise they will be shown as "Blank name". // This is the same on the web but we could use the provided name instead. continue; } int latestStatusVal = removeContactGroup( activityContact.mLocalContactId, activityContact.mName, activity.time, activity.activityFlags, null, writableDb); ContentValues cv = fillUpdateData(activity, i); cv.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); activity.localActivityId = writableDb.insertOrThrow(TABLE_NAME, null, cv); } } else { activity.localActivityId = writableDb.insertOrThrow( TABLE_NAME, null, fillUpdateData(activity, null)); } if ((activity.localActivityId != null) && (activity.localActivityId < 0)) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } if(statement != null) { statement.close(); statement = null; } return ServiceStatus.SUCCESS; } /** * Deletes all activities from the table. * * @param flag Can be a bitmap of: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * <li>NULL - to delete all activities</li> * </ul> * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteActivities(final Integer flag, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteActivities()"); try { String whereClause = null; if (flag != null) { whereClause = Field.FLAG + "&" + flag; } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } public static ServiceStatus fetchNativeIdsFromLocalContactId(List<Integer > nativeItemIdList, final long localContactId, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNativeIdsFromLocalContactId()"); Cursor cursor = null; try { cursor = readableDb.rawQuery("SELECT " + Field.NATIVE_ITEM_ID + " FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + " = " + localContactId, null); while (cursor.moveToNext()) { nativeItemIdList.add(cursor.getInt(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchNativeIdsFromLocalContactId()" + "Unable to fetch list of NativeIds from localcontactId", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Deletes specified timeline activity from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivity(final Context context, final TimelineSummaryItem timelineItem, final SQLiteDatabase writableDb, final SQLiteDatabase readableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteTimelineActivity()"); try { List<Integer > nativeItemIdList = new ArrayList<Integer>() ; //Delete from Native Database if(timelineItem.mNativeThreadId != null) { //Sms Native Database final Uri smsUri = Uri.parse("content://sms"); context.getContentResolver().delete(smsUri , "thread_id=" + timelineItem.mNativeThreadId, null); //Mms Native Database final Uri mmsUri = Uri.parse("content://mms"); context.getContentResolver().delete(mmsUri, "thread_id=" + timelineItem.mNativeThreadId, null); } else { // For CallLogs if(timelineItem.mLocalContactId != null) { fetchNativeIdsFromLocalContactId(nativeItemIdList, timelineItem.mLocalContactId, readableDb); if(nativeItemIdList.size() > 0) { //CallLog Native Database for(Integer nativeItemId : nativeItemIdList) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + nativeItemId, null); } } + } else if ((TextUtils.isEmpty(timelineItem.mContactName)) && // we have an unknown caller + (null == timelineItem.mContactId)) { + context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + + timelineItem.mNativeItemId, null); } else { if(timelineItem.mContactAddress != null) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls.NUMBER + "='" + timelineItem.mContactAddress+"'", null); } } } String whereClause = null; //Delete from People Client database if(timelineItem.mLocalContactId != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } else if(timelineItem.mContactAddress != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } + } else if ((TextUtils.isEmpty(timelineItem.mContactName)) && // we have an unknown caller + (null == timelineItem.mContactId)) { + whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + + Field.NATIVE_ITEM_ID + "=" + timelineItem.mNativeItemId; } +LogUtils.logE("-------------------------------------------------- " + whereClause); + if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } /** * Deletes all the timeline activities for a particular contact from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivities(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.deleteTimelineActivities()"); Cursor cursor = null; try { TimelineNativeTypes[] typeList = null; //For CallLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); //For SmsLog/MmsLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); //For ChatLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * * Deletes one or more timeline items for a contact for the given types. * * @param context The app context to open the transaction in. * @param latestTimelineItem The latest item from the timeline to get the belonging contact from. * @param writableDb The database to write to. * @param readableDb The database to read from. * @param typeList The list of types to delete timeline events for. * * @return Returns a success if the transaction was successful, an error otherwise. * */ private static ServiceStatus deleteTimeLineActivitiesByType(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb, TimelineNativeTypes[] typeList) { Cursor cursor = null; TimelineSummaryItem timelineItem = null; try { - cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, - latestTimelineItem.mContactName, typeList, null, readableDb); - - if(cursor != null && cursor.getCount() > 0) { - cursor.moveToFirst(); - timelineItem = getTimelineData(cursor); - if(timelineItem != null) { - return deleteTimelineActivity(context, timelineItem, writableDb, readableDb); - } - } + if ((TextUtils.isEmpty(latestTimelineItem.mContactName)) && + (latestTimelineItem.mContactId != null)) { + cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, + latestTimelineItem.mContactName, typeList, null, readableDb); + + if(cursor != null && cursor.getCount() > 0) { + cursor.moveToFirst(); + timelineItem = getTimelineData(cursor); + if(timelineItem != null) { + return deleteTimelineActivity(context, timelineItem, writableDb, readableDb); + } + } + } else { // contact id and name are null or empty, so it is an unknown contact + return deleteTimelineActivity(context, latestTimelineItem, writableDb, readableDb); + } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * Fetches timeline events grouped by local contact ID, name or contact * address. Events returned will be in reverse-chronological order. If a * native type list is provided the result will be filtered by the list. * * @param minTimeStamp Only timeline events from this date will be returned * @param nativeTypes A list of native types to filter the result, or null * to return all. * @param readableDb Readable SQLite database * @return A cursor containing the result. The * {@link #getTimelineData(Cursor)} method should be used for * reading the cursor. */ public static Cursor fetchTimelineEventList(final Long minTimeStamp, final TimelineNativeTypes[] nativeTypes, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchTimelineEventList() " + "minTimeStamp[" + minTimeStamp + "]"); try { int andVal = 1; String typesQuery = " AND "; if (nativeTypes != null) { typesQuery += DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), nativeTypes, "OR"); typesQuery += " AND "; andVal = 2; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + Field.TIMESTAMP + " > " + minTimeStamp + " AND (" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") ORDER BY " + Field.TIMESTAMP + " DESC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchLastUpdateTime() " + "Unable to fetch timeline event list", e); return null; } } /** * Adds a list of timeline events to the database. Each event is grouped by * contact and grouped by contact + native type. * * @param itemList List of timeline events * @param isCallLog true to group all activities with call logs, false to * group with messaging * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error */ public static ServiceStatus addTimelineEvents( final ArrayList<TimelineSummaryItem> itemList, final boolean isCallLog, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addTimelineEvents()"); TimelineNativeTypes[] activityTypes; if (isCallLog) { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; } else { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; } for (TimelineSummaryItem item : itemList) { try { writableDb.beginTransaction(); if (findNativeActivity(item, writableDb)) { continue; } int latestStatusVal = 0; if (!TextUtils.isEmpty(item.mContactName) || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, activityTypes, writableDb); } else { // unknown contact latestStatusVal = 1; } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM); values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } item.mLocalActivityId = writableDb.insert(TABLE_NAME, null, values); if (item.mLocalActivityId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "ERROR_DATABASE_CORRUPT - Unable to add " + "timeline list to database"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /** * The method returns the ROW_ID i.e. the INTEGER PRIMARY KEY AUTOINCREMENT * field value for the inserted row, i.e. LOCAL_ID. * * @param item TimelineSummaryItem. * @param read - TRUE if the chat message is outgoing or gets into the * timeline history view for a contact with LocalContactId. * @param writableDb Writable SQLite database. * @return LocalContactID or -1 if the row was not inserted. */ public static long addChatTimelineEvent(final TimelineSummaryItem item, final boolean read, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addChatTimelineEvent()"); try { writableDb.beginTransaction(); int latestStatusVal = 0; if (item.mContactName != null || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }, writableDb); } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); /** Chat message body. **/ values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); if (read) { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); } else { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | 0); } values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); /** Conversation ID for chat message. **/ // values.put(Field.URI.toString(), item.conversationId); // 0 for incoming, 1 for outgoing if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } final long itemId = writableDb.insert(TABLE_NAME, null, values); if (itemId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() - " + "Unable to add timeline list to database, index<0:" + itemId); return -1; } writableDb.setTransactionSuccessful(); return itemId; } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return -1; } finally { writableDb.endTransaction(); } } /** * Clears the grouping of an activity in the database, if the given activity * is newer. This is so that only the latest activity is returned for a * particular group. Each activity is associated with two groups: * <ol> * <li>All group - Grouped by contact only</li> * <li>Native group - Grouped by contact and native type (call log or * messaging)</li> * </ol> * The group to be removed is determined by the activityTypes parameter. * Grouping must also work for timeline events that are not associated with * a contact. The following fields are used to do identify a contact for the * grouping (in order of priority): * <ol> * <li>localContactId - If it not null</li> * <li>name - If this is a valid telephone number, the match will be done to * ensure that the same phone number written in different ways will be * included in the group. See {@link #fetchNameWhereClause(Long, String)} * for more information.</li> * </ol> * * @param localContactId Local contact Id or NULL if the activity is not * associated with a contact. * @param name Name of contact or contact address (telephone number, email, * etc). * @param newUpdateTime The time that the given activity has occurred * @param flag Bitmap of types including: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * </ul> * @param activityTypes A list of native types to include in the grouping. * Currently, only two groups are supported (see above). If this * parameter is null the contact will be added to the * "all group", otherwise the contact is added to the native * group. * @param writableDb Writable SQLite database * @return The latest contact status value which should be added to the * current activities grouping. */ private static int removeContactGroup(final Long localContactId, final String name, final Long newUpdateTime, final int flag, final TimelineNativeTypes[] activityTypes, final SQLiteDatabase writableDb) { String whereClause = ""; int andVal = 1; if (activityTypes != null) { whereClause = DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), activityTypes, "OR"); whereClause += " AND "; andVal = 2; } String nameWhereClause = fetchNameWhereClause(localContactId, name); if (nameWhereClause == null) { return 0; } whereClause += nameWhereClause; Long prevTime = null; Long prevLocalId = null; Integer prevLatestContactStatus = null; Cursor cursor = null; try { cursor = writableDb.rawQuery("SELECT " + Field.TIMESTAMP + "," + Field.LOCAL_ACTIVITY_ID + "," + Field.LATEST_CONTACT_STATUS + " FROM " + TABLE_NAME + " WHERE " + whereClause + " AND " + "(" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") AND (" + Field.FLAG + "&" + flag + ") ORDER BY " + Field.TIMESTAMP + " DESC", null); if (cursor.moveToFirst()) { prevTime = cursor.getLong(0); prevLocalId = cursor.getLong(1); prevLatestContactStatus = cursor.getInt(2); } } catch (SQLException e) { return 0; } finally { CloseUtils.close(cursor); } if (prevTime != null && newUpdateTime != null) { if (newUpdateTime >= prevTime) { ContentValues cv = new ContentValues(); cv.put(Field.LATEST_CONTACT_STATUS.toString(), prevLatestContactStatus & (~andVal)); if (writableDb.update(TABLE_NAME, cv, Field.LOCAL_ACTIVITY_ID + "=" + prevLocalId, null) <= 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "Unable to update timeline as the latest"); return 0; } return andVal; } else { return 0; } } return andVal; } /** * Checks if an activity exists in the database. * * @param item The native SMS item to check against our client activities DB table. * * @return true if the activity was found, false otherwise * */ private static boolean findNativeActivity(TimelineSummaryItem item, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.findNativeActivity()"); Cursor cursor = null; boolean result = false; try { final String[] args = { Integer.toString(item.mNativeItemId), Integer.toString(item.mNativeItemType), Long.toString(item.mTimestamp) }; cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_ID + "=? AND " + Field.NATIVE_ITEM_TYPE + "=?" + " AND " + Field.TIMESTAMP + "=?", args); if (cursor.moveToFirst()) { result = true; } } finally { CloseUtils.close(cursor); } return result; } /** * Returns a string which can be added to the where clause in an SQL query * on the activities table, to filter the result for a specific contact or * name. The clause will prioritise in the following way: * <ol> * <li>Use localContactId - If it not null</li> * <li>Use name - If this is a valid telephone number, the match will be * done to ensure that the same phone number written in different ways will * be included in the group. * </ol> * * @param localContactId The local contact ID, or null if the contact does * not exist in the People database. * @param name A string containing the name, or a telephone number/email * identifying the contact. * @return The where clause string */ private static String fetchNameWhereClause(final Long localContactId, final String name) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNameWhereClause()"); if (localContactId != null) { return Field.LOCAL_CONTACT_ID + "=" + localContactId; } if (name == null) { return "1=1"; // we need to return something that evaluates to true as this method is called after a SQL AND-operator } final String searchName = DatabaseUtils.sqlEscapeString(name); if (PhoneNumberUtils.isWellFormedSmsAddress(name)) { return "(PHONE_NUMBERS_EQUAL(" + Field.CONTACT_NAME + "," + searchName + ") OR "+ Field.CONTACT_NAME + "=" + searchName+")"; } else { return Field.CONTACT_NAME + "=" + searchName; } } /** * Returns the timeline summary data from the current location of the given * cursor. The cursor can be obtained using * {@link #fetchTimelineEventList(Long, TimelineNativeTypes[], * SQLiteDatabase)} or * {@link #fetchTimelineEventsForContact(Long, Long, String, * TimelineNativeTypes[], SQLiteDatabase)}. * * @param cursor Cursor in the required position. * @return A filled out TimelineSummaryItem object */ public static TimelineSummaryItem getTimelineData(final Cursor cursor) { DatabaseHelper.trace(false, "DatabaseHelper.getTimelineData()"); TimelineSummaryItem item = new TimelineSummaryItem(); item.mLocalActivityId = SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); item.mTimestamp = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); item.mContactName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); if (!cursor.isNull( cursor.getColumnIndex(Field.CONTACT_AVATAR_URL.toString()))) { item.mHasAvatar = true; } item.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); item.mTitle = SqlUtils.setString(cursor, Field.TITLE.toString()); item.mDescription = SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); item.mContactNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); item.mNativeItemType = SqlUtils.setInt(cursor, Field.NATIVE_ITEM_TYPE.toString(), null); item.mNativeItemId = SqlUtils.setInt(cursor, Field.NATIVE_ITEM_ID.toString(), null); item.mType = SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); item.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); item.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); item.mNativeThreadId = SqlUtils.setInt(cursor, Field.NATIVE_THREAD_ID.toString(), null); item.mContactAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); item.mIncoming = SqlUtils.setTimelineSummaryItemType(cursor, Field.INCOMING.toString()); return item; } /** * Fetches timeline events for a specific contact identified by local * contact ID, name or address. Events returned will be in * reverse-chronological order. If a native type list is provided the result * will be filtered by the list. * * @param timeStamp Only events from this time will be returned * @param localContactId The local contact ID if the contact is in the * People database, or null. * @param name The name or address of the contact (required if local contact * ID is NULL). * @param nativeTypes A list of required native types to filter the result, * or null to return all timeline events for the contact. * @param readableDb Readable SQLite database * @param networkName The name of the network the contacts belongs to * (required in order to provide appropriate chat messages * filtering) If the parameter is null messages from all networks * will be returned. The values are the * SocialNetwork.VODAFONE.toString(), * SocialNetwork.GOOGLE.toString(), or * SocialNetwork.MICROSOFT.toString() results. * @return The cursor that can be read using * {@link #getTimelineData(Cursor)}. */ public static Cursor fetchTimelineEventsForContact(final Long timeStamp, final Long localContactId, final String name, final TimelineNativeTypes[] nativeTypes, final String networkName, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "fetchTimelineEventsForContact()"); try { String typesQuery = " AND "; if (nativeTypes.length > 0) { StringBuffer typesQueryBuffer = new StringBuffer(); typesQueryBuffer.append(" AND ("); for (int i = 0; i < nativeTypes.length; i++) { final TimelineNativeTypes type = nativeTypes[i]; typesQueryBuffer.append(Field.NATIVE_ITEM_TYPE + "=" + type.ordinal()); if (i < nativeTypes.length - 1) { typesQueryBuffer.append(" OR "); } } typesQueryBuffer.append(") AND "); typesQuery = typesQueryBuffer.toString(); } diff --git a/src/com/vodafone360/people/datatypes/AuthSessionHolder.java b/src/com/vodafone360/people/datatypes/AuthSessionHolder.java index c96bb65..000c99e 100644 --- a/src/com/vodafone360/people/datatypes/AuthSessionHolder.java +++ b/src/com/vodafone360/people/datatypes/AuthSessionHolder.java @@ -1,162 +1,161 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.datatypes; import java.util.Enumeration; import java.util.Hashtable; import com.vodafone360.people.utils.LogUtils; /** * BaseDataType encapsulating People Session credentials returned as a result of * successful sign-in/sign-up. */ public class AuthSessionHolder extends BaseDataType { /** * Tags associated with AuthSessionHolder representing data items associated * with AuthSessionHolder item returned from server. */ private enum Tags { USER_ID("userid"), SESSION_SECRET("sessionsecret"), USER_NAME("username"), SESSION_ID("sessionid"); private final String tag; /** * Constructor creating Tags item for specified String. * * @param s String value for Tags item. */ private Tags(String s) { tag = s; } /** * String value associated with Tags item. * * @return String value for Tags item. */ public String tag() { return tag; } } public long userID; public String sessionSecret; public String userName; public String sessionID; /** * Find Tags item for specified String. * * @param tag String value to find in Tags items. * @return Tags item for specified String, null otherwise. */ private Tags findTag(String tag) { for (Tags tags : Tags.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } return null; } public int getType() { return AUTH_SESSION_HOLDER_TYPE; } /** {@inheritDoc} */ public String toString() { final StringBuilder sb = - new StringBuilder("Auth Session Holder: \n userID: \t "); + new StringBuilder("Auth Session Holder: \n userID: \t"); sb.append(userID); - sb.append("\n sessionSecret: "); sb.append(sessionSecret); - sb.append("\n userName: \t "); sb.append(userName); - sb.append("\n sessionID: \t"); sb.append(sessionID); + sb.append("\n userName: \t"); sb.append(userName); + sb.append("\n sessionID:\n\t"); sb.append(sessionID); return sb.toString(); } /** * Create AuthSessionHolder from Hash-table (generated from Hessian data). * * @param hash Hash-table containing AuthSessionHolder data. * @return AuthSessionHolder generated from supplied Hash-table. */ public AuthSessionHolder createFromHashtable(Hashtable<String, Object> hash) { Enumeration<String> e = hash.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); Object value = hash.get(key); Tags tag = findTag(key); if (null != tag) { setValue(tag, value); } else { LogUtils.logE("Tag was null for key: " + key); } } return this; } /** * Sets the value of the member data item associated with the specified tag. * * @param tag Current tag. * @param val Value associated with the tag. */ private void setValue(Tags tag, Object value) { switch (tag) { case SESSION_ID: sessionID = (String)value; break; case SESSION_SECRET: sessionSecret = (String)value; break; case USER_ID: userID = ((Long)value).longValue(); break; case USER_NAME: userName = (String)value; break; default: // Do nothing. break; } } }
360/360-Engine-for-Android
f5dc7e300b0878ec9b770f7bd518320bbf17be92
Fixed a blocking bug in the ResponseQueue which leads sync to stop working.
diff --git a/src/com/vodafone360/people/service/io/ResponseQueue.java b/src/com/vodafone360/people/service/io/ResponseQueue.java index 7cbb7d5..5414d36 100644 --- a/src/com/vodafone360/people/service/io/ResponseQueue.java +++ b/src/com/vodafone360/people/service/io/ResponseQueue.java @@ -1,272 +1,276 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.LogUtils; /** * Queue of responses received from server. These may be either responses to * requests issued by the People client or unsolicited ('Push') messages. The * content of these Responses will have already been decoded by the * DecoderThread and converted to data-types understood by the People Client. */ public class ResponseQueue { /** * The list of responses held by this queue. An array-list of Responses. */ private final List<DecodedResponse> mResponses = new ArrayList<DecodedResponse>(); /** * The engine manager holding the various engines to cross check where * responses belong to. */ private EngineManager mEngMgr = null; /** * Class encapsulating a decoded response from the server A Response * contains; a request id which should match a request id from a request * issued by the People Client (responses to non-RPG requests or * non-solicited messages will not have a request id), the request data, a * list of decoded BaseDataTypes generated from the response content and an * engine id informing the framework which engine the response should be * routed to. */ public static class DecodedResponse { public static enum ResponseType { /** An unknown response in case anything went wrong. */ UNKNOWN, /** A response for a request that timed out. */ SERVER_ERROR, /** A response that timed out before it arrived from the server. */ TIMED_OUT_RESPONSE, /** Represents a push message that was pushed by the server */ PUSH_MESSAGE, /** The response type for available identities. */ GET_AVAILABLE_IDENTITIES_RESPONSE, /** The response type for my identities. */ GET_MY_IDENTITIES_RESPONSE, /** The response type for set identity capability */ SET_IDENTITY_CAPABILITY_RESPONSE, /** The response type for validate identity credentials */ VALIDATE_IDENTITY_CREDENTIALS_RESPONSE, /** The response type for get activities calls. */ GET_ACTIVITY_RESPONSE, /** The response type for get session by credentials calls. */ LOGIN_RESPONSE, /** The response type for bulkupdate contacts calls. */ BULKUPDATE_CONTACTS_RESPONSE, /** The response type for get contacts changes calls. */ GET_CONTACTCHANGES_RESPONSE, /** The response type for get get me calls. */ GETME_RESPONSE, /** The response type for get contact group relation calls. */ GET_CONTACT_GROUP_RELATIONS_RESPONSE, /** The response type for get groups calls. */ GET_GROUPS_RESPONSE, /** The response type for add contact calls. */ ADD_CONTACT_RESPONSE, /** The response type for signup user crypted calls. */ SIGNUP_RESPONSE, /** The response type for get public key calls. */ RETRIEVE_PUBLIC_KEY_RESPONSE, /** The response type for delete contacts calls. */ DELETE_CONTACT_RESPONSE, /** The response type for delete contact details calls. */ DELETE_CONTACT_DETAIL_RESPONSE, /** The response type for get presence calls. */ GET_PRESENCE_RESPONSE, /** The response type for create conversation calls. */ CREATE_CONVERSATION_RESPONSE, /** The response type for get t&cs. */ GET_T_AND_C_RESPONSE, /** The response type for get privacy statement. */ GET_PRIVACY_STATEMENT_RESPONSE, /** The response type for removing the identity. */ DELETE_IDENTITY_RESPONSE; // TODO add more types here and remove them from the BaseDataType. Having them in ONE location is better than in dozens!!! } /** The type of the response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ private int mResponseType; /** The request ID the response came in for. */ public Integer mReqId; /** The response items (e.g. identities of a getAvailableIdentities call) to store for the response. */ public List<BaseDataType> mDataTypes = new ArrayList<BaseDataType>(); /** The ID of the engine the response should be worked off in. */ public EngineId mSource; /** * Constructs a response object with request ID, the data and the engine * ID the response belongs to. * * @param reqId The corresponding request ID for the response. * @param data The data of the response. * @param source The originating engine ID. * @param responseType The response type. Values can be found in Response.ResponseType. * */ public DecodedResponse(Integer reqId, List<BaseDataType> data, EngineId source, final int responseType) { mReqId = reqId; mDataTypes = data; mSource = source; mResponseType = responseType; } /** * The response type for this response. The types are defined in Response.ResponseType. * * @return The response type of this response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ public int getResponseType() { return mResponseType; } } /** * Protected constructor to highlight the singleton nature of this class. */ protected ResponseQueue() { } /** * Gets an instance of the ResponseQueue as part of the singleton pattern. * * @return The instance of ResponseQueue. */ public static ResponseQueue getInstance() { return ResponseQueueHolder.rQueue; } /** * Use Initialization on demand holder pattern */ private static class ResponseQueueHolder { private static final ResponseQueue rQueue = new ResponseQueue(); } /** * Adds a response item to the queue. * * @param reqId The request ID to add the response for. * @param data The response data to add to the queue. * @param source The corresponding engine that fired off the request for the * response. */ public void addToResponseQueue(final DecodedResponse response) { synchronized (QueueManager.getInstance().lock) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.UNKNOWN_DATA_TYPE, response.mDataTypes); if (status == ServiceStatus.ERROR_INVALID_SESSION) { EngineManager em = EngineManager.getInstance(); if (em != null) { LogUtils.logE("Logging out the current user because of invalide session"); em.getLoginEngine().logoutAndRemoveUser(); return; } } mResponses.add(response); Request request = RequestQueue.getInstance().removeRequest(response.mReqId); if (request != null) { // we suppose the response being handled by the same engine // that issued the request with the given id response.mSource = request.mEngineId; } mEngMgr = EngineManager.getInstance(); if (mEngMgr != null) { mEngMgr.onCommsInMessage(response.mSource); } } } /** - * Retrieves the next response from the response list if there is one. + * Retrieves the next response from the response list if there is one and it is equal to the + * passed engine ID. * * @param source The originating engine id that requested this response. * @return Response The first response that matches the given engine or null * if no response was found. */ public DecodedResponse getNextResponse(EngineId source) { DecodedResponse resp = null; Iterator<DecodedResponse> iterator = mResponses.iterator(); while (iterator.hasNext()) { resp = iterator.next(); - iterator.remove(); - if ((null != resp) && (null != resp.mSource) && (resp.mSource == source)) { + if ((null != resp) && (resp.mSource == source)) { + // remove response if the source engine is equal to the response's engine + iterator.remove(); + if (source != null) { LogUtils.logV("ResponseQueue.getNextResponse() Returning a response to engine[" + source.name() + "]"); } + return resp; } else if ((null == resp) || (null == resp.mSource)) { LogUtils.logE("Either the response or its source was null. Response: " + resp); } } return null; } /** * Get number of items currently in the response queue. * * @return number of items currently in the response queue. */ private int responseCount() { return mResponses.size(); } /** * Test if we have response for the specified request id. * * @param reqId Request ID. * @return true If we have a response for this ID. */ protected synchronized boolean responseExists(int reqId) { boolean exists = false; for (int i = 0; i < responseCount(); i++) { if (mResponses.get(i).mReqId != null && mResponses.get(i).mReqId.intValue() == reqId) { exists = true; break; } } return exists; } }
360/360-Engine-for-Android
c1e34620400e2a6a89a8d1f558ce5b2d8bfa84c7
Fixed code review comment. Using an iterator now.
diff --git a/src/com/vodafone360/people/service/io/ResponseQueue.java b/src/com/vodafone360/people/service/io/ResponseQueue.java index 6870931..04ada9a 100644 --- a/src/com/vodafone360/people/service/io/ResponseQueue.java +++ b/src/com/vodafone360/people/service/io/ResponseQueue.java @@ -1,266 +1,270 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.LogUtils; /** * Queue of responses received from server. These may be either responses to * requests issued by the People client or unsolicited ('Push') messages. The * content of these Responses will have already been decoded by the * DecoderThread and converted to data-types understood by the People Client. */ public class ResponseQueue { /** * The list of responses held by this queue. An array-list of Responses. */ private final List<DecodedResponse> mResponses = new ArrayList<DecodedResponse>(); /** * The engine manager holding the various engines to cross check where * responses belong to. */ private EngineManager mEngMgr = null; /** * Class encapsulating a decoded response from the server A Response * contains; a request id which should match a request id from a request * issued by the People Client (responses to non-RPG requests or * non-solicited messages will not have a request id), the request data, a * list of decoded BaseDataTypes generated from the response content and an * engine id informing the framework which engine the response should be * routed to. */ public static class DecodedResponse { public static enum ResponseType { /** An unknown response in case anything went wrong. */ UNKNOWN, /** A response for a request that timed out. */ SERVER_ERROR, /** A response that timed out before it arrived from the server. */ TIMED_OUT_RESPONSE, /** Represents a push message that was pushed by the server */ PUSH_MESSAGE, /** The response type for available identities. */ GET_AVAILABLE_IDENTITIES_RESPONSE, /** The response type for my identities. */ GET_MY_IDENTITIES_RESPONSE, /** The response type for set identity capability */ SET_IDENTITY_CAPABILITY_RESPONSE, /** The response type for validate identity credentials */ VALIDATE_IDENTITY_CREDENTIALS_RESPONSE, /** The response type for get activities calls. */ GET_ACTIVITY_RESPONSE, /** The response type for get session by credentials calls. */ LOGIN_RESPONSE, /** The response type for bulkupdate contacts calls. */ BULKUPDATE_CONTACTS_RESPONSE, /** The response type for get contacts changes calls. */ GET_CONTACTCHANGES_RESPONSE, /** The response type for get get me calls. */ GETME_RESPONSE, /** The response type for get contact group relation calls. */ GET_CONTACT_GROUP_RELATIONS_RESPONSE, /** The response type for get groups calls. */ GET_GROUPS_RESPONSE, /** The response type for add contact calls. */ ADD_CONTACT_RESPONSE, /** The response type for signup user crypted calls. */ SIGNUP_RESPONSE, /** The response type for get public key calls. */ RETRIEVE_PUBLIC_KEY_RESPONSE, /** The response type for delete contacts calls. */ DELETE_CONTACT_RESPONSE, /** The response type for delete contact details calls. */ DELETE_CONTACT_DETAIL_RESPONSE, /** The response type for get presence calls. */ GET_PRESENCE_RESPONSE, /** The response type for create conversation calls. */ CREATE_CONVERSATION_RESPONSE, /** The response type for get t&cs. */ GET_T_AND_C_RESPONSE, /** The response type for get privacy statement. */ GET_PRIVACY_STATEMENT_RESPONSE; // TODO add more types here and remove them from the BaseDataType. Having them in ONE location is better than in dozens!!! } /** The type of the response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ private int mResponseType; /** The request ID the response came in for. */ public Integer mReqId; /** The response items (e.g. identities of a getAvailableIdentities call) to store for the response. */ public List<BaseDataType> mDataTypes = new ArrayList<BaseDataType>(); /** The ID of the engine the response should be worked off in. */ public EngineId mSource; /** * Constructs a response object with request ID, the data and the engine * ID the response belongs to. * * @param reqId The corresponding request ID for the response. * @param data The data of the response. * @param source The originating engine ID. * @param responseType The response type. Values can be found in Response.ResponseType. * */ public DecodedResponse(Integer reqId, List<BaseDataType> data, EngineId source, final int responseType) { mReqId = reqId; mDataTypes = data; mSource = source; mResponseType = responseType; } /** * The response type for this response. The types are defined in Response.ResponseType. * * @return The response type of this response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ public int getResponseType() { return mResponseType; } } /** * Protected constructor to highlight the singleton nature of this class. */ protected ResponseQueue() { } /** * Gets an instance of the ResponseQueue as part of the singleton pattern. * * @return The instance of ResponseQueue. */ public static ResponseQueue getInstance() { return ResponseQueueHolder.rQueue; } /** * Use Initialization on demand holder pattern */ private static class ResponseQueueHolder { private static final ResponseQueue rQueue = new ResponseQueue(); } /** * Adds a response item to the queue. * * @param reqId The request ID to add the response for. * @param data The response data to add to the queue. * @param source The corresponding engine that fired off the request for the * response. */ public void addToResponseQueue(final DecodedResponse response) { synchronized (QueueManager.getInstance().lock) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.UNKNOWN_DATA_TYPE, response.mDataTypes); if (status == ServiceStatus.ERROR_INVALID_SESSION) { EngineManager em = EngineManager.getInstance(); if (em != null) { LogUtils.logE("Logging out the current user because of invalide session"); em.getLoginEngine().logoutAndRemoveUser(); return; } } mResponses.add(response); Request request = RequestQueue.getInstance().removeRequest(response.mReqId); if (request != null) { // we suppose the response being handled by the same engine // that issued the request with the given id response.mSource = request.mEngineId; } mEngMgr = EngineManager.getInstance(); if (mEngMgr != null) { mEngMgr.onCommsInMessage(response.mSource); } } } /** - * Retrieves the next response in the list if there is one. + * Retrieves the next response from the response list if there is one. * * @param source The originating engine id that requested this response. * @return Response The first response that matches the given engine or null * if no response was found. */ public DecodedResponse getNextResponse(EngineId source) { DecodedResponse resp = null; - for (int i = 0; i < mResponses.size(); i++) { - resp = mResponses.remove(i); + Iterator<DecodedResponse> iterator = mResponses.iterator(); + + while (iterator.hasNext()) { + resp = iterator.next(); + iterator.remove(); if ((null != resp) && (null != resp.mSource) && (resp.mSource == source)) { if (source != null) { LogUtils.logV("ResponseQueue.getNextResponse() Returning a response to engine[" + source.name() + "]"); } return resp; } else if ((null == resp) || (null == resp.mSource)) { LogUtils.logE("Either the response or its source was null. Response: " + resp); } } return null; } /** * Get number of items currently in the response queue. * * @return number of items currently in the response queue. */ private int responseCount() { return mResponses.size(); } /** * Test if we have response for the specified request id. * * @param reqId Request ID. * @return true If we have a response for this ID. */ protected synchronized boolean responseExists(int reqId) { boolean exists = false; for (int i = 0; i < responseCount(); i++) { if (mResponses.get(i).mReqId != null && mResponses.get(i).mReqId.intValue() == reqId) { exists = true; break; } } return exists; } }
360/360-Engine-for-Android
9f05092f6e21a71a30dc65d16bd72c3ca38e71f3
PAND-1185 Application Cache changes for launching of correct tab when Remote Service not running
diff --git a/src/com/vodafone360/people/ApplicationCache.java b/src/com/vodafone360/people/ApplicationCache.java index 3d02c5b..fea55ef 100644 --- a/src/com/vodafone360/people/ApplicationCache.java +++ b/src/com/vodafone360/people/ApplicationCache.java @@ -1,648 +1,654 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import java.security.InvalidParameterException; import java.util.ArrayList; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import com.vodafone360.people.R; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.engine.contactsync.SyncStatus; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.ThirdPartyAccount; import com.vodafone360.people.utils.LoginPreferences; import com.vodafone360.people.utils.LogUtils; /** * Caches information about the current state of the application. Stores most * recent activity and caches other information such as login details, so that * the application is returned to its most recent state when brought back to the * foreground or re-entered. The cached details can be cleared if required (as * part of 'Remove user data' for example). */ public class ApplicationCache { /** Text key for Terms of Service content. **/ private final static String TERMS_OF_SERVICE = "TERMS_OF_SERVICE"; /** Text key for Terms of Service last updated time. **/ private final static String TERMS_OF_SERVICE_TIME = "TERMS_OF_SERVICE_TIME"; /** Text key for Privacy content. **/ private final static String PRIVACY = "PRIVACY"; /** Text key for Privacy last updated time. **/ private final static String PRIVACY_TIME = "PRIVACY_TIME"; /** * Refresh any cached terms of service or privacy content after 10 minutes. */ private final static long REFRESH_TIME = 10 * 60 * 1000; private static final String TRUE = "true"; private static final String FALSE = "false"; /** * Login details are stored in the preferences file so that they can be used * to pre-populate the edit fields if the user is interrupted in the middle * of login/signup */ public static final String PREFS_FILE = "NOW_PLUS"; public static final String CONTACT_DATA = "ContactData"; public static final String CONTACT_SUMMARY = "ContactSummary"; public static final String CONTACT_ID = "CONTACTID"; public static final String CONTACT_NAME = "CONTACTNAME"; public static final String CONTACT_NUMBER = "CONTACTNUMBER"; public static final String CONTACT_NETWORK = "CONTACTNETWORK"; public static final String CONTACT_MODIFIED = "ContactModified"; public static final String STARTUP_LAUNCH_PATH_KEY = "LAUNCHED_FROM"; public static final int RESULT_DELETE = -100; public static final int CONTACT_PROFILE_VIEW = 0; public static final int CONTACT_PROFILE_EDIT = 1; public static final int CONTACT_PROFILE_ADD = 2; public static final int CONTACT_PROFILE_VIEW_ME = 3; public static final String THIRD_PARTY_ACCOUNT_NAME_KEY = "ThirdPartyAccountName"; public static final String THIRD_PARTY_ACCOUNT_NETWORK_KEY = "ThirdPartyNetworkName"; public static final String THIRD_PARTY_ACCOUNT_USERNAME_KEY = "ThirdPartyAccountUsername"; public static final String THIRD_PARTY_ACCOUNT_PASSWORD_KEY = "ThirdPartyAccountPassword"; public static final String THIRD_PARTY_ACCOUNT_CAPABILITIES = "ThirdPartyAccountCapabilities"; public static final String THIRD_PARTY_ACCOUNT_ERROR_CODE = "ThirdPartyAccountErrorCode"; private final static String FACEBOOK_SUBSCRIBED = "FacebookSubscribed"; private final static String HYVES_SUBSCRIBED = "HyvesSubscribed"; public final static String PREFS_NAME = "NowPlus_Prefs"; // Check settings public final static String PREFS_CHECK_FREQUENCY = "checkFrequency"; // Upgrade version - these values are deleted when the latest version is not // new public final static String PREFS_LAST_DIALOG_DATE = "lastDialogDate"; public final static String PREFS_LAST_CHECKED_DATE = "lastCheckedDate"; public final static String PREFS_UPGRADE_LATEST_VERSION = "upgradeLatestVersion"; public final static String PREFS_UPGRADE_URL = "upgradeUrl"; public final static String PREFS_UPGRADE_TEXT = "upgradeText"; + + /** + * Text key to indicate if the intent from StartTabsActivity needs to be + * retained. + */ + public final static String RETAIN_INTENT = "RetainIntent"; public static String sWidgetProviderClassName = null; public static String sIsNewMessage = "isNewMessage"; // Frequency setting descriptions and defaults public final static long[] FREQUENCY_SETTING_LONG = { -1, // Off 7 * 24 * 60 * 60 * 1000, // Weekly 24 * 60 * 60 * 1000, // Daily 6 * 60 * 60 * 1000, // Every 6 hours 1 * 60 * 60 * 1000, // Hourly 10 * 60 * 1000 // Every 10 minutes }; /** In memory cache of the current contacts sync status. **/ private SyncStatus mSyncStatus = null; // Cached login flags private boolean mFirstTimeLogin = true; private boolean mScanThirdPartyAccounts = true; private boolean mAcceptedTermsAndConditions = false; private int mIdentityBeingProcessed = -1; private ArrayList<ThirdPartyAccount> mThirdPartyAccountsCache; private ContactSummary mMeProfileSummary; private Contact mCurrentContact; private ContactSummary mCurrentContactSummary; private ServiceStatus mServiceStatus = ServiceStatus.ERROR_UNKNOWN; private TimelineSummaryItem mCurrentTimelineSummary; private long mCurrentContactFilter; /** Cached whether ThirdPartyAccountsActivity is opened. */ private boolean mIsAddAccountActivityOpened; /*** * GETTER Whether "add Account" activity is opened * * @return True if "add Account" activity is opened */ public boolean addAccountActivityOpened() { return mIsAddAccountActivityOpened; } /*** * SETTER Whether "add Account" activity is opened. * * @param flag if "add Account" activity is opened */ public void setAddAccountActivityOpened(final boolean flag) { mIsAddAccountActivityOpened = flag; } /** * Whether this is a first time login (on this device) for current account. * * @return True if this is the first login for current account. */ public boolean firstTimeLogin() { return mFirstTimeLogin; } /** * Set whether this is a first time login (on this device) for current * account. If we have not logged in on this device (or after 'Remove user * data') we will need to perform the first time 'full' time contact sync. * * @param aState True if this is our 1st time sync. */ public void setFirstTimeLogin(boolean state) { mFirstTimeLogin = state; } /** * Set whether application should re-scan 3rd party accounts. * * @param state true if application should re-scan 3rd party accounts. */ public void setScanThirdPartyAccounts(boolean state) { mScanThirdPartyAccounts = state; } /** * Return whether application should re-scan 3rd party accounts. * * @return true if application should re-scan 3rd party accounts. */ public boolean getScanThirdPartyAccounts() { return mScanThirdPartyAccounts; } /** * Set index of Identity currently being processed. * * @param index Index of Identity currently being processed. */ public void setIdentityBeingProcessed(int index) { mIdentityBeingProcessed = index; } /** * Return index of the Identity currently being processed. * * @return index of the Identity currently being processed. */ public int getIdentityBeingProcessed() { return mIdentityBeingProcessed; } /** * Set whether user has accepted the Terms and Conditions on sign-up. * * @param state true if user has accepted terms and conditions. */ public void setAcceptedTermsAndConditions(boolean state) { mAcceptedTermsAndConditions = state; } /** * Return whether user has accepted the Terms and Conditions on sign-up. * * @return true if user has accepted terms and conditions. */ public boolean getAcceptedTermsAndConditions() { return mAcceptedTermsAndConditions; } /** * Clear all cached data currently stored in People application. */ protected void clearCachedData(Context context) { LoginPreferences.clearPreferencesFile(context); LoginPreferences.clearCachedLoginDetails(); mFirstTimeLogin = true; mScanThirdPartyAccounts = true; mIdentityBeingProcessed = -1; mAcceptedTermsAndConditions = false; mMeProfileSummary = null; mCurrentContact = null; mCurrentContactSummary = null; mServiceStatus = ServiceStatus.ERROR_UNKNOWN; mThirdPartyAccountsCache = null; mSyncStatus = null; mIsAddAccountActivityOpened = false; } /** * Gets the ME profile object. * * @return The ME profile object. */ public ContactSummary getMeProfile() { return mMeProfileSummary; } /** * Sets the ME profile object. * * @param summary ContyactSummary for Me profile. */ public void setMeProfile(ContactSummary summary) { mMeProfileSummary = summary; } /** * Gets the contact currently being viewed in the UI. * * @return The currently view contact. */ public Contact getCurrentContact() { return mCurrentContact; } /** * Sets the contact currently being viewed in the UI. * * @param contact The currently viewed contact. */ public void setCurrentContact(Contact contact) { mCurrentContact = contact; } /** * Gets the summary information of the contact currently being viewed in the * UI. * * @return Contact summary information. */ public ContactSummary getCurrentContactSummary() { return mCurrentContactSummary; } /** * Sets the summary information of the contact currently being viewed in the * UI. * * @param contactSummary Contact summary information. */ public void setCurrentContactSummary(ContactSummary contactSummary) { mCurrentContactSummary = contactSummary; } /** * Return status of request issued to People service. * * @return status of request issued to People service. */ public ServiceStatus getServiceStatus() { return mServiceStatus; } /** * Set status of request issued to People service. * * @param status of request issued to People service. */ public void setServiceStatus(ServiceStatus status) { mServiceStatus = status; } /** * Cache list of 3rd party accounts (Identities) associated with current * login. * * @param list List of ThirdPartyAccount items retrieved from current login. */ public void storeThirdPartyAccounts(Context context, ArrayList<ThirdPartyAccount> list) { setValue(context, FACEBOOK_SUBSCRIBED, isFacebookInThirdPartyAccountList(list) + ""); setValue(context, HYVES_SUBSCRIBED, isHyvesInThirdPartyAccountList(list) + ""); mThirdPartyAccountsCache = list; } /** * Return cached list of 3rd party accounts (Identities) associated with * current login. * * @return List of ThirdPartyAccount items retrieved from current login. */ public ArrayList<ThirdPartyAccount> getThirdPartyAccounts() { return mThirdPartyAccountsCache; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Facebook account. */ private static boolean isFacebookInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("facebook")) { if (thirdPartyAccount.isVerified()) { LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook is verified"); return true; } else { LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook is not verified"); return false; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given ThirdPartyAccount contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Hyves account. */ private static boolean isHyvesInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("hyves")) { if (thirdPartyAccount.isVerified()) { LogUtils .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is verified"); return true; } else { LogUtils .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is not verified"); return false; } } } } LogUtils.logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves not found in list"); return false; } /** * Get list of IDs of Home-screen widgets. * * @param context Current context. * @return list of IDs of Home-screen widgets. */ public int[] getWidgetIdList(Context context) { if(sWidgetProviderClassName != null) { return AppWidgetManager.getInstance(context).getAppWidgetIds( new ComponentName(context, sWidgetProviderClassName)); } return null; } /*** * Set a value in the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param value Preference value. */ private static void setValue(Context context, String key, String value) { SharedPreferences.Editor editor = context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(key, value); if (!editor.commit()) { throw new NullPointerException("MainApplication.setValue() Failed to set key[" + key + "] with value[" + value + "]"); } LogUtils.logV("ApplicationCache.setValue() key [" + key + "] value [" + value + "] saved to properties file"); } /*** * Gets the current sync state, or NULL if the state has not been set in * this JVM instance. * * @return SyncStatus or NULL. */ public SyncStatus getSyncStatus() { return mSyncStatus; } /*** * Sets the current sync status. * * @param syncStatus New sync status. */ public void setSyncStatus(SyncStatus syncStatus) { mSyncStatus = syncStatus; } /*** * Get a value from the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param defaultValue Preference value. * @return */ private static String getValue(Context context, String key, String defaultValue) { return context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).getString(key, defaultValue); } /*** * Return the resource ID for the SNS Subscribed warning (e.g. * facebook/hyves/etc posting), or -1 if no warning is necessary. * * @param context Android context. * @return Resource ID for textView or -1 is warning is not required. * @throws InvalidParameterException when context is NULL. */ public static int getSnsSubscribedWarningId(Context context) { if (context == null) { throw new InvalidParameterException("ApplicationCache.getSnsSubscribedWarningId() " + "context cannot be NULL"); } boolean facebook = getValue(context, FACEBOOK_SUBSCRIBED, "").equals("true"); boolean hyves = getValue(context, HYVES_SUBSCRIBED, "").equals("true"); if (facebook && hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves_and_facebook; } else if (facebook) { return R.string.ContactStatusListActivity_update_status_on_facebook; } else if (hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves; } else { return -1; } } public static boolean isBooleanValue(Context context, String key) { return TRUE.equals(getValue(context, key, FALSE)); } public static void setBooleanValue(Context context, String key, boolean value) { setValue(context, key, value ? TRUE : FALSE); } /** * Gets the summary information of the Timeline currently being viewed in the * UI. * * @return Timeline summary information. */ public TimelineSummaryItem getCurrentTimelineSummary() { return mCurrentTimelineSummary; } /** * Sets the summary information of the Timeline Item currently being viewed in the * UI. * * @param timelineSummary Timeline summary information. */ public void setCurrentTimelineSummary(TimelineSummaryItem timelineSummary) { mCurrentTimelineSummary = timelineSummary; } /*** * Set the Terms of Service content into the cache. * * @param value Terms of Service content. * @param context Android context. */ public static void setTermsOfService(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(TERMS_OF_SERVICE, value); editor.putLong(TERMS_OF_SERVICE_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setTermsOfService() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Set the Privacy content into the cache. * * @param value Privacy content. * @param context Android context. */ public static void setPrivacyStatemet(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(PRIVACY, value); editor.putLong(PRIVACY_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setPrivacyStatemet() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Get the Terms of Service content from the cache. Will return NULL if * there is no content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Terms of Service content */ public static String getTermsOfService(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(TERMS_OF_SERVICE_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME) { return null; } else { return sharedPreferences.getString(TERMS_OF_SERVICE, null); } } /*** * Get the Privacy content from the cache. Will return NULL if there is no * content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Privacy content */ public static String getPrivacyStatement(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(PRIVACY_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME) { return null; } else { return sharedPreferences.getString(PRIVACY, null); } } private static ServiceStatus sStatus = ServiceStatus.SUCCESS; public static void setTermsStatus(final ServiceStatus status) { sStatus = status; }
360/360-Engine-for-Android
3e15c0690bc4ee832e9f2a741ce220e88ed5fa7d
Took some measures for a crash after the first sync.
diff --git a/src/com/vodafone360/people/service/io/ResponseQueue.java b/src/com/vodafone360/people/service/io/ResponseQueue.java index 42f2ce5..6870931 100644 --- a/src/com/vodafone360/people/service/io/ResponseQueue.java +++ b/src/com/vodafone360/people/service/io/ResponseQueue.java @@ -1,265 +1,266 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.util.ArrayList; import java.util.List; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.LogUtils; /** * Queue of responses received from server. These may be either responses to * requests issued by the People client or unsolicited ('Push') messages. The * content of these Responses will have already been decoded by the * DecoderThread and converted to data-types understood by the People Client. */ public class ResponseQueue { /** * The list of responses held by this queue. An array-list of Responses. */ private final List<DecodedResponse> mResponses = new ArrayList<DecodedResponse>(); /** * The engine manager holding the various engines to cross check where * responses belong to. */ private EngineManager mEngMgr = null; /** * Class encapsulating a decoded response from the server A Response * contains; a request id which should match a request id from a request * issued by the People Client (responses to non-RPG requests or * non-solicited messages will not have a request id), the request data, a * list of decoded BaseDataTypes generated from the response content and an * engine id informing the framework which engine the response should be * routed to. */ public static class DecodedResponse { public static enum ResponseType { /** An unknown response in case anything went wrong. */ UNKNOWN, /** A response for a request that timed out. */ SERVER_ERROR, /** A response that timed out before it arrived from the server. */ TIMED_OUT_RESPONSE, /** Represents a push message that was pushed by the server */ PUSH_MESSAGE, /** The response type for available identities. */ GET_AVAILABLE_IDENTITIES_RESPONSE, /** The response type for my identities. */ GET_MY_IDENTITIES_RESPONSE, /** The response type for set identity capability */ SET_IDENTITY_CAPABILITY_RESPONSE, /** The response type for validate identity credentials */ VALIDATE_IDENTITY_CREDENTIALS_RESPONSE, /** The response type for get activities calls. */ GET_ACTIVITY_RESPONSE, /** The response type for get session by credentials calls. */ LOGIN_RESPONSE, /** The response type for bulkupdate contacts calls. */ BULKUPDATE_CONTACTS_RESPONSE, /** The response type for get contacts changes calls. */ GET_CONTACTCHANGES_RESPONSE, /** The response type for get get me calls. */ GETME_RESPONSE, /** The response type for get contact group relation calls. */ GET_CONTACT_GROUP_RELATIONS_RESPONSE, /** The response type for get groups calls. */ GET_GROUPS_RESPONSE, /** The response type for add contact calls. */ ADD_CONTACT_RESPONSE, /** The response type for signup user crypted calls. */ SIGNUP_RESPONSE, /** The response type for get public key calls. */ RETRIEVE_PUBLIC_KEY_RESPONSE, /** The response type for delete contacts calls. */ DELETE_CONTACT_RESPONSE, /** The response type for delete contact details calls. */ DELETE_CONTACT_DETAIL_RESPONSE, /** The response type for get presence calls. */ GET_PRESENCE_RESPONSE, /** The response type for create conversation calls. */ CREATE_CONVERSATION_RESPONSE, /** The response type for get t&cs. */ GET_T_AND_C_RESPONSE, /** The response type for get privacy statement. */ GET_PRIVACY_STATEMENT_RESPONSE; // TODO add more types here and remove them from the BaseDataType. Having them in ONE location is better than in dozens!!! } /** The type of the response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ private int mResponseType; /** The request ID the response came in for. */ public Integer mReqId; /** The response items (e.g. identities of a getAvailableIdentities call) to store for the response. */ public List<BaseDataType> mDataTypes = new ArrayList<BaseDataType>(); /** The ID of the engine the response should be worked off in. */ public EngineId mSource; /** * Constructs a response object with request ID, the data and the engine * ID the response belongs to. * * @param reqId The corresponding request ID for the response. * @param data The data of the response. * @param source The originating engine ID. * @param responseType The response type. Values can be found in Response.ResponseType. * */ public DecodedResponse(Integer reqId, List<BaseDataType> data, EngineId source, final int responseType) { mReqId = reqId; mDataTypes = data; mSource = source; mResponseType = responseType; } /** * The response type for this response. The types are defined in Response.ResponseType. * * @return The response type of this response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ public int getResponseType() { return mResponseType; } } /** * Protected constructor to highlight the singleton nature of this class. */ protected ResponseQueue() { } /** * Gets an instance of the ResponseQueue as part of the singleton pattern. * * @return The instance of ResponseQueue. */ public static ResponseQueue getInstance() { return ResponseQueueHolder.rQueue; } /** * Use Initialization on demand holder pattern */ private static class ResponseQueueHolder { private static final ResponseQueue rQueue = new ResponseQueue(); } /** * Adds a response item to the queue. * * @param reqId The request ID to add the response for. * @param data The response data to add to the queue. * @param source The corresponding engine that fired off the request for the * response. */ public void addToResponseQueue(final DecodedResponse response) { synchronized (QueueManager.getInstance().lock) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.UNKNOWN_DATA_TYPE, response.mDataTypes); if (status == ServiceStatus.ERROR_INVALID_SESSION) { EngineManager em = EngineManager.getInstance(); if (em != null) { LogUtils.logE("Logging out the current user because of invalide session"); em.getLoginEngine().logoutAndRemoveUser(); return; } } mResponses.add(response); Request request = RequestQueue.getInstance().removeRequest(response.mReqId); if (request != null) { // we suppose the response being handled by the same engine // that issued the request with the given id response.mSource = request.mEngineId; } mEngMgr = EngineManager.getInstance(); if (mEngMgr != null) { mEngMgr.onCommsInMessage(response.mSource); } } } /** * Retrieves the next response in the list if there is one. * * @param source The originating engine id that requested this response. * @return Response The first response that matches the given engine or null * if no response was found. */ public DecodedResponse getNextResponse(EngineId source) { DecodedResponse resp = null; for (int i = 0; i < mResponses.size(); i++) { - resp = mResponses.get(i); - if (resp.mSource == source) { - mResponses.remove(i); - + resp = mResponses.remove(i); + + if ((null != resp) && (null != resp.mSource) && (resp.mSource == source)) { if (source != null) { LogUtils.logV("ResponseQueue.getNextResponse() Returning a response to engine[" + source.name() + "]"); } return resp; + } else if ((null == resp) || (null == resp.mSource)) { + LogUtils.logE("Either the response or its source was null. Response: " + resp); } } return null; } /** * Get number of items currently in the response queue. * * @return number of items currently in the response queue. */ private int responseCount() { return mResponses.size(); } /** * Test if we have response for the specified request id. * * @param reqId Request ID. * @return true If we have a response for this ID. */ protected synchronized boolean responseExists(int reqId) { boolean exists = false; for (int i = 0; i < responseCount(); i++) { if (mResponses.get(i).mReqId != null && mResponses.get(i).mReqId.intValue() == reqId) { exists = true; break; } } return exists; } }
360/360-Engine-for-Android
0bf6a68656026895f840ad3ebd1b059e3217a02e
PAND-2061: Fix for SyncAutomatically settings.
diff --git a/src/com/vodafone360/people/MainApplication.java b/src/com/vodafone360/people/MainApplication.java index 4531aa5..ad1403b 100644 --- a/src/com/vodafone360/people/MainApplication.java +++ b/src/com/vodafone360/people/MainApplication.java @@ -1,229 +1,232 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import android.app.Application; import android.content.ContentResolver; import android.os.Handler; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.service.PersistSettings; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.interfaces.IPeopleService; import com.vodafone360.people.utils.LoginPreferences; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.WidgetUtils; /** * Application class used to create the connection to the service and cache * state between Activities. */ public class MainApplication extends Application { private IPeopleService mServiceInterface; private Handler mServiceLoadedHandler; private DatabaseHelper mDatabaseHelper; private final ApplicationCache mApplicationCache = new ApplicationCache(); /** * Called when the Application is created. */ @Override public void onCreate() { super.onCreate(); SettingsManager.loadProperties(this); mDatabaseHelper = new DatabaseHelper(this); mDatabaseHelper.start(); LoginPreferences.getCurrentLoginActivity(this); } /** * Called when the Application is exited. */ @Override public void onTerminate() { // FlurryAgent.onEndSession(this); if (mDatabaseHelper != null) { mDatabaseHelper.close(); } super.onTerminate(); } /** * Return handle to DatabaseHelper, currently provides main point of access * to People client's database tables. * * @return Handle to DatabaseHelper. */ public DatabaseHelper getDatabase() { return mDatabaseHelper; } /** * Return handle to ApplicationCache. * * @return handle to ApplicationCache. */ public ApplicationCache getCache() { return mApplicationCache; } /** * Remove all user data from People client, this includes all account * information (downloaded contacts, login credentials etc.) and all cached * settings. */ public synchronized void removeUserData() { EngineManager mEngineManager = EngineManager.getInstance(); if (mEngineManager != null) { // Resets all the engines, the call will block until every engines // have been reset. mEngineManager.resetAllEngines(); } mDatabaseHelper.removeUserData(); // Before clearing the Application cache, kick the widget update. Pref's // file contain the widget ID. WidgetUtils.kickWidgetUpdateNow(this); mApplicationCache.clearCachedData(this); } /** * Register a Handler to receive notification when the People service has * loaded. If mServiceInterface == NULL then this means that the UI is * starting before the service has loaded - in this case the UI registers to * be notified when the service is loaded using the serviceLoadedHandler. * TODO: consider any pitfalls in this situation. * * @param serviceLoadedHandler Handler that receives notification of service * being loaded. */ public synchronized void registerServiceLoadHandler(Handler serviceLoadedHandler) { if (mServiceInterface != null) { onServiceLoaded(); } else { mServiceLoadedHandler = serviceLoadedHandler; LogUtils.logI("MainApplication.registerServiceLoadHandler() mServiceInterface is NULL " + "- need to wait for service to be loaded"); } } /** * Un-register People service loading handler. */ public synchronized void unRegisterServiceLoadHandler() { mServiceLoadedHandler = null; } private void onServiceLoaded() { if (mServiceLoadedHandler != null) { mServiceLoadedHandler.sendEmptyMessage(0); } } /** * Set IPeopleService interface - this is the interface by which we * interface to People service. * * @param serviceInterface IPeopleService handle. */ public synchronized void setServiceInterface(IPeopleService serviceInterface) { if (serviceInterface == null) { LogUtils.logE("MainApplication.setServiceInterface() " + "New serviceInterface should not be NULL"); } mServiceInterface = serviceInterface; onServiceLoaded(); } /** * Return current IPeopleService interface. TODO: The case where * mServiceInterface = NULL needs to be considered. * * @return current IPeopleService interface (can be null). */ public synchronized IPeopleService getServiceInterface() { if (mServiceInterface == null) { LogUtils.logE("MainApplication.getServiceInterface() " + "mServiceInterface should not be NULL"); } return mServiceInterface; } /** * Set Internet availability - always makes Internet available, only * available in home network, allow manual connection only. This setting is * stored in People database. * * @param internetAvail Internet availability setting. + * @param forwardToSyncAdapter TRUE if the SyncAdater needs to know about the changes, FALSE otherwise * @return SerivceStatus indicating whether the Internet availability * setting has been successfully updated in the database. */ - public ServiceStatus setInternetAvail(InternetAvail internetAvail) { + public ServiceStatus setInternetAvail(InternetAvail internetAvail, boolean forwardToSyncAdapter) { + if(getInternetAvail() == internetAvail) { // Nothing to do return ServiceStatus.SUCCESS; } if(internetAvail == InternetAvail.ALWAYS_CONNECT && !NativeContactsApi.getInstance().getMasterSyncAutomatically()) { // FIXME: Perhaps an abusive use of this error code for when // Master Sync Automatically is OFF, should have a different return ServiceStatus.ERROR_NO_AUTO_CONNECT; } PersistSettings mPersistSettings = new PersistSettings(); mPersistSettings.putInternetAvail(internetAvail); ServiceStatus ss = mDatabaseHelper.setOption(mPersistSettings); // FIXME: This is a hack in order to set the system auto sync on/off depending on our data settings - NativeContactsApi.getInstance().setSyncAutomatically( - internetAvail == InternetAvail.ALWAYS_CONNECT); + if (forwardToSyncAdapter) { + NativeContactsApi.getInstance().setSyncAutomatically(internetAvail == InternetAvail.ALWAYS_CONNECT); + } synchronized (this) { if (mServiceInterface != null) { mServiceInterface.notifyDataSettingChanged(internetAvail); } else { LogUtils.logE("MainApplication.setInternetAvail() " + "mServiceInterface should not be NULL"); } } return ss; } /** * Retrieve Internet availability setting from People database. * * @return current Internet availability setting. */ public InternetAvail getInternetAvail() { return mDatabaseHelper.fetchOption(PersistSettings.Option.INTERNETAVAIL).getInternetAvail(); } } diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index 3aa4137..cc2883f 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,1275 +1,1277 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.accounts.AccountManager; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.OperationApplicationException; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.provider.ContactsContract; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.Settings; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Event; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.Website; import android.text.TextUtils; import android.util.SparseArray; import com.vodafone360.people.R; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.VCardHelper.Name; import com.vodafone360.people.datatypes.VCardHelper.Organisation; import com.vodafone360.people.datatypes.VCardHelper.PostalAddress; +import com.vodafone360.people.service.NativeAccountObjectsHolder; +import com.vodafone360.people.service.SyncAdapter; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * The implementation of the NativeContactsApi for the Android 2.X platform. */ public class NativeContactsApi2 extends NativeContactsApi { /** * Convenience Projection to fetch only a Raw Contact's ID and Native * Account Type */ private static final String[] CONTACTID_PROJECTION = new String[] { RawContacts._ID, RawContacts.ACCOUNT_TYPE }; /** * Raw ID Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_RAW_ID = 0; /** * Account Type Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_ACCOUNT_TYPE = 1; /** * Group ID Projection */ private static final String[] GROUPID_PROJECTION = new String[] { Groups._ID }; /** * Vendor specific account. Only used in 2.x API. */ private static Account sPhoneAccount = null; /** * Regular expression for a date that can be handled by the People Client at * present. Matches the following cases: N-n-n n-n-N Where: - 'n' * corresponds to one or two digits - 'N' corresponds to two or 4 digits */ private static final String COMPLETE_DATE_REGEX = "(?:^\\d{2,4}-\\d{1,2}-\\d{1,2}$|^\\d{1,2}-\\d{1,2}-\\d{2,4}$)"; /** * 'My Contacts' System group where clause */ private static final String MY_CONTACTS_GROUP_WHERE_CLAUSE = Groups.SYSTEM_ID + "=\"Contacts\""; /** * 'My Contacts' System Group Membership where in clause (Multiple 'My * Contacts' IDs) */ private static final String MY_CONTACTS_MULTI_GROUP_MEMBERSHIP = Data.MIMETYPE + "=\"" + GroupMembership.CONTENT_ITEM_TYPE + "\" AND " + Data.DATA1 + " IN ("; /** * Selection where clause for a NULL Account */ private static final String NULL_ACCOUNT_WHERE_CLAUSE = RawContacts.ACCOUNT_NAME + " IS NULL AND " + RawContacts.ACCOUNT_TYPE + " IS NULL"; /** * Selection where clause for an Organization detail. */ private static final String ORGANIZATION_DETAIL_WHERE_CLAUSE = RawContacts.Data.MIMETYPE + "=\"" + Organization.CONTENT_ITEM_TYPE + "\""; /** * The list of Uri that need to be listened to for contacts changes on * native side. */ private static final Uri[] sUri = { ContactsContract.RawContacts.CONTENT_URI, ContactsContract.Data.CONTENT_URI }; /** * Holds mapping from a NAB type (MIME) to a VCard Key */ private static final HashMap<String, Integer> sFromNabContentTypeToKeyMap; /** * Holds mapping from a VCard Key to a NAB type (MIME) */ private static final SparseArray<String> sFromKeyToNabContentTypeArray; static { sFromNabContentTypeToKeyMap = new HashMap<String, Integer>(9, 1); sFromNabContentTypeToKeyMap.put(StructuredName.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NAME); sFromNabContentTypeToKeyMap.put(Nickname.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NICKNAME); sFromNabContentTypeToKeyMap.put(Phone.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_PHONE); sFromNabContentTypeToKeyMap.put(Email.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_EMAIL); sFromNabContentTypeToKeyMap.put(StructuredPostal.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ADDRESS); sFromNabContentTypeToKeyMap .put(Organization.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ORG); sFromNabContentTypeToKeyMap.put(Website.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_URL); sFromNabContentTypeToKeyMap.put(Note.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NOTE); sFromNabContentTypeToKeyMap.put(Event.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_DATE); // sFromNabContentTypeToKeyMap.put( // Photo.CONTENT_ITEM_TYPE, ContactChange.KEY_PHOTO); sFromKeyToNabContentTypeArray = new SparseArray<String>(10); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NAME, StructuredName.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NICKNAME, Nickname.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_PHONE, Phone.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_EMAIL, Email.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ADDRESS, StructuredPostal.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ORG, Organization.CONTENT_ITEM_TYPE); // Special case: VCARD_TITLE maps to the same NAB type as sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_TITLE, Organization.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_URL, Website.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NOTE, Note.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_DATE, Event.CONTENT_ITEM_TYPE); // sFromKeyToNabContentTypeArray.append( // ContactChange.KEY_PHOTO, Photo.CONTENT_ITEM_TYPE); } /** * The observer registered by the upper layer. */ private ContactsObserver mAbstractedObserver; /** * Content values used for writing to NAB. */ private final ContentValues mValues = new ContentValues(); /** * The content observers that listens for native contacts changes. */ private final ContentObserver[] mContentObservers = new ContentObserver[sUri.length]; /** * Array of row ID in the groups table to the "My Contacts" System Group. * The reason for this being an array is because there may be multiple * "My Contacts" groups (Platform Bug!?). */ private long[] mMyContactsGroupRowIds = null; /** * Arguably another example where Organization and Title force us into extra * effort. We use this value to pass the correct detail ID when an 'add * detail' is done for one the two although the other is already present. * Make sure to reset this value for every UpdateContact operation */ private long mExistingOrganizationId = ContactChange.INVALID_ID; /** * Flag to check if we have already read a Birthday detail */ private boolean mHaveReadBirthday = false; /** * Yield value for our ContentProviderOperations. */ private boolean mYield = true; /** * Batch used for Contact Writing operations. */ private BatchOperation mBatch = new BatchOperation(); /** * Inner class for applying batches. TODO: Move to own class if batches * become supported in other areas */ private class BatchOperation { // List for storing the batch mOperations ArrayList<ContentProviderOperation> mOperations; /** * Default constructor */ public BatchOperation() { mOperations = new ArrayList<ContentProviderOperation>(); } /** * Current size of the batch * * @return Size of the batch */ public int size() { return mOperations.size(); } /** * Adds a new operation to the batch * * @param cpo The */ public void add(ContentProviderOperation cpo) { mOperations.add(cpo); } /** * Clears all operations in the batch Effectively resets the batch. */ public void clear() { mOperations.clear(); } public ContentProviderResult[] execute() { ContentProviderResult[] resultArray = null; if (mOperations.size() > 0) { // Apply the mOperations to the content provider try { resultArray = mCr.applyBatch(ContactsContract.AUTHORITY, mOperations); } catch (final OperationApplicationException e1) { LogUtils.logE("storing contact data failed", e1); } catch (final RemoteException e2) { LogUtils.logE("storing contact data failed", e2); } mOperations.clear(); } return resultArray; } } /** * Convenience interface to map the generic DATA column names to the People * profile detail column names. */ private interface PeopleProfileColumns { /** * 360 People profile MIME Type */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/com.vodafone360.people.profile"; /** * 360 People Contact's profile ID (Corresponds to Contact's Internal * Contact ID) */ public static final String DATA_PID = Data.DATA1; /** * 360 People Contact profile Summary */ public static final String DATA_SUMMARY = Data.DATA2; /** * 360 People Contact profile detail */ public static final String DATA_DETAIL = Data.DATA3; } /** * This class holds a native content observer that will be notified in case * of changes on the registered URI. */ private class NativeContentObserver extends ContentObserver { public NativeContentObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { LogUtils.logI("NativeContactsApi2.NativeContentObserver.onChange(" + selfChange + ")"); mAbstractedObserver.onChange(); } } /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { LogUtils.logI("NativeContactsApi2.registerObserver()"); if (mAbstractedObserver != null) { throw new RuntimeException( "Only one observer at a time supported... Please unregister first."); } mAbstractedObserver = observer; final ContentResolver cr = mContext.getContentResolver(); for (int i = 0; i < mContentObservers.length; i++) { mContentObservers[i] = new NativeContentObserver(); cr.registerContentObserver(sUri[i], true, mContentObservers[i]); } } /** * @see NativeContactsApi#unregisterObserver(ContactsObserver) */ @Override public void unregisterObserver() { LogUtils.logI("NativeContactsApi2.unregisterObserver()"); if (mCr != null) { mAbstractedObserver = null; for (int i = 0; i < mContentObservers.length; i++) { if (mContentObservers[i] != null) { mCr.unregisterContentObserver(mContentObservers[i]); mContentObservers[i] = null; } } } } /** * @see NativeContactsApi#initialize() */ @Override protected void initialize() { // perform here any one time initialization sPhoneAccount = getVendorSpecificAccount(); } /** * @see NativeContactsApi#getAccounts() */ @Override public Account[] getAccounts() { AccountManager accountManager = AccountManager.get(mContext); final android.accounts.Account[] accounts2xApi = accountManager.getAccounts(); Account[] accounts = null; if (accounts2xApi.length > 0) { accounts = new Account[accounts2xApi.length]; for (int i = 0; i < accounts2xApi.length; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } } return accounts; } /** * Reads vendor specific accounts from settings and through accountmanager. * Some phones with custom ui like sense have additional account that we * have to take care of. This method tryes to read them * * @return Account object if vendor specific account is found, null * otherwise */ public Account getVendorSpecificAccount() { // first read the settings String[] PROJECTION = { Settings.ACCOUNT_NAME, Settings.ACCOUNT_TYPE, Settings.UNGROUPED_VISIBLE }; // Get a cursor with all people Cursor cursor = mCr.query(Settings.CONTENT_URI, PROJECTION, null, null, null); // Got no cursor? Return with null! if (null == cursor) { return null; } try { String[] values = new String[cursor.getCount()]; for (int i = 0; i < values.length; i++) { cursor.moveToNext(); if (isVendorSpecificAccount(cursor.getString(1))) { return new Account(cursor.getString(0), cursor.getString(1)); } } } catch (Exception exc) { return null; } CursorUtils.closeCursor(cursor); // nothing found in the settings? try accountmanager Account[] accounts = getAccounts(); if (accounts == null) { return null; } for (Account account : accounts) { if (isVendorSpecificAccount(account.getType())) { return account; } } return null; } /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override public Account[] getAccountsByType(int type) { switch (type) { // people and google type lead to the same block the difference is // then handled inside in two if statements. // Otherwise we would have a lot of redundant code, case PEOPLE_ACCOUNT_TYPE: case GOOGLE_ACCOUNT_TYPE: { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts2xApi = null; // For people account set the people account type string... if (PEOPLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); } // .. and for google the same only with google string. if (GOOGLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(GOOGLE_ACCOUNT_TYPE_STRING); } final int numAccounts = accounts2xApi.length; if (numAccounts > 0) { Account[] accounts = new Account[numAccounts]; for (int i = 0; i < numAccounts; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } return accounts; } else { return null; } } case PHONE_ACCOUNT_TYPE: { if (sPhoneAccount == null) { return null; } return new Account[] { sPhoneAccount }; } default: return null; } } /** * @see NativeContactsApi#addPeopleAccount(String) */ @Override public boolean addPeopleAccount(String username) { boolean isAdded = false; try { android.accounts.Account account = new android.accounts.Account(username, PEOPLE_ACCOUNT_TYPE_STRING); AccountManager accountMan = AccountManager.get(mContext); isAdded = accountMan.addAccountExplicitly(account, null, null); if (isAdded) { if (VersionUtils.isHtcSenseDevice(mContext)) { createSettingsEntryForAccount(username); + requestSyncAdapterInitialization(account); } } } catch (Exception ex) { LogUtils.logE("People Account creation failed because of exception:\n", ex); } if (isAdded) { // Updating MyContacts Group IDs here for now because it needs to be // done one time just before first time sync. // In the future, this code may change if we modify // the way we retrieve contact IDs. fetchMyContactsGroupRowIds(); } return isAdded; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { return getPeopleAccount() != null; } /** * @see NativeContactsApi#removePeopleAccount() */ @Override public void removePeopleAccount() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); if (accounts != null && accounts.length > 0) { accountMan.removeAccount(accounts[0], null, null); } } /** * @see NativeContactsApi#getContactIds(Account) */ @Override public long[] getContactIds(Account account) { // Need to construct a where clause if (account != null) { final StringBuffer clauseBuffer = new StringBuffer(); clauseBuffer.append(RawContacts.ACCOUNT_NAME); clauseBuffer.append("=\""); clauseBuffer.append(account.getName()); clauseBuffer.append("\" AND "); clauseBuffer.append(RawContacts.ACCOUNT_TYPE); clauseBuffer.append("=\""); clauseBuffer.append(account.getType()); clauseBuffer.append('\"'); return getContactIds(clauseBuffer.toString()); } else { return getContactIds(NULL_ACCOUNT_WHERE_CLAUSE); } } /** * @see NativeContactsApi#getContact(long) */ @Override public ContactChange[] getContact(long nabContactId) { // Reset the boolean flags mHaveReadOrganization = false; mHaveReadBirthday = false; final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, nabContactId); final Uri dataUri = Uri.withAppendedPath(rawContactUri, RawContacts.Data.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(dataUri, null, null, null, null); try { if (cursor != null && cursor.getCount() > 0) { final List<ContactChange> ccList = new ArrayList<ContactChange>(); while (cursor.moveToNext()) { readDetail(cursor, ccList, nabContactId); } return ccList.toArray(new ContactChange[ccList.size()]); } } finally { CursorUtils.closeCursor(cursor); } return null; } /** * @see NativeContactsApi#addContact(Account, ContactChange[]) */ @Override public ContactChange[] addContact(Account account, ContactChange[] ccList) { // Make sure to reset all the member variables we need mYield = true; mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mValues.clear(); mBatch.clear(); mValues.put(RawContacts.ACCOUNT_TYPE, account.getType()); mValues.put(RawContacts.ACCOUNT_NAME, account.getName()); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI)).withYieldAllowed(mYield) .withValues(mValues); mBatch.add(builder.build()); // according to the calling method ccList here has at least 1 element, ccList[0] is not null final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc != null) { final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } putDetail(cc); addValuesToBatch(ContactChange.INVALID_ID); } } // Special case for the organization/title if it was flagged in the // putDetail call putOrganization(ccList); addValuesToBatch(ContactChange.INVALID_ID); // Add 360 profile detail addProfileAction(ccList[0].getInternalContactId()); // Execute the batch and Generate ID changes from it return executeNewContactBatch(ccList); } /** * @see NativeContactsApi#updateContact(ContactChange[]) */ @Override public ContactChange[] updateContact(ContactChange[] ccList) { if (ccList == null || ccList.length == 0) { LogUtils.logW("NativeContactsApi2.updateContact() nothing to update - empty ccList!"); return null; } // Make sure to reset all the member variables we need mYield = true; mBatch.clear(); mValues.clear(); mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mExistingOrganizationId = ContactChange.INVALID_ID; final long nabContactId = ccList[0].getNabContactId(); if (nabContactId == ContactChange.INVALID_ID) { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update request because of invalid NAB Contact ID. Internal Contact ID is " + ccList[0].getInternalContactId()); return null; } final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } switch (cc.getType()) { case ContactChange.TYPE_ADD_DETAIL: putDetail(cc); addValuesToBatch(nabContactId); // not a new contact break; case ContactChange.TYPE_UPDATE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { putDetail(cc); addUpdateValuesToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update to detail for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; case ContactChange.TYPE_DELETE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { addDeleteDetailToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring detail deletion for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; default: break; } } updateOrganization(ccList, nabContactId); // Execute the batch and Generate ID changes from it return executeUpdateContactBatch(ccList); } /** * @see NativeContactsApi#removeContact(long) */ @Override public void removeContact(long nabContactId) { mCr.delete(addCallerIsSyncAdapterParameter(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId)), null, null); } /** * @see NativeContactsApi#getMasterSyncAutomatically */ @Override public boolean getMasterSyncAutomatically() { - // Always true in 1.X return ContentResolver.getMasterSyncAutomatically(); } /** * @see NativeContactsApi#setSyncable(boolean) */ @Override public void setSyncable(boolean syncable) { android.accounts.Account account = getPeopleAccount(); if(account != null) { ContentResolver. setIsSyncable(account, ContactsContract.AUTHORITY, syncable ? 1 : 0); } } /** * @see NativeContactsApi#setSyncAutomatically(boolean) */ @Override public void setSyncAutomatically(boolean syncAutomatically) { android.accounts.Account account = getPeopleAccount(); if(account != null) { ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, syncAutomatically); if(syncAutomatically) { // Kick start sync ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); } else { // Cancel ongoing just in case ContentResolver.cancelSync(account, ContactsContract.AUTHORITY); } } } /** * @see NativeContactsApi#isKeySupported(int) */ @Override public boolean isKeySupported(int key) { // Only supported if in the SparseArray return sFromKeyToNabContentTypeArray.indexOfKey(key) >= 0; } /** * Inner (private) method for getting contact ids. Allows a cleaner * separation the public API method. * * @param selection The where clause for the operation * @return An array containing the Contact IDs that have been found */ private long[] getContactIds(final String selection) { // Store ids in a temporary array because of possible null values long[] tempIds = null; int idCount = 0; final Cursor cursor = mCr.query(RawContacts.CONTENT_URI, CONTACTID_PROJECTION, selection, null, null); if (cursor == null) { return null; } try { final int cursorCount = cursor.getCount(); if (cursorCount > 0) { tempIds = new long[cursorCount]; while (cursor.moveToNext()) { final long id = cursor.getLong(CONTACTID_PROJECTION_RAW_ID); final String accountType = cursor.getString(CONTACTID_PROJECTION_ACCOUNT_TYPE); // TODO: Remove hardcoding (if statement) if (TextUtils.isEmpty(accountType) || accountType.equals(NativeContactsApi.PEOPLE_ACCOUNT_TYPE_STRING) || isVendorSpecificAccount(accountType) || isContactInMyContactsGroup(id)) { tempIds[idCount] = id; idCount++; } } } } finally { CursorUtils.closeCursor(cursor); } if (idCount > 0) { // Here we copy the array to strip any eventual nulls at the end of // the tempIds array final long[] ids = new long[idCount]; System.arraycopy(tempIds, 0, ids, 0, idCount); return ids; } return null; } /** * Fetches the IDs corresponding to the "My Contacts" System Group The * reason why we return an array is because there may be multiple * "My Contacts" groups. * * @return Array containing all IDs of the "My Contacts" group or null if * none exist */ private void fetchMyContactsGroupRowIds() { final Cursor cursor = mCr.query(Groups.CONTENT_URI, GROUPID_PROJECTION, MY_CONTACTS_GROUP_WHERE_CLAUSE, null, null); if (cursor == null) { return; } try { final int count = cursor.getCount(); if (count > 0) { mMyContactsGroupRowIds = new long[count]; for (int i = 0; i < count; i++) { cursor.moveToNext(); mMyContactsGroupRowIds[i] = cursor.getLong(0); } } } finally { CursorUtils.closeCursor(cursor); } } /** * Checks if a Contact is in the "My Contacts" System Group * * @param nabContactId ID of the Contact to check * @return true if the Contact is in the Group, false if not */ private boolean isContactInMyContactsGroup(long nabContactId) { boolean belongs = false; if (mMyContactsGroupRowIds != null) { final Uri dataUri = Uri.withAppendedPath(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId), RawContacts.Data.CONTENT_DIRECTORY); // build query containing row ID values final StringBuilder sb = new StringBuilder(); sb.append(MY_CONTACTS_MULTI_GROUP_MEMBERSHIP); final int rowIdCount = mMyContactsGroupRowIds.length; for (int i = 0; i < rowIdCount; i++) { sb.append(mMyContactsGroupRowIds[i]); if (i < rowIdCount - 1) { sb.append(','); } } sb.append(')'); final Cursor cursor = mCr.query(dataUri, null, sb.toString(), null, null); try { belongs = cursor != null && cursor.getCount() > 0; } finally { CursorUtils.closeCursor(cursor); } } return belongs; } /** * Reads a Contact Detail from a Cursor into the supplied Contact Change * List. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to read Detail into * @param nabContactId NAB ID of the Contact */ private void readDetail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String mimetype = CursorUtils.getString(cursor, Data.MIMETYPE); final Integer key = sFromNabContentTypeToKeyMap.get(mimetype); if (key != null) { switch (key.intValue()) { case ContactChange.KEY_VCARD_NAME: readName(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_NICKNAME: readNickname(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_PHONE: readPhone(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_EMAIL: readEmail(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ADDRESS: readAddress(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ORG: // Only one Organization can be read (CAB limitation!) if (!mHaveReadOrganization) { readOrganization(cursor, ccList, nabContactId); } break; case ContactChange.KEY_VCARD_URL: readWebsite(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_DATE: if (!mHaveReadBirthday) { readBirthday(cursor, ccList, nabContactId); } break; default: // The default case is also a valid key final String value = CursorUtils.getString(cursor, Data.DATA1); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Data._ID); final ContactChange cc = new ContactChange(key, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } break; } } } /** * Reads an name detail as a {@link ContactChange} from the provided cursor. * For this type of detail we need to use a VCARD (semicolon separated) * value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readName(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using display name only to check if there is a valid name to read final String displayName = CursorUtils.getString(cursor, StructuredName.DISPLAY_NAME); if (!TextUtils.isEmpty(displayName)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredName._ID); // VCard Helper data type (CAB) final Name name = new Name(); // NAB: Given name -> CAB: First name name.firstname = CursorUtils.getString(cursor, StructuredName.GIVEN_NAME); // NAB: Family name -> CAB: Surname name.surname = CursorUtils.getString(cursor, StructuredName.FAMILY_NAME); // NAB: Prefix -> CAB: Title name.title = CursorUtils.getString(cursor, StructuredName.PREFIX); // NAB: Middle name -> CAB: Middle name name.midname = CursorUtils.getString(cursor, StructuredName.MIDDLE_NAME); // NAB: Suffix -> CAB: Suffixes name.suffixes = CursorUtils.getString(cursor, StructuredName.SUFFIX); // NOTE: Ignoring Phonetics (DATA7, DATA8 and DATA9)! // TODO: Need to get middle name and concatenate into value final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NAME, VCardHelper .makeName(name), ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an nickname detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readNickname(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Nickname.NAME); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Nickname._ID); /* * TODO: Decide what to do with nickname: Can only have one in VF360 * but NAB Allows more than one! */ final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NICKNAME, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an phone detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readPhone(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Phone.NUMBER); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Phone._ID); final int type = CursorUtils.getInt(cursor, Phone.TYPE); int flags = mapFromNabPhoneType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Phone.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // assuming raw value is good enough for us final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_PHONE, value, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an email detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readEmail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Email.DATA); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Email._ID); final int type = CursorUtils.getInt(cursor, Email.TYPE); int flags = mapFromNabEmailType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Email.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // assuming raw value is good enough for us final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_EMAIL, value, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an address detail as a {@link ContactChange} from the provided * cursor. For this type of detail we need to use a VCARD (semicolon * separated) value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readAddress(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using formatted address only to check if there is a valid address to // read final String formattedAddress = CursorUtils.getString(cursor, StructuredPostal.FORMATTED_ADDRESS); if (!TextUtils.isEmpty(formattedAddress)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredPostal._ID); final int type = CursorUtils.getInt(cursor, StructuredPostal.TYPE); int flags = mapFromNabAddressType(type); final boolean isPrimary = CursorUtils.getInt(cursor, StructuredPostal.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // VCard Helper data type (CAB) final PostalAddress address = new PostalAddress(); // NAB: Street -> CAB: AddressLine1 address.addressLine1 = CursorUtils.getString(cursor, StructuredPostal.STREET); // NAB: PO Box -> CAB: postOfficeBox address.postOfficeBox = CursorUtils.getString(cursor, StructuredPostal.POBOX); // NAB: Neighborhood -> CAB: AddressLine2 address.addressLine2 = CursorUtils.getString(cursor, StructuredPostal.NEIGHBORHOOD); // NAB: City -> CAB: City address.city = CursorUtils.getString(cursor, StructuredPostal.CITY); // NAB: Region -> CAB: County address.county = CursorUtils.getString(cursor, StructuredPostal.REGION); // NAB: Post code -> CAB: Post code address.postCode = CursorUtils.getString(cursor, StructuredPostal.POSTCODE); // NAB: Country -> CAB: Country address.country = CursorUtils.getString(cursor, StructuredPostal.COUNTRY); final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_ADDRESS, VCardHelper .makePostalAddress(address), flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an organization detail as a {@link ContactChange} from the provided * cursor. For this type of detail we need to use a VCARD (semicolon * separated) value. In reality two different changes may be read if a title * is also present. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readOrganization(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final int type = CursorUtils.getInt(cursor, Organization.TYPE); int flags = mapFromNabOrganizationType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Organization.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } final long nabDetailId = CursorUtils.getLong(cursor, Organization._ID); if (!mHaveReadOrganization) { // VCard Helper data type (CAB) final Organisation organization = new Organisation(); // Company organization.name = CursorUtils.getString(cursor, Organization.COMPANY); // Department final String department = CursorUtils.getString(cursor, Organization.DEPARTMENT); if (!TextUtils.isEmpty(department)) { organization.unitNames.add(department); } if ((organization.unitNames != null && organization.unitNames.size() > 0) || !TextUtils.isEmpty(organization.name)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_ORG, VCardHelper .makeOrg(organization), flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } // Title final String title = CursorUtils.getString(cursor, Organization.TITLE); if (!TextUtils.isEmpty(title)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_TITLE, title, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } } } /** * Reads an Website detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readWebsite(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String url = CursorUtils.getString(cursor, Website.URL); if (!TextUtils.isEmpty(url)) { final long nabDetailId = CursorUtils.getLong(cursor, Website._ID); final int type = CursorUtils.getInt(cursor, Website.TYPE); int flags = mapFromNabWebsiteType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Website.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_URL, url, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an Birthday detail as a {@link ContactChange} from the provided * cursor. Note that since the Android Type is the Generic "Event", it may * be the case that nothing is read if this is not actually a Birthday * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ public void readBirthday(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final int type = CursorUtils.getInt(cursor, Event.TYPE); if (type == Event.TYPE_BIRTHDAY) { final String date = CursorUtils.getString(cursor, Event.START_DATE); // Ignoring birthdays without year, day and month! // FIXME: Remove this check when/if the backend becomes able to // handle incomplete birthdays if (date != null && date.matches(COMPLETE_DATE_REGEX)) { final long nabDetailId = CursorUtils.getLong(cursor, Event._ID); final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_DATE, date, ContactChange.FLAG_BIRTHDAY); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadBirthday = true; } } } /** * Adds current values to the batch. * * @param nabContactId The existing NAB Contact ID if it is an update or an * invalid id if a new contact */ private void addValuesToBatch(long nabContactId) { // Add to batch if (mValues.size() > 0) { final boolean isNewContact = nabContactId == ContactChange.INVALID_ID; if (!isNewContact) { // Updating a Contact, need to add the ID to the Values mValues.put(Data.RAW_CONTACT_ID, nabContactId); @@ -1480,733 +1482,745 @@ public class NativeContactsApi2 extends NativeContactsApi { mValues.put(Phone.TYPE, mapToNabPhoneType(flags)); mValues.put(Phone.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(Phone.MIMETYPE, Phone.CONTENT_ITEM_TYPE); } /** * Put Email detail into the values * * @param cc {@link ContactChange} to read values from */ private void putEmail(ContactChange cc) { mValues.put(Email.DATA, cc.getValue()); final int flags = cc.getFlags(); mValues.put(Email.TYPE, mapToNabEmailType(flags)); mValues.put(Email.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(Email.MIMETYPE, Email.CONTENT_ITEM_TYPE); } /** * Put Address detail into the values * * @param cc {@link ContactChange} to read values from */ private void putAddress(ContactChange cc) { final PostalAddress address = VCardHelper.getPostalAddress(cc.getValue()); if (address == null) { // Nothing to do return; } mValues.put(StructuredPostal.STREET, address.addressLine1); mValues.put(StructuredPostal.POBOX, address.postOfficeBox); mValues.put(StructuredPostal.NEIGHBORHOOD, address.addressLine2); mValues.put(StructuredPostal.CITY, address.city); mValues.put(StructuredPostal.REGION, address.county); mValues.put(StructuredPostal.POSTCODE, address.postCode); mValues.put(StructuredPostal.COUNTRY, address.country); final int flags = cc.getFlags(); mValues.put(StructuredPostal.TYPE, mapToNabAddressType(flags)); mValues.put(StructuredPostal.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(StructuredPostal.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE); } /** * Put Website detail into the values * * @param cc {@link ContactChange} to read values from */ private void putWebsite(ContactChange cc) { mValues.put(Website.URL, cc.getValue()); final int flags = cc.getFlags(); mValues.put(Website.TYPE, mapToNabWebsiteType(flags)); mValues.put(Website.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(Website.MIMETYPE, Website.CONTENT_ITEM_TYPE); } /** * Put Note detail into the values * * @param cc {@link ContactChange} to read values from */ private void putNote(ContactChange cc) { mValues.put(Note.NOTE, cc.getValue()); mValues.put(Note.MIMETYPE, Note.CONTENT_ITEM_TYPE); } /** * Put Birthday detail into the values * * @param cc {@link ContactChange} to read values from */ private void putBirthday(ContactChange cc) { if ((cc.getFlags() & ContactChange.FLAG_BIRTHDAY) == ContactChange.FLAG_BIRTHDAY) { mValues.put(Event.START_DATE, cc.getValue()); mValues.put(Event.TYPE, Event.TYPE_BIRTHDAY); mValues.put(Event.MIMETYPE, Event.CONTENT_ITEM_TYPE); } } // PHOTO NOT USED // /** // * Do a GET request and retrieve up to maxBytes bytes // * // * @param url // * @param maxBytes // * @return // * @throws IOException // */ // public static byte[] doGetAndReturnBytes(URL url, int maxBytes) throws // IOException { // HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // conn.setRequestMethod("GET"); // InputStream istr = null; // try { // int rc = conn.getResponseCode(); // if (rc != 200) { // throw new IOException("code " + rc + " '" + conn.getResponseMessage() + // "'"); // } // istr = new BufferedInputStream(conn.getInputStream(), 512); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // copy(istr, baos, maxBytes); // return baos.toByteArray(); // } finally { // if (istr != null) { // istr.close(); // } // } // } // // /** // * Copy maxBytes from an input stream to an output stream. // * @param in // * @param out // * @param maxBytes // * @return // * @throws IOException // */ // private static int copy(InputStream in, OutputStream out, int maxBytes) // throws IOException { // byte[] buf = new byte[512]; // int bytesRead = 1; // int totalBytes = 0; // while (bytesRead > 0) { // bytesRead = in.read(buf, 0, Math.min(512, maxBytes - totalBytes)); // if (bytesRead > 0) { // out.write(buf, 0, bytesRead); // totalBytes += bytesRead; // } // } // return totalBytes; // } // // /** // * Put Photo detail into the values // * @param cc {@link ContactChange} to read values from // */ // private void putPhoto(ContactChange cc) { // try { // // File file = new File(cc.getValue()); // // InputStream is = new FileInputStream(file); // // byte[] bytes = new byte[(int) file.length()]; // // is.read(bytes); // // is.close(); // final URL url = new URL(cc.getValue()); // byte[] bytes = doGetAndReturnBytes(url, 1024 * 100); // mValues.put(Photo.PHOTO, bytes); // mValues.put(Photo.MIMETYPE, Photo.CONTENT_ITEM_TYPE); // } catch(Exception ex) { // LogUtils.logE("Unable to put Photo detail because of exception:"+ex); // } // } /** * Put Organization detail into the values * * @param cc {@link ContactChange} to read values from */ private void putOrganization(ContactChange[] ccList) { mValues.clear(); int flags = ContactChange.FLAG_NONE; if (mMarkedOrganizationIndex > -1) { final ContactChange cc = ccList[mMarkedOrganizationIndex]; flags |= cc.getFlags(); final Organisation organization = VCardHelper.getOrg(cc.getValue()); if (organization != null) { mValues.put(Organization.COMPANY, organization.name); if (organization.unitNames.size() > 0) { // Only considering one unit name (department) as that's all // we support mValues.put(Organization.DEPARTMENT, organization.unitNames.get(0)); } else { mValues.putNull(Organization.DEPARTMENT); } } } if (mMarkedTitleIndex > -1) { final ContactChange cc = ccList[mMarkedTitleIndex]; flags |= cc.getFlags(); // No need to check for empty values as there is only one mValues.put(Organization.TITLE, cc.getValue()); } if (mValues.size() > 0) { mValues.put(Organization.LABEL, (String)null); mValues.put(Organization.TYPE, mapToNabOrganizationType(flags)); mValues.put(Organization.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(Organization.MIMETYPE, Organization.CONTENT_ITEM_TYPE); } } /** * Updates the Organization detail in the context of a Contact Update * operation. The end of result of this is that the Organization may be * inserted, updated or deleted depending on the update data. For example, * if the title is deleted but there is also a company name then the * Organization is just updated. However, if there was no company name then * the detail should be deleted altogether. * * @param ccList {@link ContactChange} list where Organization and Title may * be found * @param nabContactId The NAB ID of the Contact */ private void updateOrganization(ContactChange[] ccList, long nabContactId) { if (mMarkedOrganizationIndex < 0 && mMarkedTitleIndex < 0) { // no organization or title to update - do nothing return; } // First we check if there is an existing Organization detail in NAB final Uri uri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI, nabContactId), RawContacts.Data.CONTENT_DIRECTORY); Cursor cursor = mCr.query(uri, null, ORGANIZATION_DETAIL_WHERE_CLAUSE, null, RawContacts.Data._ID); String company = null; String department = null; String title = null; int flags = ContactChange.FLAG_NONE; try { if (cursor != null && cursor.moveToNext()) { // Found an organization detail company = CursorUtils.getString(cursor, Organization.COMPANY); department = CursorUtils.getString(cursor, Organization.DEPARTMENT); title = CursorUtils.getString(cursor, Organization.TITLE); flags = mapFromNabOrganizationType(CursorUtils.getInt(cursor, Organization.TYPE)); final boolean isPrimary = CursorUtils.getInt(cursor, Organization.IS_PRIMARY) > 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } mExistingOrganizationId = CursorUtils.getLong(cursor, Organization._ID); } } finally { CursorUtils.closeCursor(cursor); cursor = null; // make it a candidate for the GC } if (mMarkedOrganizationIndex >= 0) { // Have an Organization (Company + Department) to update final ContactChange cc = ccList[mMarkedOrganizationIndex]; if (cc.getType() != ContactChange.TYPE_DELETE_DETAIL) { final String value = cc.getValue(); if (value != null) { final Organisation organization = VCardHelper.getOrg(value); company = organization.name; if (organization.unitNames.size() > 0) { department = organization.unitNames.get(0); } } flags = cc.getFlags(); } else { // Delete case company = null; department = null; } } if (mMarkedTitleIndex >= 0) { // Have a Title to update final ContactChange cc = ccList[mMarkedTitleIndex]; title = cc.getValue(); if (cc.getType() != ContactChange.TYPE_UPDATE_DETAIL) { flags = cc.getFlags(); } } if (company != null || department != null || title != null) { /* * If any of the above are present we assume a insert or update is * needed. */ mValues.clear(); mValues.put(Organization.LABEL, (String)null); mValues.put(Organization.COMPANY, company); mValues.put(Organization.DEPARTMENT, department); mValues.put(Organization.TITLE, title); mValues.put(Organization.TYPE, mapToNabOrganizationType(flags)); mValues.put(Organization.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(Organization.MIMETYPE, Organization.CONTENT_ITEM_TYPE); if (mExistingOrganizationId != ContactChange.INVALID_ID) { // update is needed addUpdateValuesToBatch(mExistingOrganizationId); } else { // insert is needed addValuesToBatch(nabContactId); // not a new contact } } else if (mExistingOrganizationId != ContactChange.INVALID_ID) { /* * Had an Organization but now all values are null, delete is in * order. */ addDeleteDetailToBatch(mExistingOrganizationId); } } /** * Executes a pending Batch Operation related to adding a new Contact. * * @param ccList The original {@link ContactChange} for the new Contact * @return {@link ContactChange} array containing new IDs (may contain some * null elements) */ private ContactChange[] executeNewContactBatch(ContactChange[] ccList) { if (mBatch.size() == 0) { // Nothing to execute return null; } final ContentProviderResult[] results = mBatch.execute(); if (results == null || results.length == 0) { LogUtils.logE("NativeContactsApi2.executeNewContactBatch()" + "Batch execution result is null or empty!"); return null; } // -1 because we skip the Profile detail final int resultsSize = results.length - 1; if (results[0].uri == null) { // Contact was not created LogUtils.logE("NativeContactsApi2.executeNewContactBatch()" + "NAB Contact ID not found for created contact"); return null; } final long nabContactId = ContentUris.parseId(results[0].uri); final ContactChange[] idChangeList = new ContactChange[ccList.length + 1]; // Update NAB Contact ID CC idChangeList[0] = ContactChange.createIdsChange(ccList[0], ContactChange.TYPE_UPDATE_NAB_CONTACT_ID); idChangeList[0].setNabContactId(nabContactId); // Start after contact id in the results index int resultsIndex = 1, ccListIndex = 0; final boolean haveOrganization = mMarkedOrganizationIndex != -1 || mMarkedTitleIndex != -1; while (resultsIndex < resultsSize) { if (ccListIndex == mMarkedOrganizationIndex || ccListIndex == mMarkedTitleIndex) { ccListIndex++; continue; } if (results[resultsIndex].uri == null) { throw new RuntimeException("NativeContactsApi2.executeNewContactBatch()" + "Unexpected null URI for NAB Contact:" + nabContactId); } if (resultsIndex == resultsSize - 1 && haveOrganization) { // for readability we leave Organization/Title for outside the // loop break; } final ContactChange cc = ccList[ccListIndex]; // Check if the key is one that is supported in the 2.X NAB if (sFromKeyToNabContentTypeArray.indexOfKey(cc.getKey()) >= 0) { final long nabDetailId = ContentUris.parseId(results[resultsIndex].uri); final ContactChange idChange = ContactChange.createIdsChange(ccList[ccListIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChange.setNabContactId(nabContactId); idChange.setNabDetailId(nabDetailId); idChangeList[ccListIndex + 1] = idChange; resultsIndex++; } ccListIndex++; } if (haveOrganization) { final long nabDetailId = ContentUris.parseId(results[resultsIndex].uri); if (mMarkedOrganizationIndex > -1) { final ContactChange idChange = ContactChange.createIdsChange( ccList[mMarkedOrganizationIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChange.setNabContactId(nabContactId); idChange.setNabDetailId(nabDetailId); idChangeList[mMarkedOrganizationIndex + 1] = idChange; } if (mMarkedTitleIndex > -1) { final ContactChange idChange = ContactChange.createIdsChange( ccList[mMarkedTitleIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChange.setNabContactId(nabContactId); idChange.setNabDetailId(nabDetailId); idChangeList[mMarkedTitleIndex + 1] = idChange; } } return idChangeList; } /** * Executes a pending Batch Operation related to updating a Contact. * * @param ccList The original {@link ContactChange} for the Contact update * @return {@link ContactChange} array containing new IDs (may contain some * null elements) */ private ContactChange[] executeUpdateContactBatch(ContactChange[] ccList) { if (mBatch.size() == 0) { // Nothing to execute return null; } final ContentProviderResult[] results = mBatch.execute(); final int resultsSize = results.length; if (results == null || resultsSize == 0) { // Assuming this can happen in case of no added details return null; } // Start after contact id in the results index int resultsIndex = 0, ccListIndex = 0; final boolean haveOrganization = mMarkedOrganizationIndex != -1 || mMarkedTitleIndex != -1; final ContactChange[] idChangeList = new ContactChange[ccList.length]; while (resultsIndex < resultsSize) { if (ccListIndex == mMarkedOrganizationIndex || ccListIndex == mMarkedTitleIndex) { ccListIndex++; continue; } if (results[resultsIndex].uri == null) { // Assuming detail was updated or deleted (not added) resultsIndex++; continue; } if (resultsIndex == resultsSize - 1 && haveOrganization) { // for readability we leave Organization/Title for outside the // loop break; } final ContactChange cc = ccList[ccListIndex]; // Check if the key is one that is supported in the 2.X NAB if (sFromKeyToNabContentTypeArray.indexOfKey(cc.getKey()) >= 0 && cc.getType() == ContactChange.TYPE_ADD_DETAIL) { final long nabDetailId = ContentUris.parseId(results[resultsIndex].uri); final ContactChange idChange = ContactChange.createIdsChange(ccList[ccListIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChange.setNabDetailId(nabDetailId); idChangeList[ccListIndex] = idChange; resultsIndex++; } ccListIndex++; } if (haveOrganization) { long nabDetailId = ContactChange.INVALID_ID; if (mExistingOrganizationId != nabDetailId) { nabDetailId = mExistingOrganizationId; } else if (results[resultsIndex].uri != null) { nabDetailId = ContentUris.parseId(results[resultsIndex].uri); } else { throw new RuntimeException("NativeContactsApi2.executeUpdateContactBatch()" + "Unexpected null Organization URI for NAB Contact:" + ccList[0].getNabContactId()); } if (mMarkedOrganizationIndex > -1 && ccList[mMarkedOrganizationIndex].getType() == ContactChange.TYPE_ADD_DETAIL) { final ContactChange idChange = ContactChange.createIdsChange( ccList[mMarkedOrganizationIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChange.setNabDetailId(nabDetailId); idChangeList[mMarkedOrganizationIndex] = idChange; } if (mMarkedTitleIndex > -1 && ccList[mMarkedTitleIndex].getType() == ContactChange.TYPE_ADD_DETAIL) { final ContactChange idChange = ContactChange.createIdsChange( ccList[mMarkedTitleIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChange.setNabDetailId(nabDetailId); idChangeList[mMarkedTitleIndex] = idChange; } } return idChangeList; } /** * Static utility method that adds the Sync Adapter flag to the provided URI * * @param uri URI to add the flag to * @return URI with the flag */ private static Uri addCallerIsSyncAdapterParameter(Uri uri) { return uri.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true") .build(); } /** * Utility method used to create an entry in the ContactsContract.Settings * database table for the 360 People Account. This method only exists to * compensate for HTC devices such as Legend or Desire that don't create the * entry automatically like the Nexus One. * * @param username The username of the 360 People Account. */ private void createSettingsEntryForAccount(String username) { mValues.clear(); mValues.put(Settings.ACCOUNT_NAME, username); mValues.put(Settings.ACCOUNT_TYPE, PEOPLE_ACCOUNT_TYPE_STRING); mValues.put(Settings.UNGROUPED_VISIBLE, true); mValues.put(Settings.SHOULD_SYNC, false); // TODO Unsupported for now mCr.insert(Settings.CONTENT_URI, mValues); } + + /** + * Requests the SyncAdapter to perform a sync with initialization sequence. + * + * @param account the account to be initialized + */ + private void requestSyncAdapterInitialization(android.accounts.Account account) { + + final Bundle bundle = new Bundle(); + bundle.putBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, true); + ContentResolver.requestSync(account, ContactsContract.AUTHORITY, bundle); + } /** * Maps a phone type from the native value to the {@link ContactChange} * flags. * * @param nabType Given native phone number type * @return {@link ContactChange} flags */ private static int mapFromNabPhoneType(int nabType) { switch (nabType) { case Phone.TYPE_HOME: return ContactChange.FLAG_HOME; case Phone.TYPE_MOBILE: return ContactChange.FLAG_CELL; case Phone.TYPE_WORK: return ContactChange.FLAG_WORK; case Phone.TYPE_WORK_MOBILE: return ContactChange.FLAGS_WORK_CELL; case Phone.TYPE_FAX_WORK: return ContactChange.FLAGS_WORK_FAX; case Phone.TYPE_FAX_HOME: return ContactChange.FLAGS_HOME_FAX; case Phone.TYPE_OTHER_FAX: return ContactChange.FLAG_FAX; } return ContactChange.FLAG_NONE; } /** * Maps {@link ContactChange} flags into the native phone type. * * @param flags {@link ContactChange} flags * @return Native phone type */ private static int mapToNabPhoneType(int flags) { if ((flags & ContactChange.FLAGS_WORK_CELL) == ContactChange.FLAGS_WORK_CELL) { return Phone.TYPE_WORK_MOBILE; } if ((flags & ContactChange.FLAGS_HOME_FAX) == ContactChange.FLAGS_HOME_FAX) { return Phone.TYPE_FAX_HOME; } if ((flags & ContactChange.FLAGS_WORK_FAX) == ContactChange.FLAGS_WORK_FAX) { return Phone.TYPE_FAX_WORK; } if ((flags & ContactChange.FLAG_HOME) == ContactChange.FLAG_HOME) { return Phone.TYPE_HOME; } if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return Phone.TYPE_WORK; } if ((flags & ContactChange.FLAG_CELL) == ContactChange.FLAG_CELL) { return Phone.TYPE_MOBILE; } if ((flags & ContactChange.FLAG_FAX) == ContactChange.FLAG_FAX) { return Phone.TYPE_OTHER_FAX; } return Phone.TYPE_OTHER; } /** * Maps a email type from the native value into the {@link ContactChange} * flags * * @param nabType Native email type * @return {@link ContactChange} flags */ private static int mapFromNabEmailType(int nabType) { switch (nabType) { case Email.TYPE_HOME: return ContactChange.FLAG_HOME; case Email.TYPE_MOBILE: return ContactChange.FLAG_CELL; case Email.TYPE_WORK: return ContactChange.FLAG_WORK; } return ContactChange.FLAG_NONE; } /** * Maps {@link ContactChange} flags into the native email type. * * @param flags {@link ContactChange} flags * @return Native email type */ private static int mapToNabEmailType(int flags) { if ((flags & ContactChange.FLAG_HOME) == ContactChange.FLAG_HOME) { return Email.TYPE_HOME; } if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return Email.TYPE_WORK; } return Email.TYPE_OTHER; } /** * Maps a address type from the native value into the {@link ContactChange} * flags * * @param nabType Native email type * @return {@link ContactChange} flags */ private static int mapFromNabAddressType(int nabType) { switch (nabType) { case StructuredPostal.TYPE_HOME: return ContactChange.FLAG_HOME; case StructuredPostal.TYPE_WORK: return ContactChange.FLAG_WORK; } return ContactChange.FLAG_NONE; } /** * Maps {@link ContactChange} flags into the native address type. * * @param flags {@link ContactChange} flags * @return Native address type */ private static int mapToNabAddressType(int flags) { if ((flags & ContactChange.FLAG_HOME) == ContactChange.FLAG_HOME) { return StructuredPostal.TYPE_HOME; } if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return StructuredPostal.TYPE_WORK; } return StructuredPostal.TYPE_OTHER; } /** * Maps a organization type from the native value into the * {@link ContactChange} flags * * @param nabType Given native organization type * @return {@link ContactChange} flags */ private static int mapFromNabOrganizationType(int nabType) { if (nabType == Organization.TYPE_WORK) { return ContactChange.FLAG_WORK; } return ContactChange.FLAG_NONE; } /** * Maps {@link ContactChange} flags into the native organization type. * * @param flags {@link ContactChange} flags * @return Native Organization type */ private static int mapToNabOrganizationType(int flags) { if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return Organization.TYPE_WORK; } return Organization.TYPE_OTHER; } /** * Maps a Website type from the native value into the {@link ContactChange} * flags * * @param nabType Native email type * @return {@link ContactChange} flags */ private static int mapFromNabWebsiteType(int nabType) { switch (nabType) { case Website.TYPE_HOME: return ContactChange.FLAG_HOME; case Website.TYPE_WORK: return ContactChange.FLAG_WORK; } return ContactChange.FLAG_NONE; } /** * Maps {@link ContactChange} flags into the native Website type. * * @param flags {@link ContactChange} flags * @return Native Website type */ private static int mapToNabWebsiteType(int flags) { if ((flags & ContactChange.FLAG_HOME) == ContactChange.FLAG_HOME) { return Website.TYPE_HOME; } if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return Website.TYPE_WORK; } return Website.TYPE_OTHER; } /** * Gets the first People Account found on the device or * null if none is found * @return The Android People account found or null */ public android.accounts.Account getPeopleAccount() { android.accounts.Account[] accounts = AccountManager.get(mContext).getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); if(accounts != null && accounts.length > 0) { return accounts[0]; } return null; } } diff --git a/src/com/vodafone360/people/service/SyncAdapter.java b/src/com/vodafone360/people/service/SyncAdapter.java index 9bdf5b1..2845994 100644 --- a/src/com/vodafone360/people/service/SyncAdapter.java +++ b/src/com/vodafone360/people/service/SyncAdapter.java @@ -1,281 +1,280 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import android.accounts.Account; import android.content.AbstractThreadedSyncAdapter; import android.content.BroadcastReceiver; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SyncResult; import android.content.SyncStatusObserver; import android.os.Bundle; import android.os.Handler; import android.provider.ContactsContract; import com.vodafone360.people.MainApplication; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.engine.contactsync.NativeContactsApi2; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; import com.vodafone360.people.service.PersistSettings.InternetAvail; /** * SyncAdapter implementation which basically just ties in with * the old Contacts Sync Engine code for the moment and waits for the sync to be finished. * In the future we may want to improve this, particularly if the sync * is actually be done in this thread which would also enable disable sync altogether. */ public class SyncAdapter extends AbstractThreadedSyncAdapter implements IContactSyncObserver { // TODO: RE-ENABLE SYNC VIA SYSTEM // /** // * Direct access to Sync Engine stored for convenience // */ // private final ContactSyncEngine mSyncEngine = EngineManager.getInstance().getContactSyncEngine(); // // /** // * Boolean used to remember if we have requested a sync. // * Useful to ignore events // */ // private boolean mPerformSyncRequested = false; // /** * Delay when checking our Sync Setting when there is a authority auto-sync setting change. * This waiting time is necessary because in case it is our sync adapter authority setting * that changes we cannot query in the callback because the value is not yet changed! */ private static final int SYNC_SETTING_CHECK_DELAY = 500; /** * Same as ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS * The reason we have this is just because the constant is not publicly defined before 2.2. */ private static final int SYNC_OBSERVER_TYPE_SETTINGS = 1; /** * Application object instance */ private final MainApplication mApplication; /** * Broadcast receiver used to listen for changes in the Master Auto Sync setting * intent: com.android.sync.SYNC_CONN_STATUS_CHANGED */ private final BroadcastReceiver mAutoSyncChangeBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { - setConnectionSettingForAutoSyncSetting(); + actOnAutoSyncSettings(); } }; /** * Observer for the global sync status setting. * There is no known way to only observe our sync adapter's setting. */ private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() { @Override public void onStatusChanged(int which) { mHandler.postDelayed(mRunnable, SYNC_SETTING_CHECK_DELAY); } }; /** * Handler used to post to a runnable in order to wait * for a short time before checking the sync adapter * authority sync setting after a global change occurs. */ private final Handler mHandler = new Handler(); /** * Cached Account we use to query this Sync Adapter instance's Auto-sync setting. */ private Account mAccount; /** * Runnable used to post to a runnable in order to wait * for a short time before checking the sync adapter * authority sync setting after a global change occurs. * The reason we use this kind of mechanism is because: * a) There is an intent(com.android.sync.SYNC_CONN_STATUS_CHANGED) * we can listen to for the Master Auto-sync but, * b) The authority auto-sync observer pattern using ContentResolver * listens to EVERY sync adapter setting on the device AND * when the callback is received the value is not yet changed so querying for it is useless. */ private final Runnable mRunnable = new Runnable() { @Override public void run() { - setConnectionSettingForAutoSyncSetting(); + actOnAutoSyncSettings(); } }; public SyncAdapter(Context context, MainApplication application) { // No automatic initialization (false) super(context, false); mApplication = application; context.registerReceiver(mAutoSyncChangeBroadcastReceiver, new IntentFilter( "com.android.sync.SYNC_CONN_STATUS_CHANGED")); ContentResolver.addStatusChangeListener( SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver); // Necessary in case of Application udpate forceSyncSettingsInCaseOfAppUpdate(); // Register for sync event callbacks // TODO: RE-ENABLE SYNC VIA SYSTEM // mSyncEngine.addEventCallback(this); } /** * {@inheritDoc} */ @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { if(extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false)) { initializeSyncAdapter(account, authority); return; } - setConnectionSettingForAutoSyncSetting(); + actOnAutoSyncSettings(); // TODO: RE-ENABLE SYNC VIA SYSTEM // try { // synchronized(this) { // mPerformSyncRequested = true; // if(!mSyncEngine.isSyncing()) { // mSyncEngine.startFullSync(); // } // // while(mSyncEngine.isSyncing()) { // wait(POOLING_WAIT_INTERVAL); // } // mPerformSyncRequested = false; // } // } catch (InterruptedException e) { // e.printStackTrace(); // } } /** * @see IContactSyncObserver#onContactSyncStateChange(Mode, State, State) */ @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { // TODO: RE-ENABLE SYNC VIA SYSTEM // synchronized(this) { // /* // * This check is done so that we can also update the native UI // * when the client devices to sync on it own // */ // if(!mPerformSyncRequested && // mode != Mode.NONE) { // mPerformSyncRequested = true; // Account account = new Account( // LoginPreferences.getUsername(), // NativeContactsApi2.PEOPLE_ACCOUNT_TYPE); // ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); // } // } } /** * @see IContactSyncObserver#onProgressEvent(State, int) */ @Override public void onProgressEvent(State currentState, int percent) { // Nothing to do } /** * @see IContactSyncObserver#onSyncComplete(ServiceStatus) */ @Override public void onSyncComplete(ServiceStatus status) { // Nothing to do } /** * Initializes Sync settings for this Sync Adapter * @param account The account associated with the initialization * @param authority The authority of the content */ private void initializeSyncAdapter(Account account, String authority) { mAccount = account; // caching ContentResolver.setIsSyncable(account, authority, 1); ContentResolver.setSyncAutomatically(account, authority, true); } /** * Checks if this Sync Adapter is allowed to Sync Automatically * Basically just checking if the Master and its own Auto-sync are on. * The Master Auto-sync takes precedence over the authority Auto-sync. * @return true if the settings are enabled, false otherwise */ private boolean canSyncAutomatically() { - if(!ContentResolver.getMasterSyncAutomatically()) { - return false; - } - return mAccount != null && - ContentResolver.getSyncAutomatically(mAccount, ContactsContract.AUTHORITY); + return ContentResolver.getMasterSyncAutomatically() + && mAccount != null + && ContentResolver.getSyncAutomatically(mAccount, ContactsContract.AUTHORITY); } /** - * Sets the application data connection setting depending on the Auto-Sync Setting. - * If Auto-sync is enabled then connection is to online ("always connect") + * Sets the application data connection setting depending on whether or not + * the Sync Adapter is allowed to Sync Automatically. + * If Automatic Sync is enabled then connection is to online ("always connect") * Otherwise connection is set to offline ("manual connect") */ - private synchronized void setConnectionSettingForAutoSyncSetting() { + private synchronized void actOnAutoSyncSettings() { if(canSyncAutomatically()) { // Enable data connection - mApplication.setInternetAvail(InternetAvail.ALWAYS_CONNECT); + mApplication.setInternetAvail(InternetAvail.ALWAYS_CONNECT, false); } else { // Disable data connection - mApplication.setInternetAvail(InternetAvail.MANUAL_CONNECT); + mApplication.setInternetAvail(InternetAvail.MANUAL_CONNECT, false); } } - + /** * This method is essentially needed to force the sync settings * to a consistent state in case of an Application Update. * This is because old versions of the client do not set * the sync adapter to syncable for the contacts authority. */ private void forceSyncSettingsInCaseOfAppUpdate() { NativeContactsApi2 nabApi = (NativeContactsApi2) NativeContactsApi.getInstance(); nabApi.setSyncable(true); mAccount = nabApi.getPeopleAccount(); nabApi.setSyncAutomatically( mApplication.getInternetAvail() == InternetAvail.ALWAYS_CONNECT); } }
360/360-Engine-for-Android
e55264cbeb552ffec2b09cf6b30bb11af4ad85bb
Intial commit for PAND-2018
diff --git a/src/com/vodafone360/people/datatypes/BaseDataType.java b/src/com/vodafone360/people/datatypes/BaseDataType.java index 343c7d9..a3873ab 100644 --- a/src/com/vodafone360/people/datatypes/BaseDataType.java +++ b/src/com/vodafone360/people/datatypes/BaseDataType.java @@ -1,140 +1,144 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.datatypes; /** * BaseDataType - all specific data types derive from this. */ abstract public class BaseDataType { /** * Get the data type * @return The data-type. */ abstract public int getType(); /** * Unknown data type */ public static final int UNKNOWN_DATA_TYPE = 0; /** * Activity Contact data type */ public static final int ACTIVITY_CONTACT_DATA_TYPE = 1; /** * Activity item data type */ public static final int ACTIVITY_ITEM_DATA_TYPE = 2; /** * Auth Session Holder data type */ public static final int AUTH_SESSION_HOLDER_TYPE = 3; /** * Chat Msg data type */ public static final int CHAT_MSG_DATA_TYPE = 4; /** * Contact data type */ public static final int CONTACT_DATA_TYPE = 5; /** * Contact Changes data type */ public static final int CONTACT_CHANGES_DATA_TYPE = 6; /** * Contact Detail data type */ public static final int CONTACT_DETAIL_DATA_TYPE = 7; /** * Contact Detail Deletion data type */ public static final int CONTACT_DETAIL_DELETION_DATA_TYPE = 8; /** * Contact List Reponse data type */ public static final int CONTACT_LIST_RESPONSE_DATA_TYPE = 9; /** * Conversation data type */ public static final int CONVERSATION_DATA_TYPE = 10; /** * External Response Object data type */ public static final int EXTERNAL_RESPONSE_OBJECT_DATA_TYPE = 11; /** * Group Item data type */ public static final int GROUP_ITEM_DATA_TYPE = 12; /** * My Identity data type */ public static final int MY_IDENTITY_DATA_TYPE = 13; /** * Available Identity data type */ public static final int AVAILABLE_IDENTITY_DATA_TYPE = 14; /** * Identity Capability data type */ public static final int IDENTITY_CAPABILITY_DATA_TYPE = 15; /** * Item List data type */ public static final int ITEM_LIST_DATA_TYPE = 16; /** * Presence List data type */ public static final int PRESENCE_LIST_DATA_TYPE = 17; /** * Public Key Details data type */ public static final int PUBLIC_KEY_DETAILS_DATA_TYPE = 18; /** * Push Event data type */ public static final int PUSH_EVENT_DATA_TYPE = 19; /** * Server Error data type */ public static final int SERVER_ERROR_DATA_TYPE = 20; /** * Simple Text data type */ public static final int SIMPLE_TEXT_DATA_TYPE = 21; /** * Status Msg data type */ public static final int STATUS_MSG_DATA_TYPE = 22; /** * User Profile data type */ public static final int USER_PROFILE_DATA_TYPE = 23; /** * System Notification data type */ public static final int SYSTEM_NOTIFICATION_DATA_TYPE = 24; - + /** + * Identity Removal Data type. + */ + public static final int IDENTITY_DELETION_DATA_TYPE = 25; + } diff --git a/src/com/vodafone360/people/datatypes/IdentityDeletion.java b/src/com/vodafone360/people/datatypes/IdentityDeletion.java new file mode 100644 index 0000000..6a00890 --- /dev/null +++ b/src/com/vodafone360/people/datatypes/IdentityDeletion.java @@ -0,0 +1,152 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the Common Development + * and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at + * src/com/vodafone360/people/VODAFONE.LICENSE.txt or + * http://github.com/360/360-Engine-for-Android + * See the License for the specific language governing permissions and + * limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each file and + * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. + * If applicable, add the following below this CDDL HEADER, with the fields + * enclosed by brackets "[]" replaced with your own identifying information: + * Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + * + * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. + * Use is subject to license terms. + */ + +package com.vodafone360.people.datatypes; + +import java.util.Enumeration; +import java.util.Hashtable; + +import android.os.Parcel; +import android.os.Parcelable; + +/** + * BaseDataType representing Identity deletion information retrieved from server. + */ +public class IdentityDeletion extends BaseDataType implements Parcelable { + + /** + * Enumeration of Tags for StatusMsg item. + */ + private enum Tags { + STATUS("status"), + DRYRUN("dryrun"); + + private final String tag; + + /** + * Constructor creating Tags item for specified String. + * + * @param s + * String value for Tags item. + */ + private Tags(final String s) { + tag = s; + } + + /** + * String value associated with Tags item. + * + * @return String value for Tags item. + */ + private String tag() { + return tag; + } + + /** + * Find Tags item for specified String. + * + * @param tag + * String value to find Tags item for + * @return Tags item for specified String, null otherwise + */ + private static Tags findTag(final String tag) { + for (Tags tags : Tags.values()) { + if (tag.compareTo(tags.tag()) == 0) { + return tags; + } + } + return null; + } + } + + private Boolean mStatus = null; + + private Boolean mDryRun = null; + + /** {@inheritDoc} */ + @Override + public int getType() { + return IDENTITY_DELETION_DATA_TYPE; + } + + /** + * Populate Identity from supplied Hashtable. + * + * @param hash + * Hashtable containing identity details. + * @return Identity instance + */ + public final IdentityDeletion createFromHashtable(final Hashtable<String, Object> hash) { + Enumeration<String> e = hash.keys(); + while (e.hasMoreElements()) { + String key = e.nextElement(); + Tags tag = Tags.findTag(key); + if (tag != null) { + setValue(tag, hash.get(key)); + } + } + return this; + } + + /** + * Sets the value of the member data item associated with the specified tag. + * + * @param tag + * Current tag + * @param val + * Value associated with the tag + */ + private void setValue(final Tags tag, final Object val) { + switch (tag) { + case STATUS: + mStatus = (Boolean) val; + break; + + case DRYRUN: + mDryRun = (Boolean) val; + break; + + default: + // Do nothing. + break; + } + } + + /** {@inheritDoc} */ + @Override + public final int describeContents() { + return 1; + } + + /** {@inheritDoc} */ + @Override + public final void writeToParcel(final Parcel dest, final int flags) { + Object[] ba = new Object[2]; + ba[0] = mStatus; + ba[1] = mDryRun; + dest.writeArray(ba); + + } +} diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index b117c06..5bd1360 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,776 +1,894 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.identities; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import android.os.Bundle; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Identities; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; /** * Engine responsible for handling retrieval and validation of Identities (e.g. * 3rd party/web accounts). The Identities engine can fetch a list of available * accounts, and set required capabilities and validate credentials for * specified accounts. */ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { /** * States for IdentitiesEngine. States are based on the requests that the * engine needs to handle. */ private enum State { IDLE, FETCHING_IDENTITIES, VALIDATING_IDENTITY_CREDENTIALS, SETTING_IDENTITY_STATUS, GETTING_MY_IDENTITIES, - GETTING_MY_CHATABLE_IDENTITIES + GETTING_MY_CHATABLE_IDENTITIES, + DELETE_IDENTITY } /** * Mutex for thread synchronisation */ private final Object mMutex = new Object(); /** * Container class for Identity Capability Status request. Consists of a * network, identity id and a filter containing the required capabilities. */ private static class IdentityStatusRequest { private String mNetwork; private String mIdentityId; private String mIdentityStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setIdentityStatus(String status) { mIdentityStatus = status; } } /** * Container class encapsulating an Identity validation request containing: * dry-run flag, network, user-name, password, set of required capabilities. */ private static class IdentityValidateCredentialsRequest { /** Performs a dry run if true. */ private boolean mDryRun; /** Network to sign into. */ private String mNetwork; /** Username to sign into identity with. */ private String mUserName; /** Password to sign into identity with. */ private String mPassword; private Map<String, Boolean> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } + + /** + * + * Container class for Delete Identity request. Consist network and identity id. + * + */ + private static class DeleteIdentityRequest { + /** Network to delete.*/ + private String mNetwork; + /** IdentityID which needs to be Deleted.*/ + private String mIdentityId; + } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mMyIdentityList; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; + /** + * Maintaining DeleteIdentityRequest so that it can be later removed from + * maintained cache. + **/ + private DeleteIdentityRequest identityToBeDeleted; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; mMyIdentityList = new ArrayList<Identity>(); mAvailableIdentityList = new ArrayList<Identity>(); mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { if ((mAvailableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return mMyIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = getMyThirdPartyChattableIdentities(); // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chattableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chattableIdentities; } /** * * Takes all third party identities that have a chat capability set to true. * * @return A list of chattable 3rd party identities the user is signed in to. If the retrieval identities failed the returned list will be empty. * */ public ArrayList<Identity> getMyThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = new ArrayList<Identity>(); int identityListSize = mMyIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = mMyIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue)) { chattableIdentities.add(identity); break; } } } return chattableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } + + + /** + * Delete the given social network. + * + * @param network Name of the identity, + * @param identityId Id of identity. + */ + public final void addUiDeleteIdentityRequest(final String network, final String identityId) { + LogUtils.logD("IdentityEngine.addUiRemoveIdentity()"); + DeleteIdentityRequest data = new DeleteIdentityRequest(); + + data.mNetwork = network; + data.mIdentityId = identityId; + + /**maintaining the sent object*/ + setIdentityToBeDeleted(data); + + addUiRequestToQueue(ServiceUiRequest.DELETE_IDENTITY, data); + } + + /** + * Setting the DeleteIdentityRequest object. + * + * @param data + */ + private void setIdentityToBeDeleted(final DeleteIdentityRequest data) { + identityToBeDeleted = data; + } + + /** + * Return the DeleteIdentityRequest object. + * + */ + private DeleteIdentityRequest getIdentityToBeDeleted() { + return identityToBeDeleted; + } /** * Issue any outstanding UI request. - * + * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; + case DELETE_IDENTITY: + executeDeleteIdentityRequest(data); + break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } + /** + * Issue request to delete the identity as specified . (Request is not issued if there + * is currently no connectivity). + * + * @param data bundled request data containing network and identityId. + */ + + private void executeDeleteIdentityRequest(final Object data) { + if (!isConnected()) { + completeUiRequest(ServiceStatus.ERROR_NO_INTERNET); + } + newState(State.DELETE_IDENTITY); + DeleteIdentityRequest reqData = (DeleteIdentityRequest) data; + + if (!setReqId(Identities.deleteIdentity(this, reqData.mNetwork, + reqData.mIdentityId))) { + completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); + } + } + /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(DecodedResponse resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if ((null == resp) || (null == resp.mDataTypes)) { LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); return; } // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; + case BaseDataType.IDENTITY_DELETION_DATA_TYPE: + handleDeleteIdentity(resp.mDataTypes); + break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); } } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } + + /** + * Handle Server response of request to delete the identity. The response + * should be a status that whether the operation is succeeded or not. The + * response will be a status result otherwise ERROR_UNEXPECTED_RESPONSE if + * the response is not as expected. + * + * @param data + * List of BaseDataTypes generated from Server response. + */ + private void handleDeleteIdentity(final List<BaseDataType> data) { + Bundle bu = null; + ServiceStatus errorStatus = getResponseStatus( + BaseDataType.IDENTITY_DELETION_DATA_TYPE, data); + if (errorStatus == ServiceStatus.SUCCESS) { + for (BaseDataType item : data) { + if (item.getType() == BaseDataType.IDENTITY_DELETION_DATA_TYPE) { + // iterating through the subscribed identities + for (Identity identity : mMyIdentityList) { + if (identity.mIdentityId + .equals(getIdentityToBeDeleted().mIdentityId)) { + mMyIdentityList.remove(identity); + break; + } + } + + completeUiRequest(ServiceStatus.SUCCESS); + return; + } else { + completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); + return; + } + } + } + completeUiRequest(errorStatus, bu); + + } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; idBundle = mAvailableIdentityList; } else { requestKey = KEY_MY_IDS; idBundle = mMyIdentityList; } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } /** * * Retrieves the filter for the getAvailableIdentities and getMyIdentities * calls. * * @return The identities filter in form of a bundle. * */ private Bundle getIdentitiesFilter() { Bundle b = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); l.add(IdentityCapability.CapabilityID.get_own_status.name()); b.putStringArrayList("capability", l); return b; } @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } /** * Generate Map containing String capability filters for m supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, List<String>> prepareStringFilter(Bundle filter) { Map<String, List<String>> returnFilter = null; if (filter != null && filter.keySet().size() > 0) { returnFilter = new Hashtable<String, List<String>>(); for (String key : filter.keySet()) { returnFilter.put(key, filter.getStringArrayList(key)); } } else { returnFilter = null; } return returnFilter; } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ /** {@inheritDoc} */ @Override public final void onReset() { super.onReset(); mMyIdentityList.clear(); mAvailableIdentityList.clear(); mStatusList.clear(); mState = State.IDLE; } } diff --git a/src/com/vodafone360/people/service/ServiceUiRequest.java b/src/com/vodafone360/people/service/ServiceUiRequest.java index 3221220..22555eb 100644 --- a/src/com/vodafone360/people/service/ServiceUiRequest.java +++ b/src/com/vodafone360/people/service/ServiceUiRequest.java @@ -1,263 +1,267 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; /** * The list of requests that the People Client UI can issue to the People Client * service. These requests are handled by the appropriate engine. */ public enum ServiceUiRequest { /* * UiAgent: Each request is an unsolicited message sent to the UI via the * UiAgent. Requests with a higher priority can overwrite lower priority * requests waiting in the UiAgent queue. */ /** HIGH PRIRITY: Go to landing page, explain why in the Bundle. **/ UNSOLICITED_GO_TO_LANDING_PAGE, UI_REQUEST_COMPLETE, DATABASE_CHANGED_EVENT, SETTING_CHANGED_EVENT, /** Update in the terms and conditions or privacy text. **/ TERMS_CHANGED_EVENT, /*** * Update the contact sync progress bar, currently used only in the * SyncingYourAddressBookActivity. */ UPDATE_SYNC_STATE, UNSOLICITED_CHAT, UNSOLICITED_PRESENCE, UNSOLICITED_CHAT_ERROR, UNSOLICITED_CHAT_ERROR_REFRESH, UNSOLICITED_PRESENCE_ERROR, /** LOW PRIORITY Show the upgrade dialog. **/ UNSOLICITED_DIALOG_UPGRADE, /* * Non-UiAgent: Each request is handled by a specific Engine. */ /** * Login to existing account, handled by LoginEngine. * * @see com.vodafone360.people.engine.login.LoginEngine */ LOGIN, /** * Sign-up a new account, handled by LoginEngine. * * @see com.vodafone360.people.engine.login.LoginEngine */ REGISTRATION, /** * Fetch user-name availability state, handled by LoginEngine. * * @see com.vodafone360.people.engine.login.LoginEngine */ USERNAME_AVAILABILITY, /** * Handled by LoginEngine. * * @see com.vodafone360.people.engine.login.LoginEngine */ FETCH_TERMS_OF_SERVICE, /** * Handled by LoginEngine. * * @see com.vodafone360.people.engine.login.LoginEngine */ FETCH_PRIVACY_STATEMENT, /** * Fetch list of available 3rd party accounts, handled by IdentitiesEngine. * * @see com.vodafone360.people.engine.identitys.IdentityEngine */ GET_AVAILABLE_IDENTITIES, /** * Validate credentials for specified 3rd party account, handled by * IdentitiesEngine. * * @see com.vodafone360.people.engine.identitys.IdentityEngine */ VALIDATE_IDENTITY_CREDENTIALS, /** * Set required capabilities for specified 3rd party account, handled by * IdentitiesEngine. * * @see com.vodafone360.people.engine.identitys.IdentityEngine */ SET_IDENTITY_CAPABILITY_STATUS, /** * Get list of 3rd party accounts for current user, handled by * IdentitiesEngine. * * @see com.vodafone360.people.engine.identitys.IdentityEngine */ GET_MY_IDENTITIES, /** * Get list of 3rd party accounts for current user that support chat, * handled by IdentitiesEngine. * * @see com.vodafone360.people.engine.identitys.IdentityEngine */ GET_MY_CHATABLE_IDENTITIES, /** * Fetch older activities from Server, handled by ActivitiesEngine. * * @see com.vodafone360.people.engine.activities.ActivitiesEngine */ FETCH_STATUSES, /** * Fetch latest statuses from Server ("refresh" button, or push event), * handled by ActivitiesEngine. * * @see com.vodafone360.people.engine.identitys.AvtivitiesEngine */ UPDATE_STATUSES, /** * Fetch timelines from the native (invoked by "show older" button) * * @see com.vodafone360.people.engine.identitys.AvtivitiesEngine */ FETCH_TIMELINES, /** * Update the timeline list (invoked by NAB event) * * @see com.vodafone360.people.engine.identitys.AvtivitiesEngine */ UPDATE_PHONE_CALLS, /** * Update the phone calls in the list of timelines (invoked by NAB event) * * @see com.vodafone360.people.engine.identitys.AvtivitiesEngine */ UPDATE_SMS, /** * Update the SMSs in the list of timelines (invoked by push event) * * @see com.vodafone360.people.engine.identitys.AvtivitiesEngine */ UPDATE_TIMELINES, /** * Start contacts sync, handled by ContactSyncEngine. * * @see com.vodafone360.people.engine.contactsync.ContactSyncEngine */ NOWPLUSSYNC, /** * Starts me profile download, handled by SyncMeEngine. * * @see com.vodafone360.people.engine.meprofile.SyncMeEngine */ GET_ME_PROFILE, /** * Starts me profile upload, handled by SyncMeEngine. * * @see com.vodafone360.people.engine.meprofile.SyncMeEngine */ UPDATE_ME_PROFILE, /** * Starts me profile status upload. * * @see com.vodafone360.people.engine.meprofile.SyncMeEngine */ UPLOAD_ME_STATUS, /** * Starts me profile thumbnail download, handled by SyncMeEngine. * * @see com.vodafone360.people.engine.meprofile.SyncMeEngine */ DOWNLOAD_THUMBNAIL, /** Remove all user data. */ REMOVE_USER_DATA, /** * Logout from account, handled by LoginEngine. For debug/development use * only. * * @see com.vodafone360.people.engine.login.LoginEngine */ LOGOUT, /** * Request UpgradeEngine to check if an updated version of application is * available. * * @see com.vodafone360.people.engine.upgrade.UpgradeEngine */ UPGRADE_CHECK_NOW, /** * Set frequency for upgrade check in UpgradeEngine. * * @see com.vodafone360.people.engine.upgrade.UpgradeEngine */ UPGRADE_CHANGE_FREQUENCY, /** * Request list of current 'presence status'of contacts, handled by * PresenceEngine. */ GET_PRESENCE_LIST, /** * Request to set the presence availability status. */ SET_MY_AVAILABILITY, /** Start a chat conversation. */ CREATE_CONVERSATION, /** Send chat message. */ SEND_CHAT_MESSAGE, /** * UI might need to display a progress bar, or other background process * indication **/ UPDATING_UI, /** * UI might need to remove a progress bar, or other background process * indication **/ UPDATING_UI_FINISHED, /** * Gets the groups for the contacts that are retrieved from the backend. */ GET_GROUPS, + /** + * Remove Identity. + */ + DELETE_IDENTITY, /* * Do not handle this message. */ UNKNOWN; /*** * Get the UiEvent from a given Integer value. * * @param input Integer.ordinal value of the UiEvent * @return Relevant UiEvent or UNKNOWN if the Integer is not known. */ public static ServiceUiRequest getUiEvent(int input) { if (input < 0 || input > UNKNOWN.ordinal()) { return UNKNOWN; } else { return ServiceUiRequest.values()[input]; } } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index c3e5a44..4694796 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,371 +1,379 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.interfaces; import java.util.ArrayList; import java.util.Hashtable; import android.os.Bundle; import android.os.Handler; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.agent.NetworkAgentState; /*** * Interface to expose service functionality to the UI classes. */ public interface IPeopleService { /*** * Allows the Activity to register a Handler, so that it can receive new * call back events from the Service layer. * * @param Handler to listen for call back events. */ void addEventCallback(Handler uiHandler); /*** * Allows the Activity to unregister a Handler, so it will no longer receive * call back events from the Service layer. Usually called on an Activity's * onDestroy() method. * * @param Handler to listen for call back events. */ void removeEventCallback(Handler uiHandler); /*** * Called by the UI to determine if the Service is currently logged into the * Vodafone 360 back end. Called by the StartActivity and other key classes, * so the work flow can be diverted back to the Landing page if the user has * been signed out for any reason. * * @return TRUE Service is logged into the back end system, FALSE user must * log in before they can use the Application. */ boolean getLoginRequired(); /*** * Sets a preference that disables the showing of further roaming * notifications. * * @param TRUE show further roaming notifications, FALSE stop showing */ void setShowRoamingNotificationAgain(boolean showAgain); /*** * Gets the type of roaming notification to show to the user * * @return ROAMING_DIALOG_GLOBAL_ON Data roaming is on, * ROAMING_DIALOG_GLOBAL_OFF Data roaming is off */ int getRoamingNotificationType(); /*** * Gets the current IS_ROAMING_ALLOWED value for the device, which is set by * the user in the * "Menu > Settings > Wireless Controls > Mobile network settings > Data roaming" * check box. * * @return TRUE when roaming is permitted, FALSE when roaming is not * permitted. */ boolean getRoamingDeviceSetting(); /*** * Sets the current Data connectivity preference (i.e. connect, connect when * not roaming, or never connect), although this value is ignored during * initial sign up. * * @see com.vodafone360.people.service.PersistSettings.InternetAvail * @param InternetAvail New data Settings changes */ void notifyDataSettingChanged(InternetAvail internetAvail); /*** * Fetched the current Terms of Service information from the Vodafone 360 * back end system. The result is sent to the registered Handler some time * later after the download process has finished. */ void fetchTermsOfService(); /*** * Fetched the current Privacy Statement information from the Vodafone 360 * back end system. The result is sent to the registered Handler some time * later after the download process has finished. */ void fetchPrivacyStatement(); /*** * Log into the Vodafone 360 back end system using the given credentials. * * @param LoginDetails object containing user name, password, etc. */ void logon(LoginDetails loginDetails); /*** * Asks the back end server to check the validity of the given user name. * * @param String User name to check. */ void fetchUsernameState(String username); /*** * Signs up a new user to the Vodafone 360 back end using the given * Registration details. * * @param RegistrationDetails Registration details */ void register(RegistrationDetails details); /*** * Begins the process of synchronising contacts with the Vodafone 360 back * end. This is designed to run in the foreground and be shown to the user * during the initial sign up process. */ void startContactSync(); /*** * Begins the process of synchronising contacts with the Vodafone 360 back * end. This is designed to run in the background and is called every time * the ContactListActivity is shown to the user. * * @param delay the delay in milliseconds from now when the sync should * start */ void startBackgroundContactSync(long delay); /** * Pings the service about user activity. */ void pingUserActivity(); /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities(); /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities(); /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities(); /*** * Begins the process of retrieving all Third party Accounts from the * Vodafone 360 back end. The response is sent to any currently registered * Activity handlers. * * @param Bundle filter the kind of identities to return. */ //void fetchAvailableIdentities(Bundle data); /*** * Calls the set identity capability status API * * @param network Social Network Name * @param identityId Social Network Identifier * @param identityCapabilityStatus Social Network capability status Bundle */ void setIdentityStatus(String network, String identityId, boolean identityStatus); /*** * Validate the given Social Network identity * * @param dryRun Set to true to validate credentials without actually * signing the server up. * @param network Social Network Name * @param username Login user name * @param password Login password * @param identityCapabilityStatus Social Network capability status Bundle */ void validateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus); /*** * Push the UpdateEngine to immediately check for an updated version of the * client. */ void checkForUpdates(); /*** * Push the UpdateEngine to check if a new update frequency has been set and * to act accordingly. */ void setNewUpdateFrequency(); /*** * Push the ActivitiesEngine Engine to begin synchronising Activities */ void startStatusesSync(); /*** * Returns the current state of the Network Agent. Used for testing only. */ NetworkAgentState getNetworkAgentState(); /*** * Overrides the current state of the Network Agent. Used for testing only. * * @param state A new overriding state. */ void setNetworkAgentState(NetworkAgentState state); /*** * Request a refresh of the currently known Presence information (used for * testing only) * * @param contactId Provide a contactId to receive detailed presence * information for the given contact only * @param contactId Set this to -1 to receive less detailed presence * information but for every contact */ void getPresenceList(long contactId); /** * Change current global (all identities) availability state. * @param status Availability to set for all identities we have. */ void setAvailability(OnlineStatus status); /** * Changes the user's availability. * * @param status - Hashtable<String, String> is the hash of pairs <networkName, statusName>. */ void setAvailability(Hashtable<String, String> status); /** * Changes the user's availability. * * @param network - SocialNetwork to set presence on. * @param status - OnlineStatus presence status to set. */ void setAvailability(SocialNetwork network, OnlineStatus status); /*** * Allows an Activity to indicate to the Service that it is ready and able * to handle incoming unsolicited UI events. This should be called in an * Activities onResume() method, to indicate that the activity is currently * on screen. * * @param handler to accept incoming unsolicited UI events from the Service. * @param contactId Provide a contactId to receive updates for the given * contact only. Set this to -1 to receive updates for every * contact. Set this to NULL not to receive contact updates. * @param chat - TRUE if the Handler expects chat messages. */ void subscribe(Handler handler, Long contactId, boolean chat); /*** * Allows the Activity to indicate that it is no longer in the foreground * and will not handle incoming UI events correctly. This should be called * in an Activities onPause() method, to indicate that the Activity is not * on screen. * * @param handler that should no longer receive incoming unsolicited UI * events from the Service */ void unsubscribe(Handler handler); /** * This method should be used to send a message to a contact * * @param to LocalContactIds of ContactSummary/TimelineSummary items the * message is intended for. Current protocol version only * supports a single recipient. * @param body Message text */ void sendMessage(long toLocalContactId, String body, int socialNetworkId); /** * This method should be called to retrieve status updates in * StatusListActivity, @see ActivitiesEngine. */ void getStatuses(); /** * This method should be called to retrieve older timelines in * TimelineListActivity, @see ActivitiesEngine. */ void getMoreTimelines(); /** * This method should be called to retrieve older statuses in * StatusListActivity, @see ActivitiesEngine. */ void getOlderStatuses(); /** * This method triggers the Me Profile upload */ void uploadMeProfile(); /** * This method triggers the Me Profile status text upload * * @param statusText String - new Me Profile status text */ void uploadMyStatus(String statusText); /** * This method triggers the Me Profile download, is currently called by UI */ void downloadMeProfileFirstTime(); /** * This method should be called to update the Chat Notifications. */ void updateChatNotification(long localContactId); + /** + * This method delete the identity. + * @param network Social Network Name + * @param identityId Social Network Identifier + */ + void deleteIdentity(String network, String identityId); + + } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java index 9b9a392..9ab10cc 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,439 +1,449 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.interfaces; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import android.os.Bundle; import android.os.Handler; import android.os.Message; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.MainApplication; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.agent.NetworkAgentState; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.utils.LogUtils; /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback * @see com.vodafone360.people.service.interfaces.IPeopleService */ public class IPeopleServiceImpl implements IPeopleService, IEngineEventCallback { private final List<Handler> mUiEventCallbackList = new ArrayList<Handler>(); private IWorkerThreadControl mWorkerThreadControl; private RemoteService mService; private NetworkAgent mNetworkAgent; private UiAgent mHandlerAgent; private ApplicationCache mApplicationCache; /** * Initialises the object, creating the UiAgent. * * @param workerThreadControl Provides access to worker thread control * functions. * @param service Provides access to remote service functions (mainly used * to retrieve context). */ public IPeopleServiceImpl(IWorkerThreadControl workerThreadControl, RemoteService service) { mWorkerThreadControl = workerThreadControl; mService = service; mHandlerAgent = new UiAgent((MainApplication)service.getApplication(), service); mApplicationCache = ((MainApplication)service.getApplication()).getCache(); } /*** * Sets the ServiceAgent, as this needs to be called after the constructor. * * @param agent Handle to ServiceAgent. */ public void setNetworkAgent(NetworkAgent agent) { mNetworkAgent = agent; } /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#onUiEvent(UiEvent, * int, int, Object) */ @Override public void onUiEvent(ServiceUiRequest event, int arg1, int arg2, Object data) { synchronized (mUiEventCallbackList) { for (Handler handler : mUiEventCallbackList) { Message msg = handler.obtainMessage(event.ordinal(), data); msg.arg1 = arg1; msg.arg2 = arg2; if (!handler.sendMessage(msg)) { LogUtils.logE("IPeopleServiceImpl.onUiEvent() Sending msg FAILED"); } } } } /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#kickWorkerThread() */ @Override public void kickWorkerThread() { mWorkerThreadControl.kickWorkerThread(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#addEventCallback(Handler) */ @Override public void addEventCallback(Handler uiHandler) { synchronized (mUiEventCallbackList) { if (!mUiEventCallbackList.contains(uiHandler)) { mUiEventCallbackList.add(uiHandler); } } } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#removeEventCallback(Handler) */ @Override public void removeEventCallback(Handler uiHandler) { synchronized (mUiEventCallbackList) { mUiEventCallbackList.remove(uiHandler); } } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#checkForUpdates() */ @Override public void checkForUpdates() { EngineManager.getInstance().getUpgradeEngine().checkForUpdates(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMyThirdPartyIdentities() */ public ArrayList<Identity> getMyThirdPartyIdentities() { return EngineManager.getInstance().getIdentityEngine().getMyThirdPartyIdentities(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyIdentities() */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { return EngineManager.getInstance().getIdentityEngine().getAvailableThirdPartyIdentities(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyChattableIdentities() */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { return EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchPrivacyStatement() */ @Override public void fetchPrivacyStatement() { EngineManager.getInstance().getLoginEngine().addUiFetchPrivacyStatementRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchTermsOfService() */ @Override public void fetchTermsOfService() { EngineManager.getInstance().getLoginEngine().addUiFetchTermsOfServiceRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchUsernameState(String) */ @Override public void fetchUsernameState(String userName) { EngineManager.getInstance().getLoginEngine().addUiGetUsernameStateRequest(userName); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getLoginRequired() */ @Override public boolean getLoginRequired() { EngineManager manager = EngineManager.getInstance(); return manager.getLoginEngine().getLoginRequired(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getRoamingNotificationType() */ @Override public int getRoamingNotificationType() { return mService.getNetworkAgent().getRoamingNotificationType(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getRoamingDeviceSetting() */ @Override public boolean getRoamingDeviceSetting() { return mService.getNetworkAgent().getRoamingDeviceSetting(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#notifyDataSettingChanged(InternetAvail) */ @Override public void notifyDataSettingChanged(InternetAvail val) { mService.getNetworkAgent().notifyDataSettingChanged(val); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#logon(LoginDetails) */ @Override public void logon(LoginDetails loginDetails) { EngineManager manager = EngineManager.getInstance(); manager.getLoginEngine().addUiLoginRequest(loginDetails); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#register(RegistrationDetails) */ @Override public void register(RegistrationDetails details) { EngineManager.getInstance().getLoginEngine().addUiRegistrationRequest(details); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setNewUpdateFrequency() */ @Override public void setNewUpdateFrequency() { EngineManager.getInstance().getUpgradeEngine().setNewUpdateFrequency(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setShowRoamingNotificationAgain(boolean) */ @Override public void setShowRoamingNotificationAgain(boolean showAgain) { mService.getNetworkAgent().setShowRoamingNotificationAgain(showAgain); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startContactSync() */ @Override public void startContactSync() { EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); EngineManager.getInstance().getContactSyncEngine().addUiStartFullSync(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startBackgroundContactSync(long) */ @Override public void startBackgroundContactSync(long delay) { EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); EngineManager.getInstance().getContactSyncEngine().addUiStartServerSync(delay); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#pingUserActivity() */ @Override public void pingUserActivity() { EngineManager.getInstance().getContactSyncEngine().pingUserActivity(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#validateIdentityCredentials(boolean, * String, String, String, Bundle) */ @Override public void validateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { EngineManager.getInstance().getIdentityEngine().addUiValidateIdentityCredentials(dryRun, network, username, password, identityCapabilityStatus); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startStatusesSync() */ @Override public void startStatusesSync() { EngineManager.getInstance().getActivitiesEngine().addStatusesSyncRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getNetworkAgentState() */ @Override public NetworkAgentState getNetworkAgentState() { return mNetworkAgent.getNetworkAgentState(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setNetowrkAgentState(NetworkAgentState) */ @Override public void setNetworkAgentState(NetworkAgentState state) { mNetworkAgent.setNetworkAgentState(state); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getPresenceList(long) */ @Override public void getPresenceList(long contactId) { EngineManager.getInstance().getPresenceEngine().getPresenceList(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(OnlineStatus) */ @Override public void setAvailability(OnlineStatus status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(SocialNetwork, OnlineStatus) */ @Override public void setAvailability(SocialNetwork network, OnlineStatus status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(network, status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(Hashtable<String, String> status) */ @Override public void setAvailability(Hashtable<String, String> status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#subscribe(Handler, * long, boolean) */ @Override public void subscribe(Handler handler, Long contactId, boolean chat) { mHandlerAgent.subscribe(handler, contactId, chat); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#unsubscribe(Handler) */ @Override public void unsubscribe(Handler handler) { mHandlerAgent.unsubscribe(handler); } /** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#getUiAgent() */ @Override public UiAgent getUiAgent() { return mHandlerAgent; } /** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#getApplicationCache() */ @Override public ApplicationCache getApplicationCache() { return mApplicationCache; } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#sendMessage(long, * String, int) */ @Override public void sendMessage(long localContactId, String body, int networkId) { EngineManager.getInstance().getPresenceEngine() .sendMessage(localContactId, body, networkId); } @Override public void setIdentityStatus(String network, String identityId, boolean identityStatus) { EngineManager.getInstance().getIdentityEngine().addUiSetIdentityStatus(network, identityId, identityStatus); } @Override public void getStatuses() { EngineManager.getInstance().getActivitiesEngine().addStatusesSyncRequest(); } @Override public void getMoreTimelines() { EngineManager.getInstance().getActivitiesEngine().addOlderTimelinesRequest(); } @Override public void getOlderStatuses() { EngineManager.getInstance().getActivitiesEngine().addGetOlderStatusesRequest(); } @Override public void uploadMeProfile() { EngineManager.getInstance().getSyncMeEngine().addUpdateMeProfileContactRequest(); } @Override public void uploadMyStatus(String statusText) { EngineManager.getInstance().getSyncMeEngine().addUpdateMyStatusRequest(statusText); } @Override public void downloadMeProfileFirstTime() { EngineManager.getInstance().getSyncMeEngine().addGetMeProfileContactFirstTimeRequest(); } @Override public void updateChatNotification(long localContactId) { mHandlerAgent.updateChat(localContactId, false); } + + /** + * @see com.vodafone360.people.service.interfaces.IPeopleService#deleteIdentity(String,String) + */ + @Override + public void deleteIdentity(final String network, final String identityId) { + EngineManager.getInstance().getIdentityEngine() + .addUiDeleteIdentityRequest(network, identityId); + + } } \ No newline at end of file diff --git a/src/com/vodafone360/people/service/io/Request.java b/src/com/vodafone360/people/service/io/Request.java index 323e8df..deeb848 100644 --- a/src/com/vodafone360/people/service/io/Request.java +++ b/src/com/vodafone360/people/service/io/Request.java @@ -1,596 +1,597 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.io.IOException; import java.io.OutputStream; import java.util.Hashtable; import java.util.List; import java.util.Vector; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.io.rpg.RpgMessage; import com.vodafone360.people.service.io.rpg.RpgMessageTypes; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.AuthUtils; import com.vodafone360.people.service.utils.hessian.HessianEncoder; /** * Container class for Requests issued from client to People server via the * transport layer. A request consists of a payload, an identifier for the * engine responsible for handling this request, a request type and a request id * which is generated on creation of the request. */ public class Request { /** * Request types, these are based on the content requested from, or * delivered to, the server, and whether the returned response contains a * type identifier or not. */ public enum Type { COMMON, // Strongly typed ADD_CONTACT, TEXT_RESPONSE_ONLY, CONTACT_CHANGES_OR_UPDATES, CONTACT_DELETE, CONTACT_DETAIL_DELETE, FRIENDSHIP_REQUEST, USER_INVITATION, SIGN_UP, SIGN_IN, RETRIEVE_PUBLIC_KEY, EXPECTING_STATUS_ONLY, GROUP_LIST, STATUS_LIST, STATUS, CONTACT_GROUP_RELATION_LIST, CONTACT_GROUP_RELATIONS, ITEM_LIST_OF_LONGS, PRESENCE_LIST, AVAILABILITY, CREATE_CONVERSATION, SEND_CHAT_MESSAGE, PUSH_MSG, EXTERNAL_RPG_RESPONSE, GET_MY_IDENTITIES, - GET_AVAILABLE_IDENTITIES + GET_AVAILABLE_IDENTITIES, + DELETE_IDENTITY // response to external RPG request } /* * List of parameters which will be used to generate the AUTH parameter. */ private Hashtable<String, Object> mParameters = new Hashtable<String, Object>(); /** * Name of method on the backend. E.g. identities/getavailableidentities. */ private String mApiMethodName; /** RPG message payload (usually Hessian encoded message body). */ // private byte[] mPayload; /** RPG Message type - as defined above. */ public Type mType; /** Handle of Engine associated with this RPG message. */ public EngineId mEngineId = EngineId.UNDEFINED; // to be used to map request // to appropriate engine /** Whether we use RPG for this message. */ // public boolean mUseRpg = true; /** active flag - set to true once we have actually issued a request */ private boolean mIsActive = false; /** * The timeout set for the request. -1 if not set. */ private long mTimeout = -1; /** * The expiry date calculated when the request gets executed. */ private long mExpiryDate = -1; /** true if the request has expired */ public boolean expired; /** * The timestamp when the request's auth was calculated. */ private long mAuthTimestamp; /** * The timestamp when this request was created. */ private long mCreationTimestamp; /** * <p> * Represents the authentication type that needs to be taken into account * when executing this specific request. There are 3 types of authentication * types: * </p> * <ul> * <li>USE_API: needs the API. These requests are usually requests like * getSessionByCredentials that use application authentication.</li> * <li>USE_RPG: these requests should use the RPG and some of them MUST use * the RPG. Usually, all requests after the auth requests should use the * RPG.</li> * <li>USE_BOTH: some requests like the requests for getting terms and * conditions or privacy statements need to be able to use the RPG or API at * any time of the application lifecycle.</li> * </ul> */ private byte mAuthenticationType; public static final byte USE_API = 1, USE_RPG = 2, USE_BOTH = 3; /** * If true, this method is a fire and forget method and will not expect any * responses to come in. This fact can be used for removing requests from * the queue as soon as they have been sent. */ private boolean mIsFireAndForget; /** RPG message request id. */ private int mRequestId; /** * Constructor used for constructing internal (RPG/API) requests. * * @param apiMethodName The method name of the call, e.g. * "identities/getavailableidentities". * @param type RPG message type. * @param engId The engine ID. Will be used for routing the response to this * request back to the engine that can process it. * @param needsUserAuthentication If true we need to authenticate this * request by providing the session in the auth. This requires * the user to be logged in. * @param isFireAndForget True if the request is a fire and forget request. * @param timeout the timeout in milliseconds before the request throws a * timeout exception */ public Request(String apiMethodName, Type type, EngineId engineId, boolean isFireAndForget, long timeout) { mType = type; // TODO find out a type yourself? mEngineId = engineId; mApiMethodName = apiMethodName; mIsFireAndForget = isFireAndForget; mCreationTimestamp = System.currentTimeMillis(); mTimeout = timeout; if ((type == Type.RETRIEVE_PUBLIC_KEY) || (type == Type.SIGN_UP) || (type == Type.STATUS) || (type == Type.SIGN_IN)) { // we need to register, sign in, get t&c's etc. so the request needs // to happen without // user auth mAuthenticationType = USE_API; } else if (type == Type.TEXT_RESPONSE_ONLY) { // t&c or privacy mAuthenticationType = USE_BOTH; } else { // all other requests should use the RPG by default mAuthenticationType = USE_RPG; } } /** * Constructor used for constructing an external request used for fetching * e.g. images. * * @param externalUrl The external URL of the object to fetch. * @param urlParams THe parameters to add to the URL of this request. * @param engineId The ID of the engine that will be called back once the * response for this request comes in. */ public Request(String externalUrl, String urlParams, EngineId engineId) { mType = Type.EXTERNAL_RPG_RESPONSE; mEngineId = engineId; mApiMethodName = ""; mIsFireAndForget = false; mCreationTimestamp = System.currentTimeMillis(); mParameters = new Hashtable<String, Object>(); mParameters.put("method", "GET"); mParameters.put("url", externalUrl + urlParams); mAuthenticationType = USE_RPG; } /** * Is request active - i.e has it been issued * * @return true if request is active */ public boolean isActive() { return mIsActive; } /** * <p> * Sets whether this request is active or not. An active request is a * request that is currently being sent to the server and awaiting a * response. * </p> * <p> * The reason is that an active request should not be sent twice. * </p> * * @param isActive True if the request is active, false otherwise. */ public void setActive(boolean isActive) { mIsActive = isActive; } /** * Returns a description of the contents of this object * * @return The description */ @Override public String toString() { StringBuilder sb = new StringBuilder("Request [mEngineId="); sb.append(mEngineId); sb.append(", mIsActive="); sb.append(mIsActive); sb.append(", mTimeout="); sb.append(mTimeout); sb.append(", mReqId="); sb.append(mRequestId); sb.append(", mType="); sb.append(mType); sb.append(", mNeedsUserAuthentication="); sb.append(mAuthenticationType); sb.append(", mExpired="); sb.append(expired); sb.append(", mDate="); sb.append(mExpiryDate); sb.append("]\n"); sb.append(mParameters); return sb.toString(); } /** * Adds element to list of params * * @param name key name for object to be added to parameter list * @param nv object which will be added */ public void addData(String name, Hashtable<String, ?> nv) { mParameters.put(name, nv); } /** * Adds element to list of params * * @param name key name for object to be added to parameter list * @param value object which will be added */ public void addData(String name, Vector<Object> value) { mParameters.put(name, value); } /** * Adds element to list of params * * @param name key name for object to be added to parameter list * @param value object which will be added */ public void addData(String name, List<String> value) { mParameters.put(name, value); } /** * Adds byte array to parameter list * * @param varName name * @param value byte[] array to be added */ public void addData(String varName, byte[] value) { mParameters.put(varName, value); } /** * Create new NameValue and adds it to list of params * * @param varName name * @param value string value */ public void addData(String varName, String value) { mParameters.put(varName, value); } /** * Create new NameValue and adds it to list of params * * @param varName name * @param value Long value */ public void addData(String varName, Long value) { mParameters.put(varName, value); } /** * Create new NameValue and adds it to list of params * * @param varName name * @param value Integer value */ public void addData(String varName, Integer value) { mParameters.put(varName, value); } /** * Create new NameValue and adds it to list of params * * @param varName name * @param value Boolean value */ public void addData(String varName, Boolean value) { mParameters.put(varName, value); } /** * Returns a Hashtable containing current request parameter list. * * @return params The parameters that were added to this backend request. */ /* * public Hashtable<String, Object> getParameters() { return mParameters; } */ /** * Returns the authentication type of this request. This can be one of the * following: USE_API, which must be used for authentication requests that * need application authentication, USE_RPG, useful for requests against the * API that need user authentication and want to profit from the mobile * enhancements of the RPG, or USE_BOTH for requests that need to be able to * be used on the API or RPG. These requests are for example the Terms and * Conditions requests which need to be accessible from anywhere in the * client. * * @return True if this method requires user authentication or a valid * session to be more precise. False is returned if the method only * needs application authentication. */ public byte getAuthenticationType() { return mAuthenticationType; } /** * Gets the request ID of this request. * * @return The unique request ID for this request. */ public int getRequestId() { return mRequestId; } /** * Sets the request ID for this request. * * @param requestId The request ID to set. */ public void setRequestId(int requestId) { mRequestId = requestId; } /** * Gets the time stamp when this request's hash was calculated. * * @return The time stamp representing the creation date of this request. */ public long getAuthTimestamp() { return mAuthTimestamp; } /** * Gets the time stamp when this request was created. * * @return The time stamp representing the creation date of this request. */ public long getCreationTimestamp() { return mCreationTimestamp; } /** * Gets the set timeout. * * @return the timeout in milliseconds, -1 if not set. */ public long getTimeout() { return mTimeout; } /** * Gets the calculated expiry date. * * @return the expiry date in milliseconds, -1 if not set. */ public long getExpiryDate() { return mExpiryDate; } /** * Overwrites the timestamp if we need to wait one more second due to an * issue on the backend. * * @param timestamp The timestamp in milliseconds(!) to overwrite with. */ /* public void overwriteTimetampBecauseOfBadSessionErrorOnBackend(long timestamp) { mAuthTimestamp = timestamp; if (null != mParameters) { if (null != mParameters.get("timestamp")) { String ts = "" + (timestamp / 1000); mParameters.put("timestamp", ts); } } } */ /** * Returns the API call this request will use. * * @return The API method name this request will call. */ public String getApiMethodName() { return mApiMethodName; } /** * Returns true if the method is a fire and forget method. Theses methods * can be removed from the request queue as soon as they have been sent out. * * @return True if the request is fire and forget, false otherwise. */ public boolean isFireAndForget() { return mIsFireAndForget; } /** * Serializes the request's data structure to the passed output stream * enabling the connection to easily prepare one or multiple) requests. * * @param os The output stream to serialise this request to. * @param writeRpgHeader If true the RPG header is written. */ public void writeToOutputStream(OutputStream os, boolean writeRpgHeader) { if (null == os) { return; } byte[] body; calculateAuth(); try { body = makeBody(); if (!writeRpgHeader) { os.write(body); // writing to the api directly return; } } catch (IOException ioe) { HttpConnectionThread.logE("Request.writeToOutputStream()", "Failed writing standard API request: " + mRequestId, ioe); return; } int requestType = 0; if (mType == Request.Type.PRESENCE_LIST) { requestType = RpgMessageTypes.RPG_GET_PRESENCE; } else if (mType == Request.Type.AVAILABILITY) { requestType = RpgMessageTypes.RPG_SET_AVAILABILITY; } else if (mType == Request.Type.CREATE_CONVERSATION) { requestType = RpgMessageTypes.RPG_CREATE_CONV; } else if (mType == Request.Type.SEND_CHAT_MESSAGE) { requestType = RpgMessageTypes.RPG_SEND_IM; } else if (mType == Request.Type.EXTERNAL_RPG_RESPONSE) { requestType = RpgMessageTypes.RPG_EXT_REQ; } else { requestType = RpgMessageTypes.RPG_INT_REQ; } byte[] message = RpgMessage.createRpgMessage(body, requestType, mRequestId); try { os.write(message); } catch (IOException ioe) { HttpConnectionThread.logE("Request.writeToOutputStream()", "Failed writing RPG request: " + mRequestId, ioe); } } /** * Creates the body of the request using the parameter list. * * @return payload The hessian encoded payload of this request body. * @throws IOException Thrown if anything goes wrong using the hessian * encoder. */ private byte[] makeBody() throws IOException { // XXX this whole method needs to go or at least be changed into a // bytearray outputstream byte[] payload = HessianEncoder.createHessianByteArray(mApiMethodName, mParameters); if (payload == null) { return null; } payload[1] = (byte)1; // TODO we need to change this if we want to use a // baos payload[2] = (byte)0; return payload; } /** * Gets the auth of this request. Prior to the the * writeToOutputStream()-method must have been called. * * @return The auth of this request or null if it was not calculated before. */ public String getAuth() { return (String)mParameters.get("auth"); } /** * Calculate the Auth value for this Requester. TODO: Throttle by * timestamp/function to prevent automatic backend log out */ private void calculateAuth() { String ts = null; if (null != mParameters) { ts = (String)mParameters.get("timestamp"); } if (null == ts) { mAuthTimestamp = System.currentTimeMillis(); ts = "" + (mAuthTimestamp / 1000); } AuthSessionHolder session = LoginEngine.getSession(); if (session != null) { addData("auth", SettingsManager.getProperty(Settings.APP_KEY_ID) + "::" + session.sessionID + "::" + ts); } else { addData("auth", SettingsManager.getProperty(Settings.APP_KEY_ID) + "::" + ts); } addData("auth", AuthUtils.calculateAuth(mApiMethodName, mParameters, ts, session)); /** * if (mNeedsUserAuthentication) { addData("auth", * AuthUtils.calculateAuth(mApiMethodName, mParameters, ts, session)); } * else { // create the final auth without the session addData("auth", * AuthUtils.calculateAuth(mApiMethodName, mParameters, ts, null)); } */ } /** * Calculates the expiry date based on the timeout. TODO: should have * instead an execute() method to call when performing the request. it would * set the request to active, calculates the expiry date, etc... */ public void calculateExpiryDate() { if (mTimeout > 0) { mExpiryDate = System.currentTimeMillis() + mTimeout; } } diff --git a/src/com/vodafone360/people/service/io/ResponseQueue.java b/src/com/vodafone360/people/service/io/ResponseQueue.java index 42f2ce5..4951480 100644 --- a/src/com/vodafone360/people/service/io/ResponseQueue.java +++ b/src/com/vodafone360/people/service/io/ResponseQueue.java @@ -1,265 +1,267 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.util.ArrayList; import java.util.List; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.LogUtils; /** * Queue of responses received from server. These may be either responses to * requests issued by the People client or unsolicited ('Push') messages. The * content of these Responses will have already been decoded by the * DecoderThread and converted to data-types understood by the People Client. */ public class ResponseQueue { /** * The list of responses held by this queue. An array-list of Responses. */ private final List<DecodedResponse> mResponses = new ArrayList<DecodedResponse>(); /** * The engine manager holding the various engines to cross check where * responses belong to. */ private EngineManager mEngMgr = null; /** * Class encapsulating a decoded response from the server A Response * contains; a request id which should match a request id from a request * issued by the People Client (responses to non-RPG requests or * non-solicited messages will not have a request id), the request data, a * list of decoded BaseDataTypes generated from the response content and an * engine id informing the framework which engine the response should be * routed to. */ public static class DecodedResponse { public static enum ResponseType { /** An unknown response in case anything went wrong. */ UNKNOWN, /** A response for a request that timed out. */ SERVER_ERROR, /** A response that timed out before it arrived from the server. */ TIMED_OUT_RESPONSE, /** Represents a push message that was pushed by the server */ PUSH_MESSAGE, /** The response type for available identities. */ GET_AVAILABLE_IDENTITIES_RESPONSE, /** The response type for my identities. */ GET_MY_IDENTITIES_RESPONSE, /** The response type for set identity capability */ SET_IDENTITY_CAPABILITY_RESPONSE, /** The response type for validate identity credentials */ VALIDATE_IDENTITY_CREDENTIALS_RESPONSE, /** The response type for get activities calls. */ GET_ACTIVITY_RESPONSE, /** The response type for get session by credentials calls. */ LOGIN_RESPONSE, /** The response type for bulkupdate contacts calls. */ BULKUPDATE_CONTACTS_RESPONSE, /** The response type for get contacts changes calls. */ GET_CONTACTCHANGES_RESPONSE, /** The response type for get get me calls. */ GETME_RESPONSE, /** The response type for get contact group relation calls. */ GET_CONTACT_GROUP_RELATIONS_RESPONSE, /** The response type for get groups calls. */ GET_GROUPS_RESPONSE, /** The response type for add contact calls. */ ADD_CONTACT_RESPONSE, /** The response type for signup user crypted calls. */ SIGNUP_RESPONSE, /** The response type for get public key calls. */ RETRIEVE_PUBLIC_KEY_RESPONSE, /** The response type for delete contacts calls. */ DELETE_CONTACT_RESPONSE, /** The response type for delete contact details calls. */ DELETE_CONTACT_DETAIL_RESPONSE, /** The response type for get presence calls. */ GET_PRESENCE_RESPONSE, /** The response type for create conversation calls. */ CREATE_CONVERSATION_RESPONSE, /** The response type for get t&cs. */ GET_T_AND_C_RESPONSE, /** The response type for get privacy statement. */ - GET_PRIVACY_STATEMENT_RESPONSE; + GET_PRIVACY_STATEMENT_RESPONSE, + /** The response type for removing the identity. */ + DELETE_IDENTITY_RESPONSE; // TODO add more types here and remove them from the BaseDataType. Having them in ONE location is better than in dozens!!! } /** The type of the response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ private int mResponseType; /** The request ID the response came in for. */ public Integer mReqId; /** The response items (e.g. identities of a getAvailableIdentities call) to store for the response. */ public List<BaseDataType> mDataTypes = new ArrayList<BaseDataType>(); /** The ID of the engine the response should be worked off in. */ public EngineId mSource; /** * Constructs a response object with request ID, the data and the engine * ID the response belongs to. * * @param reqId The corresponding request ID for the response. * @param data The data of the response. * @param source The originating engine ID. * @param responseType The response type. Values can be found in Response.ResponseType. * */ public DecodedResponse(Integer reqId, List<BaseDataType> data, EngineId source, final int responseType) { mReqId = reqId; mDataTypes = data; mSource = source; mResponseType = responseType; } /** * The response type for this response. The types are defined in Response.ResponseType. * * @return The response type of this response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ public int getResponseType() { return mResponseType; } } /** * Protected constructor to highlight the singleton nature of this class. */ protected ResponseQueue() { } /** * Gets an instance of the ResponseQueue as part of the singleton pattern. * * @return The instance of ResponseQueue. */ public static ResponseQueue getInstance() { return ResponseQueueHolder.rQueue; } /** * Use Initialization on demand holder pattern */ private static class ResponseQueueHolder { private static final ResponseQueue rQueue = new ResponseQueue(); } /** * Adds a response item to the queue. * * @param reqId The request ID to add the response for. * @param data The response data to add to the queue. * @param source The corresponding engine that fired off the request for the * response. */ public void addToResponseQueue(final DecodedResponse response) { synchronized (QueueManager.getInstance().lock) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.UNKNOWN_DATA_TYPE, response.mDataTypes); if (status == ServiceStatus.ERROR_INVALID_SESSION) { EngineManager em = EngineManager.getInstance(); if (em != null) { LogUtils.logE("Logging out the current user because of invalide session"); em.getLoginEngine().logoutAndRemoveUser(); return; } } mResponses.add(response); Request request = RequestQueue.getInstance().removeRequest(response.mReqId); if (request != null) { // we suppose the response being handled by the same engine // that issued the request with the given id response.mSource = request.mEngineId; } mEngMgr = EngineManager.getInstance(); if (mEngMgr != null) { mEngMgr.onCommsInMessage(response.mSource); } } } /** * Retrieves the next response in the list if there is one. * * @param source The originating engine id that requested this response. * @return Response The first response that matches the given engine or null * if no response was found. */ public DecodedResponse getNextResponse(EngineId source) { DecodedResponse resp = null; for (int i = 0; i < mResponses.size(); i++) { resp = mResponses.get(i); if (resp.mSource == source) { mResponses.remove(i); if (source != null) { LogUtils.logV("ResponseQueue.getNextResponse() Returning a response to engine[" + source.name() + "]"); } return resp; } } return null; } /** * Get number of items currently in the response queue. * * @return number of items currently in the response queue. */ private int responseCount() { return mResponses.size(); } /** * Test if we have response for the specified request id. * * @param reqId Request ID. * @return true If we have a response for this ID. */ protected synchronized boolean responseExists(int reqId) { boolean exists = false; for (int i = 0; i < responseCount(); i++) { if (mResponses.get(i).mReqId != null && mResponses.get(i).mReqId.intValue() == reqId) { exists = true; break; } } return exists; } } diff --git a/src/com/vodafone360/people/service/io/api/Identities.java b/src/com/vodafone360/people/service/io/api/Identities.java index 5d898ce..486a2ce 100644 --- a/src/com/vodafone360/people/service/io/api/Identities.java +++ b/src/com/vodafone360/people/service/io/api/Identities.java @@ -1,214 +1,262 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io.api; import java.util.Hashtable; import java.util.List; import java.util.Map; import com.vodafone360.people.Settings; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.utils.LogUtils; /** * Implementation of Now+ Identities APIs (used for access to 3rd party accounts * such as Facebook). */ public class Identities { private final static String FUNCTION_GET_AVAILABLE_IDENTITIES = "identities/getavailableidentities"; private final static String FUNCTION_GET_MY_IDENTITIES = "identities/getmyidentities"; // AA private final static String FUNCTION_SET_IDENTITY_CAPABILITY_STATUS = // "identities/setidentitycapabilitystatus"; private final static String FUNCTION_SET_IDENTITY_STATUS = "identities/setidentitystatus"; private final static String FUNCTION_VALIDATE_IDENTITY_CREDENTIALS = "identities/validateidentitycredentials"; + private final static String FUNCTION_DELETE_IDENITY = "identities/deleteidentity"; + public final static String ENABLE_IDENTITY = "enable"; public final static String DISABLE_IDENTITY = "disable"; //public final static String SUSPENDED_IDENTITY = "suspended"; /** * Implementation of identities/getavailableidentities API. Parameters are; * [auth], Map<String, List<String>> filterlist [opt] * * @param engine handle to IdentitiesEngine * @param filterlist List of filters the get identities request is filtered * against. * @return request id generated for this request */ public static int getAvailableIdentities(BaseEngine engine, Map<String, List<String>> filterlist) { if (LoginEngine.getSession() == null) { LogUtils.logE("Identities.getAvailableIdentities() Invalid session, return -1"); return -1; } Request request = new Request(FUNCTION_GET_AVAILABLE_IDENTITIES, Request.Type.GET_AVAILABLE_IDENTITIES, engine.engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); if (filterlist != null) { request.addData("filterlist", ApiUtils.createHashTable(filterlist)); } QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } /** * Implementation of identities/getmyidentities API. Parameters are; [auth], * Map<String, List<String>> filterlist [opt] * * @param engine handle to IdentitiesEngine * @param filterlist List of filters the get identities request is filtered * against. * @return request id generated for this request */ public static int getMyIdentities(BaseEngine engine, Map<String, List<String>> filterlist) { if (LoginEngine.getSession() == null) { LogUtils.logE("Identities.getMyIdentities() Invalid session, return -1"); return -1; } Request request = new Request(FUNCTION_GET_MY_IDENTITIES, Request.Type.GET_MY_IDENTITIES, engine .engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); if (filterlist != null) { request.addData("filterlist", ApiUtils.createHashTable(filterlist)); } QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } /** * @param engine * @param network * @param identityid * @param identityStatus * @return */ public static int setIdentityStatus(BaseEngine engine, String network, String identityid, String identityStatus) { if (LoginEngine.getSession() == null) { LogUtils.logE("Identities.setIdentityStatus() Invalid session, return -1"); return -1; } if (identityid == null) { LogUtils.logE("Identities.setIdentityStatus() identityid cannot be NULL"); return -1; } if (network == null) { LogUtils.logE("Identities.setIdentityStatus() network cannot be NULL"); return -1; } if (identityStatus == null) { LogUtils.logE("Identities.setIdentityStatus() identity status cannot be NULL"); return -1; } Request request = new Request(FUNCTION_SET_IDENTITY_STATUS, Request.Type.EXPECTING_STATUS_ONLY, engine.engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); request.addData("network", network); request.addData("identityid", identityid); request.addData("status", identityStatus); QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } /** * Implementation of identities/validateidentitycredentials API. Parameters * are; [auth], Boolean dryrun [opt], String network [opt], String username, * String password, String server [opt], String contactdetail [opt], Map * identitycapabilitystatus [opt] * * @param engine handle to IdentitiesEngine * @param dryrun Whether this is a dry-run request. * @param network Name of network. * @param username User-name. * @param password Password. * @param server * @param contactdetail * @param identitycapabilitystatus Capabilities for this identity/network. * @return request id generated for this request */ public static int validateIdentityCredentials(BaseEngine engine, Boolean dryrun, String network, String username, String password, String server, String contactdetail, Map<String, Boolean> identitycapabilitystatus) { if (LoginEngine.getSession() == null) { LogUtils.logE("Identities.validateIdentityCredentials() Invalid session, return -1"); return -1; } if (network == null) { LogUtils.logE("Identities.validateIdentityCredentials() network cannot be NULL"); return -1; } if (username == null) { LogUtils.logE("Identities.validateIdentityCredentials() username cannot be NULL"); return -1; } if (password == null) { LogUtils.logE("Identities.validateIdentityCredentials() password cannot be NULL"); return -1; } Request request = new Request(FUNCTION_VALIDATE_IDENTITY_CREDENTIALS, Request.Type.EXPECTING_STATUS_ONLY, engine.engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); if (dryrun != null) { request.addData("dryrun", dryrun); } request.addData("network", network); request.addData("username", username); request.addData("password", password); if (server != null) { request.addData("server", server); } if (contactdetail != null) { request.addData("contactdetail", contactdetail); } if (identitycapabilitystatus != null) { request.addData("identitycapabilitystatus", new Hashtable<String, Object>( identitycapabilitystatus)); } QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } + + /** + * Implementation of identities/deleteIdentity API. Parameters are; [auth], + * String network, String identityid. + * + * @param engine + * Handle to IdentitiesEngine. + * @param network + * Name of network. + * @param identityId + * The user's identity ID. + * @return requestId The request ID generated for this request. + */ + + public static int deleteIdentity(final BaseEngine engine, + final String network, final String identityId) { + if (LoginEngine.getSession() == null) { + LogUtils + .logE("Identities.deleteIdentity() Invalid session, return -1"); + return -1; + } + if (network == null) { + LogUtils.logE("Identities.deleteIdentity() network cannot be NULL"); + return -1; + } + if (identityId == null) { + LogUtils + .logE("Identities.deleteIdentity() identityId cannot be NULL"); + return -1; + } + + Request request = new Request(FUNCTION_DELETE_IDENITY, + Request.Type.DELETE_IDENTITY, engine.engineId(), false, + Settings.API_REQUESTS_TIMEOUT_IDENTITIES); + request.addData("network", network); + request.addData("identityid", identityId); + + LogUtils.logI("Identity to be removed : " + network + " : " + + identityId); + + QueueManager queue = QueueManager.getInstance(); + int requestId = queue.addRequest(request); + queue.fireQueueStateChanged(); + return requestId; + + } } diff --git a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java index e8aa994..8089e46 100644 --- a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java +++ b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java @@ -1,556 +1,563 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.utils.hessian; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Vector; import java.util.zip.GZIPInputStream; import com.caucho.hessian.micro.MicroHessianInput; import com.vodafone360.people.datatypes.ActivityItem; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactChanges; import com.vodafone360.people.datatypes.ContactDetailDeletion; import com.vodafone360.people.datatypes.ContactListResponse; import com.vodafone360.people.datatypes.Conversation; import com.vodafone360.people.datatypes.ExternalResponseObject; import com.vodafone360.people.datatypes.Identity; +import com.vodafone360.people.datatypes.IdentityDeletion; import com.vodafone360.people.datatypes.ItemList; import com.vodafone360.people.datatypes.PresenceList; import com.vodafone360.people.datatypes.PublicKeyDetails; import com.vodafone360.people.datatypes.PushAvailabilityEvent; import com.vodafone360.people.datatypes.PushChatConversationEvent; import com.vodafone360.people.datatypes.PushChatMessageEvent; import com.vodafone360.people.datatypes.PushClosedConversationEvent; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.SimpleText; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.datatypes.UserProfile; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.io.rpg.RpgPushMessage; import com.vodafone360.people.utils.CloseUtils; import com.vodafone360.people.utils.LogUtils; /** * Hessian decoding . TODO: Currently casting every response to a Map, losing * for example push events "c0" which only contains a string. This may need a * fix. */ public class HessianDecoder { private static final String KEY_ACTIVITY_LIST = "activitylist"; private static final String KEY_AVAILABLE_IDENTITY_LIST = "availableidentitylist"; private static final String KEY_CONTACT_ID_LIST = "contactidlist"; private static final String KEY_CONTACT_LIST = "contactlist"; private static final String KEY_IDENTITY_LIST = "identitylist"; private static final String KEY_SESSION = "session"; private static final String KEY_USER_PROFILE = "userprofile"; private static final String KEY_USER_PROFILE_LIST = "userprofilelist"; /** * The MicroHessianInput is here declared as member and will be reused * instead of making new instances on every need */ private MicroHessianInput mMicroHessianInput = new MicroHessianInput(); /** * * Parse Hessian encoded byte array placing parsed contents into List. * * @param requestId The request ID that the response was received for. * @param data byte array containing Hessian encoded data * @param type Event type Shows whether we have a push or common message type. * @param isZipped True if the response is gzipped, otherwise false. * @param engineId The engine ID the response should be reported back to. * * @return The response containing the decoded objects. * * @throws IOException Thrown if there is something wrong with reading the (gzipped) hessian encoded input stream. * */ public DecodedResponse decodeHessianByteArray(int requestId, byte[] data, Request.Type type, boolean isZipped, EngineId engineId) throws IOException { InputStream is = null; InputStream bis = null; if (isZipped == true) { LogUtils.logV("HessianDecoder.decodeHessianByteArray() Handle zipped data"); bis = new ByteArrayInputStream(data); is = new GZIPInputStream(bis, data.length); } else { LogUtils.logV("HessianDecoder.decodeHessianByteArray() Handle non-zipped data"); is = new ByteArrayInputStream(data); } DecodedResponse response = null; mMicroHessianInput.init(is); LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); try { response = decodeResponse(is, requestId, type, isZipped, engineId); } catch (IOException e) { LogUtils.logE("HessianDecoder.decodeHessianByteArray() " + "IOException during decodeResponse", e); } CloseUtils.close(bis); CloseUtils.close(is); return response; } @SuppressWarnings("unchecked") public Hashtable<String, Object> decodeHessianByteArrayToHashtable(byte[] data) throws IOException { InputStream is = new ByteArrayInputStream(data); mMicroHessianInput.init(is); Object obj = null; obj = mMicroHessianInput.decodeTag(); if (obj instanceof Hashtable) { return (Hashtable<String, Object>)obj; } else { return null; } } /** * * * * @param is * @param requestId * @param type * @param isZipped * @param engineId * * @return * * @throws IOException */ @SuppressWarnings("unchecked") private DecodedResponse decodeResponse(InputStream is, int requestId, Request.Type type, boolean isZipped, EngineId engineId) throws IOException { boolean usesReplyTag = false; int responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); List<BaseDataType> resultList = new ArrayList<BaseDataType>(); mMicroHessianInput.init(is); // skip start int tag = is.read(); // initial map tag or fail if (tag == 'r') { // reply / response is.read(); // read major and minor is.read(); tag = is.read(); // read next tag usesReplyTag = true; } if (tag == -1) { return null; } // check for fail // read reason string and throw exception if (tag == 'f') { ServerError zybErr = new ServerError(mMicroHessianInput.readFault().errString()); resultList.add(zybErr); DecodedResponse decodedResponse = new DecodedResponse(requestId, resultList, engineId, DecodedResponse.ResponseType.SERVER_ERROR.ordinal()); return decodedResponse; } // handle external response // this is not wrapped up in a hashtable if (type == Request.Type.EXTERNAL_RPG_RESPONSE) { LogUtils.logV("HessianDecoder.decodeResponse() EXTERNAL_RPG_RESPONSE"); if (tag != 'I') { LogUtils.logE("HessianDecoder.decodeResponse() " + "tag!='I' Unexpected Hessian type:" + tag); } parseExternalResponse(resultList, is, tag); DecodedResponse decodedResponse = new DecodedResponse(requestId, resultList, engineId, DecodedResponse.ResponseType.SERVER_ERROR.ordinal()); return decodedResponse; } // internal response: should contain a Map type - i.e. Hashtable if (tag != 'M') { LogUtils .logE("HessianDecoder.decodeResponse() tag!='M' Unexpected Hessian type:" + tag); throw new IOException("Unexpected Hessian type"); } else if ((type == Request.Type.COMMON) || (type == Request.Type.SIGN_IN) || // if we have a common request or sign in request (type == Request.Type.GET_MY_IDENTITIES) || (type == Request.Type.GET_AVAILABLE_IDENTITIES)) { Hashtable<String, Object> map = (Hashtable<String, Object>)mMicroHessianInput .readHashMap(tag); if (null == map) { return null; } if (map.containsKey(KEY_SESSION)) { AuthSessionHolder auth = new AuthSessionHolder(); Hashtable<String, Object> authHash = (Hashtable<String, Object>)map .get(KEY_SESSION); resultList.add(auth.createFromHashtable(authHash)); responseType = DecodedResponse.ResponseType.LOGIN_RESPONSE.ordinal(); } else if (map.containsKey(KEY_CONTACT_LIST)) { // contact list getContacts(resultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); responseType = DecodedResponse.ResponseType.GET_CONTACTCHANGES_RESPONSE.ordinal(); } else if (map.containsKey(KEY_USER_PROFILE_LIST)) { Vector<Hashtable<String, Object>> upVect = (Vector<Hashtable<String, Object>>)map .get(KEY_USER_PROFILE_LIST); for (Hashtable<String, Object> obj : upVect) { resultList.add(UserProfile.createFromHashtable(obj)); } responseType = DecodedResponse.ResponseType.GETME_RESPONSE.ordinal(); } else if (map.containsKey(KEY_USER_PROFILE)) { Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map .get(KEY_USER_PROFILE); resultList.add(UserProfile.createFromHashtable(userProfileHash)); responseType = DecodedResponse.ResponseType.GETME_RESPONSE.ordinal(); } else if ((map.containsKey(KEY_IDENTITY_LIST)) // we have identity items in the map which we can parse || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { int identityType = 0; Vector<Hashtable<String, Object>> idcap = null; if (map.containsKey(KEY_IDENTITY_LIST)) { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); identityType = BaseDataType.MY_IDENTITY_DATA_TYPE; responseType = DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal(); } else { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); identityType = BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE; responseType = DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal(); } for (Hashtable<String, Object> obj : idcap) { Identity id = new Identity(identityType); resultList.add(id.createFromHashtable(obj)); } } else if (type == Request.Type.GET_AVAILABLE_IDENTITIES) { // we have an available identities response, but it is empty responseType = DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal(); } else if (type == Request.Type.GET_MY_IDENTITIES) { // we have a my identities response, but it is empty responseType = DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal(); } else if (map.containsKey(KEY_ACTIVITY_LIST)) { Vector<Hashtable<String, Object>> activityList = (Vector<Hashtable<String, Object>>)map .get(KEY_ACTIVITY_LIST); for (Hashtable<String, Object> obj : activityList) { resultList.add(ActivityItem.createFromHashtable(obj)); } responseType = DecodedResponse.ResponseType.GET_ACTIVITY_RESPONSE.ordinal(); } } else if ((type != Request.Type.COMMON) && (type != Request.Type.SIGN_IN)) { // get initial hash table // TODO: we cast every response to a Map, losing e.g. push event // "c0" which only contains a string - to fix Hashtable<String, Object> hash = (Hashtable<String, Object>)mMicroHessianInput .decodeType(tag); responseType = decodeResponseByRequestType(resultList, hash, type); } if (usesReplyTag) { is.read(); // read the last 'z' } DecodedResponse decodedResponse = new DecodedResponse(requestId, resultList, engineId, responseType); return decodedResponse; } private void parseExternalResponse(List<BaseDataType> clist, InputStream is, int tag) throws IOException { mMicroHessianInput.init(is); ExternalResponseObject resp = new ExternalResponseObject(); // we already read the 'I' in the decodeResponse()-method // now we read and check the response code if (mMicroHessianInput.readInt(tag) != 200) { return; } try { resp.mMimeType = mMicroHessianInput.readString(); } catch (IOException ioe) { LogUtils.logE("Failed to parse hessian string."); return; } // read data - could be gzipped try { resp.mBody = mMicroHessianInput.readBytes(); } catch (IOException ioe) { LogUtils.logE("Failed to read bytes."); return; } LogUtils.logI("HessianDecoder.parseExternalResponse()" + " Parsed external object with length: " + resp.mBody.length); clist.add(resp); } /** * * Parses the hashtables retrieved from the hessian payload that came from the server and * returns a type for it. * * @param clist The list that will be populated with the data types. * @param hash The hash table that contains the parsed date returned by the backend. * @param type The type of the request that was sent, e.g. get contacts changes. * * @return The type of the response that was parsed (to be found in DecodedResponse.ResponseType). * */ private int decodeResponseByRequestType(List<BaseDataType> clist, Hashtable<String, Object> hash, Request.Type type) { int responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); switch (type) { case CONTACT_CHANGES_OR_UPDATES: responseType = DecodedResponse.ResponseType.GET_CONTACTCHANGES_RESPONSE.ordinal(); // create ContactChanges ContactChanges contChanges = new ContactChanges(); contChanges = contChanges.createFromHashtable(hash); clist.add(contChanges); break; case ADD_CONTACT: clist.add(Contact.createFromHashtable(hash)); responseType = DecodedResponse.ResponseType.ADD_CONTACT_RESPONSE.ordinal(); break; case SIGN_UP: clist.add(Contact.createFromHashtable(hash)); responseType = DecodedResponse.ResponseType.SIGNUP_RESPONSE.ordinal(); break; case RETRIEVE_PUBLIC_KEY: // AA define new object type clist.add(PublicKeyDetails.createFromHashtable(hash)); responseType = DecodedResponse.ResponseType.RETRIEVE_PUBLIC_KEY_RESPONSE.ordinal(); break; case CONTACT_DELETE: ContactListResponse cresp = new ContactListResponse(); cresp.createFromHashTable(hash); // add ids @SuppressWarnings("unchecked") Vector<Long> contactIds = (Vector<Long>)hash.get(KEY_CONTACT_ID_LIST); if (contactIds != null) { for (Long cid : contactIds) { cresp.mContactIdList.add((cid).intValue()); } } clist.add(cresp); responseType = DecodedResponse.ResponseType.DELETE_CONTACT_RESPONSE.ordinal(); break; case CONTACT_DETAIL_DELETE: ContactDetailDeletion cdel = new ContactDetailDeletion(); clist.add(cdel.createFromHashtable(hash)); responseType = DecodedResponse.ResponseType.DELETE_CONTACT_DETAIL_RESPONSE.ordinal(); break; case CONTACT_GROUP_RELATION_LIST: ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); groupRelationList.populateFromHashtable(hash); clist.add(groupRelationList); responseType = DecodedResponse.ResponseType.GET_CONTACT_GROUP_RELATIONS_RESPONSE.ordinal(); break; case CONTACT_GROUP_RELATIONS: ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); groupRelationsList.populateFromHashtable(hash); clist.add(groupRelationsList); responseType = DecodedResponse.ResponseType.GET_CONTACT_GROUP_RELATIONS_RESPONSE.ordinal(); break; case GROUP_LIST: ItemList zyblist = new ItemList(ItemList.Type.group_privacy); zyblist.populateFromHashtable(hash); clist.add(zyblist); responseType = DecodedResponse.ResponseType.GET_GROUPS_RESPONSE.ordinal(); break; case ITEM_LIST_OF_LONGS: ItemList listOfLongs = new ItemList(ItemList.Type.long_value); listOfLongs.populateFromHashtable(hash); clist.add(listOfLongs); responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); // TODO break; case STATUS_LIST: // TODO status and status list are used by many requests as a type. each request should have its own type however! ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); zybstatlist.populateFromHashtable(hash); clist.add(zybstatlist); responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); // TODO break; case STATUS: StatusMsg s = new StatusMsg(); s.mStatus = true; clist.add(s); responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); // TODO break; case TEXT_RESPONSE_ONLY: Object val = hash.get("result"); if (val != null && val instanceof String) { SimpleText txt = new SimpleText(); txt.addText((String)val); clist.add(txt); } responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); // TODO break; case EXPECTING_STATUS_ONLY: StatusMsg statMsg = new StatusMsg(); clist.add(statMsg.createFromHashtable(hash)); responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); // TODO break; case PRESENCE_LIST: PresenceList mPresenceList = new PresenceList(); mPresenceList.createFromHashtable(hash); clist.add(mPresenceList); responseType = DecodedResponse.ResponseType.GET_PRESENCE_RESPONSE.ordinal(); break; case PUSH_MSG: // parse content of RPG Push msg parsePushMessage(clist, hash); responseType = DecodedResponse.ResponseType.PUSH_MESSAGE.ordinal(); break; case CREATE_CONVERSATION: Conversation mConversation = new Conversation(); mConversation.createFromHashtable(hash); clist.add(mConversation); responseType = DecodedResponse.ResponseType.CREATE_CONVERSATION_RESPONSE.ordinal(); break; + case DELETE_IDENTITY: + IdentityDeletion mIdenitityDeletion = new IdentityDeletion(); + clist.add(mIdenitityDeletion.createFromHashtable(hash)); + responseType = DecodedResponse.ResponseType.DELETE_IDENTITY_RESPONSE + .ordinal(); + break; default: LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" + type.name() + "]"); } return responseType; } private void getContacts(List<BaseDataType> clist, Vector<?> cont) { for (Object obj : cont) { @SuppressWarnings("unchecked") Hashtable<String, Object> hash = (Hashtable<String, Object>)obj; clist.add(Contact.createFromHashtable(hash)); } } private void parsePushMessage(List<BaseDataType> list, Hashtable<String, Object> hash) { RpgPushMessage push = RpgPushMessage.createFromHashtable(hash); parsePushPayload(push, list); } private void parsePushPayload(RpgPushMessage msg, List<BaseDataType> list) { // convert push msg type string to PushMsgType PushMessageTypes type = msg.mType; EngineId engineId = EngineId.UNDEFINED; if (type != null) { switch (type) { case CHAT_MESSAGE: LogUtils.logV("Parse incomming chat_message"); engineId = EngineId.PRESENCE_ENGINE; list.add(new PushChatMessageEvent(msg, engineId)); return; case AVAILABILITY_STATE_CHANGE: LogUtils.logV("Parse availability state change:"); engineId = EngineId.PRESENCE_ENGINE; list.add(PushAvailabilityEvent.createPushEvent(msg, engineId)); return; case START_CONVERSATION: LogUtils.logV("Parse new conversation event:"); engineId = EngineId.PRESENCE_ENGINE; list.add(new PushChatConversationEvent(msg, engineId)); return; case CLOSED_CONVERSATION: LogUtils.logV("Parse closed conversation event:"); engineId = EngineId.PRESENCE_ENGINE; list.add(new PushClosedConversationEvent(msg, engineId)); return; case CONVERSATION_END: break; // API events create push message type case PROFILE_CHANGE: engineId = EngineId.SYNCME_ENGINE; break; case CONTACTS_CHANGE: engineId = EngineId.CONTACT_SYNC_ENGINE; break; case TIMELINE_ACTIVITY_CHANGE: case STATUS_ACTIVITY_CHANGE: engineId = EngineId.ACTIVITIES_ENGINE; break; case FRIENDSHIP_REQUEST_RECEIVED: break; case IDENTITY_CHANGE: engineId = EngineId.IDENTITIES_ENGINE; break; case IDENTITY_NETWORK_CHANGE: engineId = EngineId.IDENTITIES_ENGINE; break; case SYSTEM_NOTIFICATION: LogUtils.logE("SYSTEM_NOTIFICATION push msg:" + msg.mHash); list.add(SystemNotification.createFromHashtable(msg.mHash, engineId)); return; default: } list.add(PushEvent.createPushEvent(msg, engineId)); } } }
360/360-Engine-for-Android
14bc2606cc5088f088156b901277434aee2056fc
Deletion of timeline items containing a # fixed
diff --git a/src/com/vodafone360/people/database/tables/ActivitiesTable.java b/src/com/vodafone360/people/database/tables/ActivitiesTable.java index 42ad971..d13f41b 100644 --- a/src/com/vodafone360/people/database/tables/ActivitiesTable.java +++ b/src/com/vodafone360/people/database/tables/ActivitiesTable.java @@ -249,1025 +249,1025 @@ public abstract class ActivitiesTable { sb.append(mLocalActivityId); sb.append("], mTimestamp["); sb.append(mTimestamp); sb.append("], mContactName["); sb.append(mContactName); sb.append("], mHasAvatar["); sb.append(mHasAvatar); sb.append("], mType["); sb.append(mType); sb.append("], mLocalContactId["); sb.append(mLocalContactId); sb.append("], mContactNetwork["); sb.append(mContactNetwork); sb.append("], mTitle["); sb.append(mTitle); sb.append("], mDescription["); sb.append(mDescription); sb.append("], mNativeItemType["); sb.append(mNativeItemType); sb.append("], mNativeItemId["); sb.append(mNativeItemId); sb.append("], mContactId["); sb.append(mContactId); sb.append("], mUserId["); sb.append(mUserId); sb.append("], mNativeThreadId["); sb.append(mNativeThreadId); sb.append("], mContactAddress["); sb.append(mContactAddress); sb.append("], mIncoming["); sb.append(mIncoming); sb.append("]]");; return sb.toString(); } @Override public final boolean equals(final Object object) { if (TimelineSummaryItem.class != object.getClass()) { return false; } TimelineSummaryItem item = (TimelineSummaryItem) object; return mLocalActivityId.equals(item.mLocalActivityId) && mTimestamp.equals(item.mTimestamp) && mContactName.equals(item.mContactName) && mHasAvatar == item.mHasAvatar && mType.equals(item.mType) && mLocalContactId.equals(item.mLocalContactId) && mContactNetwork.equals(item.mContactNetwork) && mTitle.equals(item.mTitle) && mDescription.equals(item.mDescription) && mNativeItemType.equals(item.mNativeItemType) && mNativeItemId.equals(item.mNativeItemId) && mContactId.equals(item.mContactId) && mUserId.equals(item.mUserId) && mNativeThreadId.equals(item.mNativeThreadId) && mContactAddress.equals(item.mContactAddress) && mIncoming.equals(item.mIncoming); } }; /** Number of milliseconds in a day. **/ private static final int NUMBER_OF_MS_IN_A_DAY = 24 * 60 * 60 * 1000; /** Number of milliseconds in a second. **/ private static final int NUMBER_OF_MS_IN_A_SECOND = 1000; /*** * Private constructor to prevent instantiation. */ private ActivitiesTable() { // Do nothing. } /** * Create Activities Table. * * @param writeableDb A writable SQLite database. */ public static void create(final SQLiteDatabase writeableDb) { DatabaseHelper.trace(true, "DatabaseHelper.create()"); writeableDb.execSQL("CREATE TABLE " + TABLE_NAME + " (" + Field.LOCAL_ACTIVITY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.ACTIVITY_ID + " LONG, " + Field.TIMESTAMP + " LONG, " + Field.TYPE + " TEXT, " + Field.URI + " TEXT, " + Field.TITLE + " TEXT, " + Field.DESCRIPTION + " TEXT, " + Field.PREVIEW_URL + " TEXT, " + Field.STORE + " TEXT, " + Field.FLAG + " INTEGER, " + Field.PARENT_ACTIVITY + " LONG, " + Field.HAS_CHILDREN + " INTEGER, " + Field.VISIBILITY + " INTEGER, " + Field.MORE_INFO + " TEXT, " + Field.CONTACT_ID + " LONG, " + Field.USER_ID + " LONG, " + Field.CONTACT_NAME + " TEXT, " + Field.LOCAL_CONTACT_ID + " LONG, " + Field.CONTACT_NETWORK + " TEXT, " + Field.CONTACT_ADDRESS + " TEXT, " + Field.CONTACT_AVATAR_URL + " TEXT, " + Field.LATEST_CONTACT_STATUS + " INTEGER, " + Field.NATIVE_ITEM_TYPE + " INTEGER, " + Field.NATIVE_ITEM_ID + " INTEGER, " + Field.NATIVE_THREAD_ID + " INTEGER, " + Field.INCOMING + " INTEGER);"); writeableDb.execSQL("CREATE INDEX " + TABLE_INDEX_NAME + " ON " + TABLE_NAME + " ( " + Field.TIMESTAMP + " )"); } /** * Fetches a comma separated list of table fields which can be used in an * SQL SELECT statement as the query projection. One of the * {@link #getQueryData} methods can used to fetch data from the cursor. * * @return SQL string */ private static String getFullQueryList() { DatabaseHelper.trace(false, "DatabaseHelper.getFullQueryList()"); final StringBuffer fullQuery = StringBufferPool.getStringBuffer(); fullQuery.append(Field.LOCAL_ACTIVITY_ID).append(SqlUtils.COMMA). append(Field.ACTIVITY_ID).append(SqlUtils.COMMA). append(Field.TIMESTAMP).append(SqlUtils.COMMA). append(Field.TYPE).append(SqlUtils.COMMA). append(Field.URI).append(SqlUtils.COMMA). append(Field.TITLE).append(SqlUtils.COMMA). append(Field.DESCRIPTION).append(SqlUtils.COMMA). append(Field.PREVIEW_URL).append(SqlUtils.COMMA). append(Field.STORE).append(SqlUtils.COMMA). append(Field.FLAG).append(SqlUtils.COMMA). append(Field.PARENT_ACTIVITY).append(SqlUtils.COMMA). append(Field.HAS_CHILDREN).append(SqlUtils.COMMA). append(Field.VISIBILITY).append(SqlUtils.COMMA). append(Field.MORE_INFO).append(SqlUtils.COMMA). append(Field.CONTACT_ID).append(SqlUtils.COMMA). append(Field.USER_ID).append(SqlUtils.COMMA). append(Field.CONTACT_NAME).append(SqlUtils.COMMA). append(Field.LOCAL_CONTACT_ID).append(SqlUtils.COMMA). append(Field.CONTACT_NETWORK).append(SqlUtils.COMMA). append(Field.CONTACT_ADDRESS).append(SqlUtils.COMMA). append(Field.CONTACT_AVATAR_URL).append(SqlUtils.COMMA). append(Field.INCOMING); return StringBufferPool.toStringThenRelease(fullQuery); } /** * Fetches activities information from a cursor at the current position. The * {@link #getFullQueryList()} method should be used to make the query. * * @param cursor The cursor returned by the query * @param activityItem An empty activity object that will be filled with the * result * @param activityContact An empty activity contact object that will be * filled */ public static void getQueryData(final Cursor cursor, final ActivityItem activityItem, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityItem. **/ activityItem.localActivityId = SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); activityItem.activityId = SqlUtils.setLong(cursor, Field.ACTIVITY_ID.toString(), null); activityItem.time = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); activityItem.type = SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); activityItem.uri = SqlUtils.setString(cursor, Field.URI.toString()); activityItem.title = SqlUtils.setString(cursor, Field.TITLE.toString()); activityItem.description = SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); activityItem.previewUrl = SqlUtils.setString(cursor, Field.PREVIEW_URL.toString()); activityItem.store = SqlUtils.setString(cursor, Field.STORE.toString()); activityItem.activityFlags = SqlUtils.setInt(cursor, Field.FLAG.toString(), null); activityItem.parentActivity = SqlUtils.setLong(cursor, Field.PARENT_ACTIVITY.toString(), null); activityItem.hasChildren = SqlUtils.setBoolean(cursor, Field.HAS_CHILDREN.toString(), activityItem.hasChildren); activityItem.visibilityFlags = SqlUtils.setInt(cursor, Field.VISIBILITY.toString(), null); // TODO: Field MORE_INFO is not used, consider deleting. /** Populate ActivityContact. **/ getQueryData(cursor, activityContact); } /** * Fetches activities information from a cursor at the current position. The * {@link #getFullQueryList()} method should be used to make the query. * * @param cursor The cursor returned by the query. * @param activityContact An empty activity contact object that will be * filled */ public static void getQueryData(final Cursor cursor, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityContact. **/ activityContact.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); activityContact.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); activityContact.mName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); activityContact.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); activityContact.mNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); activityContact.mAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); activityContact.mAvatarUrl = SqlUtils.setString(cursor, Field.CONTACT_AVATAR_URL.toString()); } /*** * Provides a ContentValues object that can be used to update the table. * * @param item The source activity item * @param contactIdx The index of the contact to use for the update, or null * to exclude contact specific information. * @return ContentValues for use in an SQL update or insert. * @note Items that are NULL will be not modified in the database. */ private static ContentValues fillUpdateData(final ActivityItem item, final Integer contactIdx) { DatabaseHelper.trace(false, "DatabaseHelper.fillUpdateData()"); ContentValues activityItemValues = new ContentValues(); ActivityContact ac = null; if (contactIdx != null) { ac = item.contactList.get(contactIdx); } activityItemValues.put(Field.ACTIVITY_ID.toString(), item.activityId); activityItemValues.put(Field.TIMESTAMP.toString(), item.time); if (item.type != null) { activityItemValues.put(Field.TYPE.toString(), item.type.getTypeCode()); } if (item.uri != null) { activityItemValues.put(Field.URI.toString(), item.uri); } /** TODO: Not sure if we need this. **/ // activityItemValues.put(Field.INCOMING.toString(), false); activityItemValues.put(Field.TITLE.toString(), item.title); activityItemValues.put(Field.DESCRIPTION.toString(), item.description); if (item.previewUrl != null) { activityItemValues.put(Field.PREVIEW_URL.toString(), item.previewUrl); } if (item.store != null) { activityItemValues.put(Field.STORE.toString(), item.store); } if (item.activityFlags != null) { activityItemValues.put(Field.FLAG.toString(), item.activityFlags); } if (item.parentActivity != null) { activityItemValues.put(Field.PARENT_ACTIVITY.toString(), item.parentActivity); } if (item.hasChildren != null) { activityItemValues.put(Field.HAS_CHILDREN.toString(), item.hasChildren); } if (item.visibilityFlags != null) { activityItemValues.put(Field.VISIBILITY.toString(), item.visibilityFlags); } if (ac != null) { activityItemValues.put(Field.CONTACT_ID.toString(), ac.mContactId); activityItemValues.put(Field.USER_ID.toString(), ac.mUserId); activityItemValues.put(Field.CONTACT_NAME.toString(), ac.mName); activityItemValues.put(Field.LOCAL_CONTACT_ID.toString(), ac.mLocalContactId); if (ac.mNetwork != null) { activityItemValues.put(Field.CONTACT_NETWORK.toString(), ac.mNetwork); } if (ac.mAddress != null) { activityItemValues.put(Field.CONTACT_ADDRESS.toString(), ac.mAddress); } if (ac.mAvatarUrl != null) { activityItemValues.put(Field.CONTACT_AVATAR_URL.toString(), ac.mAvatarUrl); } } return activityItemValues; } /** * Fetches a list of status items from the given time stamp. * * @param timeStamp Time stamp in milliseconds * @param readableDb Readable SQLite database * @return A cursor (use one of the {@link #getQueryData} methods to read * the data) */ public static Cursor fetchStatusEventList(final long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchStatusEventList()"); return readableDb.rawQuery("SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + " & " + ActivityItem.STATUS_ITEM + ") AND " + Field.TIMESTAMP + " > " + timeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); } /** * Returns a list of activity IDs already synced, in reverse chronological * order Fetches from the given timestamp. * * @param actIdList An empty list which will be filled with the result * @param timeStamp The time stamp to start the fetch * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus fetchActivitiesIds(final List<Long> actIdList, final Long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchActivitiesIds()"); Cursor cursor = null; try { long queryTimeStamp; if (timeStamp != null) { queryTimeStamp = timeStamp; } else { queryTimeStamp = 0; } cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.TIMESTAMP + " >= " + queryTimeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); while (cursor.moveToNext()) { actIdList.add(cursor.getLong(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchActivitiesIds()" + "Unable to fetch group list", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Adds a list of activities to table. The activities added will be grouped * in the database, based on local contact Id, name or contact address (see * {@link #removeContactGroup(Long, String, Long, int, * TimelineNativeTypes[], SQLiteDatabase)} * for more information on how the grouping works. * * @param actList The list of activities * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus addActivities(final List<ActivityItem> actList, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addActivities()"); SQLiteStatement statement = ContactsTable.fetchLocalFromServerIdStatement(writableDb); for (ActivityItem activity : actList) { try { writableDb.beginTransaction(); if (activity.contactList != null) { int clistSize = activity.contactList.size(); for (int i = 0; i < clistSize; i++) { final ActivityContact activityContact = activity.contactList.get(i); activityContact.mLocalContactId = ContactsTable.fetchLocalFromServerId( activityContact.mContactId, statement); if (activityContact.mLocalContactId == null) { // Just skip activities for which we don't have a corresponding contact // in the database anymore otherwise they will be shown as "Blank name". // This is the same on the web but we could use the provided name instead. continue; } int latestStatusVal = removeContactGroup( activityContact.mLocalContactId, activityContact.mName, activity.time, activity.activityFlags, null, writableDb); ContentValues cv = fillUpdateData(activity, i); cv.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); activity.localActivityId = writableDb.insertOrThrow(TABLE_NAME, null, cv); } } else { activity.localActivityId = writableDb.insertOrThrow( TABLE_NAME, null, fillUpdateData(activity, null)); } if ((activity.localActivityId != null) && (activity.localActivityId < 0)) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } if(statement != null) { statement.close(); statement = null; } return ServiceStatus.SUCCESS; } /** * Deletes all activities from the table. * * @param flag Can be a bitmap of: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * <li>NULL - to delete all activities</li> * </ul> * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteActivities(final Integer flag, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteActivities()"); try { String whereClause = null; if (flag != null) { whereClause = Field.FLAG + "&" + flag; } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } public static ServiceStatus fetchNativeIdsFromLocalContactId(List<Integer > nativeItemIdList, final long localContactId, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNativeIdsFromLocalContactId()"); Cursor cursor = null; try { cursor = readableDb.rawQuery("SELECT " + Field.NATIVE_ITEM_ID + " FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + " = " + localContactId, null); while (cursor.moveToNext()) { nativeItemIdList.add(cursor.getInt(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchNativeIdsFromLocalContactId()" + "Unable to fetch list of NativeIds from localcontactId", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Deletes specified timeline activity from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivity(final Context context, final TimelineSummaryItem timelineItem, final SQLiteDatabase writableDb, final SQLiteDatabase readableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteTimelineActivity()"); try { List<Integer > nativeItemIdList = new ArrayList<Integer>() ; //Delete from Native Database if(timelineItem.mNativeThreadId != null) { //Sms Native Database final Uri smsUri = Uri.parse("content://sms"); context.getContentResolver().delete(smsUri , "thread_id=" + timelineItem.mNativeThreadId, null); //Mms Native Database final Uri mmsUri = Uri.parse("content://mms"); context.getContentResolver().delete(mmsUri, "thread_id=" + timelineItem.mNativeThreadId, null); } else { // For CallLogs if(timelineItem.mLocalContactId != null) { fetchNativeIdsFromLocalContactId(nativeItemIdList, timelineItem.mLocalContactId, readableDb); if(nativeItemIdList.size() > 0) { //CallLog Native Database for(Integer nativeItemId : nativeItemIdList) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + nativeItemId, null); } } } else { if(timelineItem.mContactAddress != null) { - context.getContentResolver().delete(Calls.CONTENT_URI, Calls.NUMBER + "=" + timelineItem.mContactAddress, null); + context.getContentResolver().delete(Calls.CONTENT_URI, Calls.NUMBER + "='" + timelineItem.mContactAddress+"'", null); } } } String whereClause = null; //Delete from People Client database if(timelineItem.mLocalContactId != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } else if(timelineItem.mContactAddress != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } /** * Deletes all the timeline activities for a particular contact from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivities(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.deleteTimelineActivities()"); Cursor cursor = null; try { TimelineNativeTypes[] typeList = null; //For CallLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); //For SmsLog/MmsLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); //For ChatLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * * Deletes one or more timeline items for a contact for the given types. * * @param context The app context to open the transaction in. * @param latestTimelineItem The latest item from the timeline to get the belonging contact from. * @param writableDb The database to write to. * @param readableDb The database to read from. * @param typeList The list of types to delete timeline events for. * * @return Returns a success if the transaction was successful, an error otherwise. * */ private static ServiceStatus deleteTimeLineActivitiesByType(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb, TimelineNativeTypes[] typeList) { Cursor cursor = null; TimelineSummaryItem timelineItem = null; try { cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { return deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * Fetches timeline events grouped by local contact ID, name or contact * address. Events returned will be in reverse-chronological order. If a * native type list is provided the result will be filtered by the list. * * @param minTimeStamp Only timeline events from this date will be returned * @param nativeTypes A list of native types to filter the result, or null * to return all. * @param readableDb Readable SQLite database * @return A cursor containing the result. The * {@link #getTimelineData(Cursor)} method should be used for * reading the cursor. */ public static Cursor fetchTimelineEventList(final Long minTimeStamp, final TimelineNativeTypes[] nativeTypes, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchTimelineEventList() " + "minTimeStamp[" + minTimeStamp + "]"); try { int andVal = 1; String typesQuery = " AND "; if (nativeTypes != null) { typesQuery += DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), nativeTypes, "OR"); typesQuery += " AND "; andVal = 2; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + Field.TIMESTAMP + " > " + minTimeStamp + " AND (" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") ORDER BY " + Field.TIMESTAMP + " DESC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchLastUpdateTime() " + "Unable to fetch timeline event list", e); return null; } } /** * Adds a list of timeline events to the database. Each event is grouped by * contact and grouped by contact + native type. * * @param itemList List of timeline events * @param isCallLog true to group all activities with call logs, false to * group with messaging * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error */ public static ServiceStatus addTimelineEvents( final ArrayList<TimelineSummaryItem> itemList, final boolean isCallLog, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addTimelineEvents()"); TimelineNativeTypes[] activityTypes; if (isCallLog) { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; } else { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; } for (TimelineSummaryItem item : itemList) { try { writableDb.beginTransaction(); if (findNativeActivity(item, writableDb)) { continue; } int latestStatusVal = 0; if (!TextUtils.isEmpty(item.mContactName) || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, activityTypes, writableDb); } else { // unknown contact latestStatusVal = 1; } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM); values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } item.mLocalActivityId = writableDb.insert(TABLE_NAME, null, values); if (item.mLocalActivityId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "ERROR_DATABASE_CORRUPT - Unable to add " + "timeline list to database"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /** * The method returns the ROW_ID i.e. the INTEGER PRIMARY KEY AUTOINCREMENT * field value for the inserted row, i.e. LOCAL_ID. * * @param item TimelineSummaryItem. * @param read - TRUE if the chat message is outgoing or gets into the * timeline history view for a contact with LocalContactId. * @param writableDb Writable SQLite database. * @return LocalContactID or -1 if the row was not inserted. */ public static long addChatTimelineEvent(final TimelineSummaryItem item, final boolean read, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addChatTimelineEvent()"); try { writableDb.beginTransaction(); int latestStatusVal = 0; if (item.mContactName != null || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }, writableDb); } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); /** Chat message body. **/ values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); if (read) { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); } else { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | 0); } values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); /** Conversation ID for chat message. **/ // values.put(Field.URI.toString(), item.conversationId); // 0 for incoming, 1 for outgoing if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } final long itemId = writableDb.insert(TABLE_NAME, null, values); if (itemId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() - " + "Unable to add timeline list to database, index<0:" + itemId); return -1; } writableDb.setTransactionSuccessful(); return itemId; } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return -1; } finally { writableDb.endTransaction(); } } /** * Clears the grouping of an activity in the database, if the given activity * is newer. This is so that only the latest activity is returned for a * particular group. Each activity is associated with two groups: * <ol> * <li>All group - Grouped by contact only</li> * <li>Native group - Grouped by contact and native type (call log or * messaging)</li> * </ol> * The group to be removed is determined by the activityTypes parameter. * Grouping must also work for timeline events that are not associated with * a contact. The following fields are used to do identify a contact for the * grouping (in order of priority): * <ol> * <li>localContactId - If it not null</li> * <li>name - If this is a valid telephone number, the match will be done to * ensure that the same phone number written in different ways will be * included in the group. See {@link #fetchNameWhereClause(Long, String)} * for more information.</li> * </ol> * * @param localContactId Local contact Id or NULL if the activity is not * associated with a contact. * @param name Name of contact or contact address (telephone number, email, * etc). * @param newUpdateTime The time that the given activity has occurred * @param flag Bitmap of types including: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * </ul> * @param activityTypes A list of native types to include in the grouping. * Currently, only two groups are supported (see above). If this * parameter is null the contact will be added to the * "all group", otherwise the contact is added to the native * group. * @param writableDb Writable SQLite database * @return The latest contact status value which should be added to the * current activities grouping. */ private static int removeContactGroup(final Long localContactId, final String name, final Long newUpdateTime, final int flag, final TimelineNativeTypes[] activityTypes, final SQLiteDatabase writableDb) { String whereClause = ""; int andVal = 1; if (activityTypes != null) { whereClause = DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), activityTypes, "OR"); whereClause += " AND "; andVal = 2; } String nameWhereClause = fetchNameWhereClause(localContactId, name); if (nameWhereClause == null) { return 0; } whereClause += nameWhereClause; Long prevTime = null; Long prevLocalId = null; Integer prevLatestContactStatus = null; Cursor cursor = null; try { cursor = writableDb.rawQuery("SELECT " + Field.TIMESTAMP + "," + Field.LOCAL_ACTIVITY_ID + "," + Field.LATEST_CONTACT_STATUS + " FROM " + TABLE_NAME + " WHERE " + whereClause + " AND " + "(" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") AND (" + Field.FLAG + "&" + flag + ") ORDER BY " + Field.TIMESTAMP + " DESC", null); if (cursor.moveToFirst()) { prevTime = cursor.getLong(0); prevLocalId = cursor.getLong(1); prevLatestContactStatus = cursor.getInt(2); } } catch (SQLException e) { return 0; } finally { CloseUtils.close(cursor); } if (prevTime != null && newUpdateTime != null) { if (newUpdateTime >= prevTime) { ContentValues cv = new ContentValues(); cv.put(Field.LATEST_CONTACT_STATUS.toString(), prevLatestContactStatus & (~andVal)); if (writableDb.update(TABLE_NAME, cv, Field.LOCAL_ACTIVITY_ID + "=" + prevLocalId, null) <= 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "Unable to update timeline as the latest"); return 0; } return andVal; } else { return 0; } } return andVal; } /** * Checks if an activity exists in the database. * * @param item The native SMS item to check against our client activities DB table. * * @return true if the activity was found, false otherwise * */ private static boolean findNativeActivity(TimelineSummaryItem item, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.findNativeActivity()"); Cursor cursor = null; boolean result = false; try { final String[] args = { Integer.toString(item.mNativeItemId), Integer.toString(item.mNativeItemType), Long.toString(item.mTimestamp) }; cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_ID + "=? AND " + Field.NATIVE_ITEM_TYPE + "=?" + " AND " + Field.TIMESTAMP + "=?", args); if (cursor.moveToFirst()) { result = true; } } finally { CloseUtils.close(cursor); } return result; } /** * Returns a string which can be added to the where clause in an SQL query * on the activities table, to filter the result for a specific contact or * name. The clause will prioritise in the following way: * <ol> * <li>Use localContactId - If it not null</li> * <li>Use name - If this is a valid telephone number, the match will be * done to ensure that the same phone number written in different ways will * be included in the group. * </ol> * * @param localContactId The local contact ID, or null if the contact does * not exist in the People database. * @param name A string containing the name, or a telephone number/email * identifying the contact. * @return The where clause string */ private static String fetchNameWhereClause(final Long localContactId, final String name) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNameWhereClause()");
360/360-Engine-for-Android
50a9f5698d1173482dc9ffd93fe1e3ad75070fc8
Removed false import
diff --git a/src/com/vodafone360/people/ApplicationCache.java b/src/com/vodafone360/people/ApplicationCache.java index aaf4ac2..4ad13f6 100644 --- a/src/com/vodafone360/people/ApplicationCache.java +++ b/src/com/vodafone360/people/ApplicationCache.java @@ -1,554 +1,553 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import java.security.InvalidParameterException; import java.util.ArrayList; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import com.vodafone360.people.R; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.engine.contactsync.SyncStatus; import com.vodafone360.people.service.ServiceStatus; -import com.vodafone360.people.ui.contacts.MyProfileCache; import com.vodafone360.people.utils.ThirdPartyAccount; import com.vodafone360.people.utils.LoginPreferences; import com.vodafone360.people.utils.LogUtils; /** * Caches information about the current state of the application. Stores most * recent activity and caches other information such as login details, so that * the application is returned to its most recent state when brought back to the * foreground or re-entered. The cached details can be cleared if required (as * part of 'Remove user data' for example). */ public class ApplicationCache { /** Text key for Terms of Service content. **/ private final static String TERMS_OF_SERVICE = "TERMS_OF_SERVICE"; /** Text key for Terms of Service last updated time. **/ private final static String TERMS_OF_SERVICE_TIME = "TERMS_OF_SERVICE_TIME"; /** Text key for Privacy content. **/ private final static String PRIVACY = "PRIVACY"; /** Text key for Privacy last updated time. **/ private final static String PRIVACY_TIME = "PRIVACY_TIME"; /** * Refresh any cached terms of service or privacy content after 10 minutes. */ private final static long REFRESH_TIME = 10 * 60 * 1000; private static final String TRUE = "true"; private static final String FALSE = "false"; /** * Login details are stored in the preferences file so that they can be used * to pre-populate the edit fields if the user is interrupted in the middle * of login/signup */ public static final String PREFS_FILE = "NOW_PLUS"; public static final String CONTACT_DATA = "ContactData"; public static final String CONTACT_SUMMARY = "ContactSummary"; public static final String CONTACT_ID = "CONTACTID"; public static final String CONTACT_NAME = "CONTACTNAME"; public static final String CONTACT_NUMBER = "CONTACTNUMBER"; public static final String CONTACT_NETWORK = "CONTACTNETWORK"; public static final String CONTACT_MODIFIED = "ContactModified"; public static final String STARTUP_LAUNCH_PATH_KEY = "LAUNCHED_FROM"; public static final int RESULT_DELETE = -100; public static final int CONTACT_PROFILE_VIEW = 0; public static final int CONTACT_PROFILE_EDIT = 1; public static final int CONTACT_PROFILE_ADD = 2; public static final int CONTACT_PROFILE_VIEW_ME = 3; public static final String THIRD_PARTY_ACCOUNT_NAME_KEY = "ThirdPartyAccountName"; public static final String THIRD_PARTY_ACCOUNT_NETWORK_KEY = "ThirdPartyNetworkName"; public static final String THIRD_PARTY_ACCOUNT_USERNAME_KEY = "ThirdPartyAccountUsername"; public static final String THIRD_PARTY_ACCOUNT_PASSWORD_KEY = "ThirdPartyAccountPassword"; public static final String THIRD_PARTY_ACCOUNT_CAPABILITIES = "ThirdPartyAccountCapabilities"; public static final String THIRD_PARTY_ACCOUNT_ERROR_CODE = "ThirdPartyAccountErrorCode"; private final static String FACEBOOK_SUBSCRIBED = "FacebookSubscribed"; private final static String HYVES_SUBSCRIBED = "HyvesSubscribed"; public final static String PREFS_NAME = "NowPlus_Prefs"; // Check settings public final static String PREFS_CHECK_FREQUENCY = "checkFrequency"; // Upgrade version - these values are deleted when the latest version is not // new public final static String PREFS_LAST_DIALOG_DATE = "lastDialogDate"; public final static String PREFS_LAST_CHECKED_DATE = "lastCheckedDate"; public final static String PREFS_UPGRADE_LATEST_VERSION = "upgradeLatestVersion"; public final static String PREFS_UPGRADE_URL = "upgradeUrl"; public final static String PREFS_UPGRADE_TEXT = "upgradeText"; public static String sWidgetProviderClassName = null; public static String sIsNewMessage = "isNewMessage"; // Frequency setting descriptions and defaults public final static long[] FREQUENCY_SETTING_LONG = { -1, // Off 7 * 24 * 60 * 60 * 1000, // Weekly 24 * 60 * 60 * 1000, // Daily 6 * 60 * 60 * 1000, // Every 6 hours 1 * 60 * 60 * 1000, // Hourly 10 * 60 * 1000 // Every 10 minutes }; /** In memory cache of the current contacts sync status. **/ private SyncStatus mSyncStatus = null; // Cached login flags private boolean mFirstTimeLogin = true; private boolean mScanThirdPartyAccounts = true; private boolean mAcceptedTermsAndConditions = false; private int mIdentityBeingProcessed = -1; private ArrayList<ThirdPartyAccount> mThirdPartyAccountsCache; private ContactSummary mMeProfileSummary; private Contact mCurrentContact; private ContactSummary mCurrentContactSummary; private ServiceStatus mServiceStatus = ServiceStatus.ERROR_UNKNOWN; private TimelineSummaryItem mCurrentTimelineSummary; private long mCurrentContactFilter; /** Cached whether ThirdPartyAccountsActivity is opened. */ private boolean mIsAddAccountActivityOpened; /*** * GETTER Whether "add Account" activity is opened * * @return True if "add Account" activity is opened */ public boolean addAccountActivityOpened() { return mIsAddAccountActivityOpened; } /*** * SETTER Whether "add Account" activity is opened. * * @param flag if "add Account" activity is opened */ public void setAddAccountActivityOpened(final boolean flag) { mIsAddAccountActivityOpened = flag; } /** * Whether this is a first time login (on this device) for current account. * * @return True if this is the first login for current account. */ public boolean firstTimeLogin() { return mFirstTimeLogin; } /** * Set whether this is a first time login (on this device) for current * account. If we have not logged in on this device (or after 'Remove user * data') we will need to perform the first time 'full' time contact sync. * * @param aState True if this is our 1st time sync. */ public void setFirstTimeLogin(boolean state) { mFirstTimeLogin = state; } /** * Set whether application should re-scan 3rd party accounts. * * @param state true if application should re-scan 3rd party accounts. */ public void setScanThirdPartyAccounts(boolean state) { mScanThirdPartyAccounts = state; } /** * Return whether application should re-scan 3rd party accounts. * * @return true if application should re-scan 3rd party accounts. */ public boolean getScanThirdPartyAccounts() { return mScanThirdPartyAccounts; } /** * Set index of Identity currently being processed. * * @param index Index of Identity currently being processed. */ public void setIdentityBeingProcessed(int index) { mIdentityBeingProcessed = index; } /** * Return index of the Identity currently being processed. * * @return index of the Identity currently being processed. */ public int getIdentityBeingProcessed() { return mIdentityBeingProcessed; } /** * Set whether user has accepted the Terms and Conditions on sign-up. * * @param state true if user has accepted terms and conditions. */ public void setAcceptedTermsAndConditions(boolean state) { mAcceptedTermsAndConditions = state; } /** * Return whether user has accepted the Terms and Conditions on sign-up. * * @return true if user has accepted terms and conditions. */ public boolean getAcceptedTermsAndConditions() { return mAcceptedTermsAndConditions; } /** * Clear all cached data currently stored in People application. */ protected void clearCachedData(Context context) { LoginPreferences.clearPreferencesFile(context); LoginPreferences.clearCachedLoginDetails(); mFirstTimeLogin = true; mScanThirdPartyAccounts = true; mIdentityBeingProcessed = -1; mAcceptedTermsAndConditions = false; mMeProfileSummary = null; mCurrentContact = null; mCurrentContactSummary = null; mServiceStatus = ServiceStatus.ERROR_UNKNOWN; mThirdPartyAccountsCache = null; mSyncStatus = null; mIsAddAccountActivityOpened = false; } /** * Gets the ME profile object. * * @return The ME profile object. */ public ContactSummary getMeProfile() { return mMeProfileSummary; } /** * Sets the ME profile object. * * @param summary ContyactSummary for Me profile. */ public void setMeProfile(ContactSummary summary) { mMeProfileSummary = summary; } /** * Gets the contact currently being viewed in the UI. * * @return The currently view contact. */ public Contact getCurrentContact() { return mCurrentContact; } /** * Sets the contact currently being viewed in the UI. * * @param contact The currently viewed contact. */ public void setCurrentContact(Contact contact) { mCurrentContact = contact; } /** * Gets the summary information of the contact currently being viewed in the * UI. * * @return Contact summary information. */ public ContactSummary getCurrentContactSummary() { return mCurrentContactSummary; } /** * Sets the summary information of the contact currently being viewed in the * UI. * * @param contactSummary Contact summary information. */ public void setCurrentContactSummary(ContactSummary contactSummary) { mCurrentContactSummary = contactSummary; } /** * Return status of request issued to People service. * * @return status of request issued to People service. */ public ServiceStatus getServiceStatus() { return mServiceStatus; } /** * Set status of request issued to People service. * * @param status of request issued to People service. */ public void setServiceStatus(ServiceStatus status) { mServiceStatus = status; } /** * Cache list of 3rd party accounts (Identities) associated with current * login. * * @param list List of ThirdPartyAccount items retrieved from current login. */ public void storeThirdPartyAccounts(Context context, ArrayList<ThirdPartyAccount> list) { setValue(context, FACEBOOK_SUBSCRIBED, isFacebookInThirdPartyAccountList(list) + ""); setValue(context, HYVES_SUBSCRIBED, isHyvesInThirdPartyAccountList(list) + ""); mThirdPartyAccountsCache = list; } /** * Return cached list of 3rd party accounts (Identities) associated with * current login. * * @return List of ThirdPartyAccount items retrieved from current login. */ public ArrayList<ThirdPartyAccount> getThirdPartyAccounts() { return mThirdPartyAccountsCache; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Facebook account. */ private static boolean isFacebookInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("facebook")) { if (thirdPartyAccount.isChecked()) { LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook is checked"); return true; } else { LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook is unchecked"); return false; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given ThirdPartyAccount contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Hyves account. */ private static boolean isHyvesInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("hyves")) { if (thirdPartyAccount.isChecked()) { LogUtils .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is checked"); return true; } else { LogUtils .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is unchecked"); return false; } } } } LogUtils.logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves not found in list"); return false; } /** * Get list of IDs of Home-screen widgets. * * @param context Current context. * @return list of IDs of Home-screen widgets. */ public int[] getWidgetIdList(Context context) { if(sWidgetProviderClassName != null) { return AppWidgetManager.getInstance(context).getAppWidgetIds( new ComponentName(context, sWidgetProviderClassName)); } return null; } /*** * Set a value in the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param value Preference value. */ private static void setValue(Context context, String key, String value) { SharedPreferences.Editor editor = context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(key, value); if (!editor.commit()) { throw new NullPointerException("MainApplication.setValue() Failed to set key[" + key + "] with value[" + value + "]"); } LogUtils.logV("ApplicationCache.setValue() key [" + key + "] value [" + value + "] saved to properties file"); } /*** * Gets the current sync state, or NULL if the state has not been set in * this JVM instance. * * @return SyncStatus or NULL. */ public SyncStatus getSyncStatus() { return mSyncStatus; } /*** * Sets the current sync status. * * @param syncStatus New sync status. */ public void setSyncStatus(SyncStatus syncStatus) { mSyncStatus = syncStatus; } /*** * Get a value from the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param defaultValue Preference value. * @return */ private static String getValue(Context context, String key, String defaultValue) { return context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).getString(key, defaultValue); } /*** * Return the resource ID for the SNS Subscribed warning (e.g. * facebook/hyves/etc posting), or -1 if no warning is necessary. * * @param context Android context. * @return Resource ID for textView or -1 is warning is not required. * @throws InvalidParameterException when context is NULL. */ public static int getSnsSubscribedWarningId(Context context) { if (context == null) { throw new InvalidParameterException("ApplicationCache.getSnsSubscribedWarningId() " + "context cannot be NULL"); } boolean facebook = getValue(context, FACEBOOK_SUBSCRIBED, "").equals("true"); boolean hyves = getValue(context, HYVES_SUBSCRIBED, "").equals("true"); if (facebook && hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves_and_facebook; } else if (facebook) { return R.string.ContactStatusListActivity_update_status_on_facebook; } else if (hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves; } else { return -1; } } public static boolean isBooleanValue(Context context, String key) { return TRUE.equals(getValue(context, key, FALSE)); } public static void setBooleanValue(Context context, String key, boolean value) { setValue(context, key, value ? TRUE : FALSE); } /** * Gets the summary information of the Timeline currently being viewed in the * UI. * * @return Timeline summary information.
360/360-Engine-for-Android
5f3db6a696e1907b7cd622307edeb683b63ebcac
Reinitialize the buffer
diff --git a/src/com/vodafone360/people/utils/ResetableBufferedInputStream.java b/src/com/vodafone360/people/utils/ResetableBufferedInputStream.java index f13ee13..7548299 100644 --- a/src/com/vodafone360/people/utils/ResetableBufferedInputStream.java +++ b/src/com/vodafone360/people/utils/ResetableBufferedInputStream.java @@ -1,80 +1,84 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.utils; import java.io.BufferedInputStream; import java.io.InputStream; /** * Extended BufferedInputStream with a possibility to reset it and reuse it. * This way one can avoid GC issues that happen to come with the BufferedInputStream * which allways has to be recreated for new use. * @author admin * */ public class ResetableBufferedInputStream extends BufferedInputStream { /** * This method takes a new InputStream and sets all counts and markers back to initial values. * The buffer will not be touched so it can be reused * @param in New InputStream to use */ public void reset(InputStream in){ + // just in case close() was called initialize the buffer again. + if (buf==null){ + buf = new byte[8192]; + } this.in=in; count=0; marklimit=0; markpos = -1; pos=0; } /** * Constructs a new {@code ResetableBufferedInputStream} on the {@link InputStream} * {@code in}. The default buffer size (8 KB) is allocated and all reads * can now be filtered through this stream. * * @param in * the InputStream the buffer reads from. */ public ResetableBufferedInputStream(InputStream in) { super(in); } /** * Constructs a new {@code ResetableBufferedInputStream} on the {@link InputStream} * {@code in}. The buffer size is specified by the parameter {@code size} * and all reads are now filtered through this stream. * * @param in * the input stream the buffer reads from. * @param size * the size of buffer to allocate. * @throws IllegalArgumentException * if {@code size < 0}. */ public ResetableBufferedInputStream(InputStream in, int size) { super(in,size); } }
360/360-Engine-for-Android
23542f0a77039f0b6459812671eae8df3d7338e6
Fixed small bug
diff --git a/src/com/caucho/hessian/micro/MicroHessianInput.java b/src/com/caucho/hessian/micro/MicroHessianInput.java index c7170a8..5c31f3f 100644 --- a/src/com/caucho/hessian/micro/MicroHessianInput.java +++ b/src/com/caucho/hessian/micro/MicroHessianInput.java @@ -1,550 +1,550 @@ /* * Copyright (c) 2001-2006 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Scott Ferguson * */ package com.caucho.hessian.micro; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Hashtable; import java.util.Vector; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.ResetableBufferedInputStream; /** * Input stream for Hessian requests, compatible with microedition Java. It only * uses classes and types available to J2ME. In particular, it does not have any * support for the &lt;double> type. * <p> * MicroHessianInput does not depend on any classes other than in J2ME, so it * can be extracted independently into a smaller package. * <p> * MicroHessianInput is unbuffered, so any client needs to provide its own * buffering. * * <pre> * InputStream is = ...; // from http connection * MicroHessianInput in = new MicroHessianInput(is); * String value; * in.startReply(); // read reply header * value = in.readString(); // read string value * in.completeReply(); // read reply footer * </pre> */ public class MicroHessianInput { protected DataInputStream is; /** * Using a special BufferedInputstream, which is constructed once and then reused. * Saves a lot of GC time. */ protected ResetableBufferedInputStream rbis; /** Using fast but not thread safe StringBuilder for constructing strings */ private StringBuilder mStringBuilder = new StringBuilder(255); /** * Creates a new Hessian input stream, initialized with an underlying input * stream. * * @param is the underlying input stream. */ public MicroHessianInput(InputStream is) { init(is); } /** * Creates an uninitialized Hessian input stream. */ public MicroHessianInput() { } /** * Initialize the hessian stream with the underlying input stream. */ public void init(InputStream is) { //use the reusable resetablebufferedinputstream here if (rbis==null){ // create it only once rbis=new ResetableBufferedInputStream(is,2048); }else{ // then reuse it rbis.reset(is); } - this.is = new DataInputStream(is); + this.is = new DataInputStream(rbis); } /** * Starts reading the reply * <p> * A successful completion will have a single value: * * <pre> * r x01 x00 * </pre> */ public void startReply() throws IOException { int tag = is.read(); if (tag != 'r') throw protocolException("expected hessian reply"); // remove some bits from the input stream is.skip(2); } /** * Completes reading the call * <p> * A successful completion will have a single value: * * <pre> * z * </pre> */ public void completeReply() throws IOException { int tag = is.read(); if (tag != 'z') throw protocolException("expected end of reply"); } /** * Reads a boolean * * <pre> * T * F * </pre> */ public boolean readBoolean() throws IOException { int tag = is.read(); switch (tag) { case 'T': return true; case 'F': return false; default: throw expect("boolean", tag); } } /** * Reads an integer * * <pre> * I b32 b24 b16 b8 * </pre> */ public int readInt() throws IOException { int tag = is.read(); return readInt(tag); } public int readInt(int tag) throws IOException { if (tag != 'I') throw expect("integer", tag); return is.readInt(); } /** * Reads a long * * <pre> * L b64 b56 b48 b40 b32 b24 b16 b8 * </pre> */ public long readLong() throws IOException { int tag = is.read(); return readLong(tag); } private long readLong(int tag) throws IOException { if (tag != 'L') throw protocolException("expected long"); return is.readLong(); } /** * Reads a date. * * <pre> * T b64 b56 b48 b40 b32 b24 b16 b8 * </pre> */ public long readUTCDate() throws IOException { int tag = is.read(); if (tag != 'd') throw protocolException("expected date"); return is.readLong(); } /** * Reads a byte array * * @return byte[] array extracted from Hessian stream, NULL if 'N' specified * in data. * @throws IOException. */ public byte[] readBytes() throws IOException { int tag = is.read(); return readBytes(tag); } private byte[] readBytes(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'B') throw expect("bytes", tag); int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; byte[] bytes = new byte[len]; is.read(bytes); return bytes; } /** * Reads an arbitrary object the input stream. */ public Object readObject(Class<?> expectedClass) throws IOException { int tag = is.read(); switch (tag) { case 'N': return null; case 'T': return true; case 'F': return false; case 'I': { return readInt(tag); } case 'L': { return readLong(tag); } case 'd': { return new Date(is.readLong()); } case 'S': case 'X': { int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; return readStringImpl(len); } case 'B': { return readBytes(tag); } default: throw new IOException("unknown code:" + (char)tag); } } public Vector<Object> readVector() throws IOException { int tag = is.read(); return readVector(tag); } private Vector<Object> readVector(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'V') throw expect("vector", tag); Vector<Object> v = new Vector<Object>(); Object o = decodeTag(); if (o instanceof End) return v; if (o instanceof Type) o = decodeTag(); if (o instanceof End) return v; int len = 0; if (o instanceof Integer) { len = ((Integer)o); o = decodeTag(); } for (int i = 0; i < len; i++) { v.addElement(o); o = decodeTag(); } return v; } public Fault readFault() throws IOException { decodeTag(); int tag = is.read(); if (tag == 'S') { return new Fault(readString(tag)); } return null; } public Object decodeTag() throws IOException { int tag = is.read(); // HessianUtils.printTagValue(tag); return decodeType(tag); } public Object decodeType(int tag) throws IOException { // LogUtils.logD("HessianDecoder.decodeType() tag["+tag+"]"); switch (tag) { case 't': // tag is.skip(2); Type type = new Type(); return type; case 'l': // length int i = 0; i += (is.read() << 24); i += (is.read() << 16); i += (is.read() << 8); i += is.read(); Integer len = i; return len; case 'z': // end End end = new End(); return end; case 'N': // null return null; case 'r': // reply startReply should have retrieved this? return null; case 'M': return readHashMap(tag); case 'V': // array/Vector return readVector(tag); case 'T': // boolean true return true; case 'F': // boolean false return false; case 'I': // integer return readInt(tag); case 'L': // read long return readLong(tag); case 'd': // UTC date return null; case 'S': // String return readString(tag); case 'B': // read byte array return readBytes(tag); case 'f': return readFault(); default: LogUtils.logE("HessianDecoder.decodeType() Unknown type"); return null; } } /** * Reads a string * * <pre> * S b16 b8 string value * </pre> */ public String readString() throws IOException { int tag = is.read(); return readString(tag); } private String readString(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'S') throw expect("string", tag); int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; return readStringImpl(len); } /** * Reads a string from the underlying stream. */ private String readStringImpl(int length) throws IOException { // reset the StringBuilder. Recycling is better than making always a // new one. mStringBuilder.setLength(0); for (int i = 0; i < length; i++) { int ch = is.read(); if (ch < 0x80) mStringBuilder.append((char)ch); else if ((ch & 0xe0) == 0xc0) { int ch1 = is.read(); int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f); mStringBuilder.append((char)v); } else if ((ch & 0xf0) == 0xe0) { int ch1 = is.read(); int ch2 = is.read(); int v = ((ch & 0x0f) << 12) + ((ch1 & 0x3f) << 6) + (ch2 & 0x3f); mStringBuilder.append((char)v); } else if ((ch & 0xff) >= 0xf0 && (ch & 0xff) <= 0xf4) { // UTF-4 final byte[] b = new byte[4]; b[0] = (byte)ch; b[1] = (byte)is.read(); b[2] = (byte)is.read(); b[3] = (byte)is.read(); mStringBuilder.append(new String(b, "utf-8")); i++; } else throw new IOException("bad utf-8 encoding"); } return mStringBuilder.substring(0, mStringBuilder.length()); } public Hashtable<String, Object> readHashMap() throws IOException { // read map type int tag = is.read(); return readHashMap(tag); } public Hashtable<String, Object> readHashMap(int tag) throws IOException { // read map type if (tag == 'N') return null; if (tag != 'M') throw expect("map", tag); Hashtable<String, Object> ht = new Hashtable<String, Object>(); Object obj = decodeTag(); if (obj instanceof Type) { // get following object obj = decodeTag(); } Object obj1 = null; while (obj != null && !(obj instanceof End)) // 'z' = list-end { obj1 = decodeTag(); ht.put(obj.toString(), obj1); obj = decodeTag(); } return ht; } protected IOException expect(String expect, int ch) { if (ch < 0) return protocolException("expected " + expect + " at end of file"); else return protocolException("expected " + expect + " at " + (char)ch); } protected IOException protocolException(String message) { return new IOException(message); } /** * Place-holder class for End tag 'z' */ private static class End { } /** * Place-holder class for Type tag 't' */ private static class Type { } /** * Class holding error string returned during Hessian decoding */ public static class Fault { private String mErrString = null; private Fault(String eString) { mErrString = eString; } public String errString() { return mErrString; } } }
360/360-Engine-for-Android
44950f3d48a6b7a9be470b9a4d7000f541723913
did a follow up on the code review, removed class HardCodedUtils.java
diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index 06d73b8..f182ed3 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,314 +1,319 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ContactDetailsTable; import com.vodafone360.people.database.tables.ContactSummaryTable; import com.vodafone360.people.database.tables.ContactsTable; import com.vodafone360.people.database.tables.PresenceTable; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactDetail; +import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.agent.UiAgent; -import com.vodafone360.people.utils.HardcodedUtils; import com.vodafone360.people.utils.LogUtils; public class PresenceDbUtils { /** * the user id of the me profile contact */ private static long sMeProfileUserId = -1L; /** * the local contact id of the me profile contact */ private static long sMeProfileLocalContactId = -1L; public static void resetMeProfileIds() { sMeProfileUserId = -1L; sMeProfileLocalContactId = -1L; } /** * This method returns true if the provided user id matches the one of me profile. * @return TRUE if the provided user id matches the one of me profile. */ private static boolean isMeProfile(String userId, DatabaseHelper databaseHelper) { return userId.equals(String.valueOf(getMeProfileUserId(databaseHelper))); } /** * @param databaseHelper * @return */ protected static Long getMeProfileUserId(DatabaseHelper databaseHelper) { if (sMeProfileUserId == -1L) { Contact meProfile = new Contact(); if (SyncMeDbUtils.fetchMeProfile(databaseHelper, meProfile) != ServiceStatus.ERROR_NOT_FOUND) { sMeProfileUserId = meProfile.userID; sMeProfileLocalContactId = meProfile.localContactID; } } return sMeProfileUserId; } /** * @param databaseHelper * @return */ protected static User getMeProfilePresenceStatus(DatabaseHelper databaseHelper) { // if // (!sMeProfileLocalContactId.equals(databaseHelper.getMeProfileId())) { Long meProfileId = SyncMeDbUtils.getMeProfileLocalContactId(databaseHelper); sMeProfileLocalContactId = (meProfileId == null || meProfileId.intValue() == -1) ? -1 : meProfileId; // LogUtils.logE("The DB Helper and Utils IDs are not synchronized"); // } User user = PresenceTable.getUserPresenceByLocalContactId( getMeProfileUserId(databaseHelper), databaseHelper.getWritableDatabase()); if (user == null || (user.getPayload() == null)) { // the table is // empty, need to set // the status for the // 1st time // Get presence list constructed from identities Hashtable<String, String> status = EngineManager.getInstance().getPresenceEngine().getPresencesForStatus(OnlineStatus.ONLINE); user = new User(String.valueOf(getMeProfileUserId(databaseHelper)), status); } return user; } /** * This method returns wrapper with the presence information for all user * networks * * @param localContactId - the localContactId of the contact we want to get * presence states information for. * @param databaseHelper * @return User wrapper with the presence information for all user networks. * If no information is on the database the payload is NULL */ public static User getUserPresenceStatusByLocalContactId(long localContactId, DatabaseHelper databaseHelper) { User user = PresenceTable.getUserPresenceByLocalContactId(localContactId, databaseHelper .getWritableDatabase()); LogUtils.logW("UI called getUserPresenceStatusByLocalContactId: " + user); return user; } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users List<User> - the list of user presence states * @param idListeningTo long - local contact id which this UI is watching, -1 is all contacts * @param dbHelper DatabaseHelper - the database. * @return TRUE if database has changed in result of the update. */ protected static boolean updateDatabase(List<User> users, long idListeningTo, DatabaseHelper dbHelper) { boolean presenceChanged = false; boolean deleteNetworks = false; // list of network presence information we ignore - the networks where the user is offline. ArrayList<Integer> ignoredNetworks = new ArrayList<Integer>(); SQLiteDatabase writableDb = dbHelper.getWritableDatabase(); for (User user : users) { if (!user.getPayload().isEmpty()) { long localContactId = -1; ArrayList<NetworkPresence> payload = user.getPayload(); // if it is the me profile User boolean meProfile = false; String userId = null; int networkId = 0; for (NetworkPresence presence : payload) { userId = presence.getUserId(); if (!TextUtils.isEmpty(userId)) { networkId = presence.getNetworkId(); // if this is me profile contact if (isMeProfile(userId, dbHelper)) { localContactId = sMeProfileLocalContactId; meProfile = true; // remove the PC presence, as we don't display it in me profile if (networkId == SocialNetwork.PC.ordinal()) { presenceChanged = true; } } // 360 contact, PC or MOBILE network else if (networkId == SocialNetwork.PC.ordinal() || networkId == SocialNetwork.MOBILE.ordinal()) { localContactId = ContactsTable.fetchLocalIdFromUserId(Long .valueOf(userId), writableDb); if (localContactId != -1) { break; } } else { // 3rd party accounts localContactId = ContactDetailsTable.findLocalContactIdByKey( SocialNetwork.getPresenceValue(networkId).toString(), userId, ContactDetail.DetailKeys.VCARD_IMADDRESS, writableDb); if (localContactId != -1) { break; } } } } // set the local contact id user.setLocalContactId(localContactId); if (meProfile) { if (deleteNetworks = processMeProfile(presenceChanged, user, ignoredNetworks)) { // delete the information about offline networks from PresenceTable PresenceTable.setTPCNetworksOffline(ignoredNetworks, writableDb); } } if (user.getLocalContactId() > -1) { // will not save infos from the ignored networks updateUserRecord(user, ignoredNetworks, writableDb); if (user.getLocalContactId() == idListeningTo) { presenceChanged = true; } } } } // if contact summary table needs extra refresh, to make sure no statuses are displayed for offline TPC networks users if (deleteNetworks) { ArrayList<Long> userIds = PresenceTable.getLocalContactIds(dbHelper.getWritableDatabase()); ContactSummaryTable.setUsersOffline(userIds); presenceChanged = true; } if (idListeningTo == UiAgent.ALL_USERS) { presenceChanged = true; } return presenceChanged; } /** * This method writes the user presence status change from the passed User object * to the database and then fills the same User object with updated information. * @param user - the User presence change. * @param ignoredNetworks - the networks information from which must be ignored. * @param writableDb - database. */ private static void updateUserRecord(User user , ArrayList<Integer> ignoredNetworks, SQLiteDatabase writableDb) { // write the user presence update into the database and read the complete wrapper PresenceTable.updateUser(user, ignoredNetworks, writableDb); PresenceTable.getUserPresence(user, writableDb); // update the user aggregated presence state in the ContactSummaryTable ContactSummaryTable.updateOnlineStatus(user); } /** * This method alters the User wrapper of me profile, * and returns true if me profile information contains the ignored TPC networks information. * Based on the result this information may be deleted. * @param removePCPresence - if TRUE the PC network will be removed from the network list. * @param user - the me profile wrapper. * @param ignoredNetworks - the list if ignored integer network ids. * @return */ private static boolean processMeProfile(boolean removePCPresence, User user, ArrayList<Integer> ignoredNetworks){ if (removePCPresence) { user.removeNetwork(SocialNetwork.PC.ordinal()); int max = OnlineStatus.OFFLINE.ordinal(); // calculate the new aggregated presence status for (NetworkPresence presence : user.getPayload()) { if (presence.getOnlineStatusId() > max) { max = presence.getOnlineStatusId(); } } user.setOverallOnline(max); } // the list of chat network ids in this User wrapper ArrayList<Integer> userNetworks = new ArrayList<Integer>(); ArrayList<NetworkPresence> payload = user.getPayload(); for (NetworkPresence presence : payload) { int networkId = presence.getNetworkId(); userNetworks.add(networkId); // 1. ignore offline TPC networks if (presence.getOnlineStatusId() == OnlineStatus.OFFLINE.ordinal()) { ignoredNetworks.add(networkId); } } // 2. ignore the TPC networks presence state for which is unknown - for (int networkId : HardcodedUtils.THIRD_PARTY_CHAT_ACCOUNTS) { - if (!userNetworks.contains(networkId)) { - ignoredNetworks.add(networkId); + ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); + SocialNetwork network = null; + for (Identity identity : identities) { + network = SocialNetwork.getValue(identity.mNetwork); + if (network != null) { + if (!userNetworks.contains(network.ordinal())) { + ignoredNetworks.add(network.ordinal()); + } } } return !ignoredNetworks.isEmpty(); } protected static boolean updateMyPresence(User user, DatabaseHelper dbHelper) { boolean contactsChanged = false; if (PresenceTable.updateUser( user, null, dbHelper.getWritableDatabase()) != PresenceTable.USER_NOTADDED) { contactsChanged = (ContactSummaryTable.updateOnlineStatus(user) == ServiceStatus.SUCCESS); } return contactsChanged; } /** * Set all users to offline state * * @param dbHelper */ protected static void setPresenceOfflineInDatabase(DatabaseHelper dbHelper) { SQLiteDatabase writableDatabase = dbHelper.getWritableDatabase(); PresenceTable.setAllUsersOffline(writableDatabase); ContactSummaryTable.setOfflineStatus(); } /** * Removes all presence infos besides those related to MeProfile * * @param dbHelper */ protected static void resetPresenceStatesAcceptForMe(long localContactIdOfMe, DatabaseHelper dbHelper) { SQLiteDatabase writableDb = dbHelper.getWritableDatabase(); if (writableDb != null) { LogUtils.logW(" PresenceDBUtils.resetPresenceStatesAcceptForMe: " + "#rows affected by delete method " + PresenceTable.setAllUsersOfflineExceptForMe(localContactIdOfMe, writableDb)); ContactSummaryTable.setOfflineStatusExceptForMe(localContactIdOfMe); } } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index fd9018d..d34a091 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -130,702 +130,700 @@ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, } @Override public void onCreate() { } @Override public void onDestroy() { if (mDbHelper != null && SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper) != null) { PresenceDbUtils.resetPresenceStatesAcceptForMe(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), mDbHelper); } EngineManager.getInstance().getLoginEngine().removeListener(this); } /** * Checks if the SyncMe and ContactSync Engines have both completed first time sync. * * @return true if both engines have completed first time sync */ private boolean isFirstTimeSyncComplete() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!isFirstTimeSyncComplete()) { LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"); return -1; } /** * need isUiRequestOutstanding() because currently the worker thread is * running and finishing before PresenceEngine.setNextRuntime is called */ if (isCommsResponseOutstanding() || isUiRequestOutstanding()) { LogUtils.logV("PresenceEngine getNextRunTime() comms response outstanding"); return 0; } if (firstRun) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); firstRun = false; } return getCurrentTimeout(); } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + getCurrentTimeout() + "]"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logV("PresenceEngine.run() handled processCommsInQueue()"); return; } if (processTimeout()) { LogUtils.logV("PresenceEngine.run() handled processTimeout()"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logV("PresenceEngine.run(): AgentState.DISCONNECTED"); setPresenceOffline(); } /** * and the getNextRunTime must check the uiRequestReady() function and * return 0 if it is true */ if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { return isUiRequestOutstanding(); } private User getMyAvailabilityStatusFromDatabase() { return PresenceDbUtils.getMeProfilePresenceStatus(mDbHelper); } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setTimeout(CHECK_FREQUENCY); } } else { firstRun = true; mFailedMessagesList.clear(); mSendMessagesHash.clear(); setPresenceOffline(); } } /*** * Set the Global presence status to offline. */ private synchronized void setPresenceOffline() { PresenceDbUtils.setPresenceOfflineInDatabase(mDbHelper); // We clear the mUsers of any pending presence updates because this // Offline presence update request should take the highest priority. mUsers = null; mState = IDLE; mEventCallback.getUiAgent().updatePresence(UiAgent.ALL_USERS); } @Override protected void onRequestComplete() { LogUtils.logI("PresenceEngine.onRequestComplete()"); } @Override protected void onTimeoutEvent() { LogUtils.logI("PresenceEngine.onTimeoutEvent()"); switch (mState) { case UPDATE_PROCESSING_GOING_ON: updatePresenceDatabaseNextPage(); break; case IDLE: default: if (mLoggedIn) { if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setTimeout(CHECK_FREQUENCY); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); setTimeout(CHECK_FREQUENCY / 20); } } } } @Override protected void processCommsResponse(DecodedResponse resp) { handleServerResponse(resp.mDataTypes); } private void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg) { UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribedWithChat()) { uiAgent.sendUnsolicitedUiEvent(errorEvent, null); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users List of users that require updating. */ private synchronized void updatePresenceDatabase(List<User> users) { if (users == null || users.size() == 0) { LogUtils.logW("PresenceEngine.updatePresenceDatabase() users is NULL or zero size"); } else { if (mUsers == null) { mUsers = users; } else { // Doing an add one by one is not an efficient way but then // there is an issue in the addAll API. It crashes sometimes. // And the java code for the AddAll API seems to be erroneous. // More investigation is needed on this. for (User user : users) { mUsers.add(user); } } } mState = UPDATE_PROCESSING_GOING_ON; updatePresenceDatabaseNextPage(); } /** * This API makes the presence updates in pages of 10 with a timeout * after each page. The HandlerAgent is notified after every 10 pages. */ private synchronized void updatePresenceDatabaseNextPage(){ UiAgent uiAgent = mEventCallback.getUiAgent(); if(mUsers == null){ mState = IDLE; return; } int listSize = mUsers.size(); int start = 0; int end = UPDATE_PRESENCE_PAGE_SIZE; if(listSize == 0){ mState = IDLE; mUsers = null; return; } else if(listSize < end) { end = listSize; } List<User> userSubset = mUsers.subList(start, end); if ((userSubset != null)) { long idListeningTo = UiAgent.ALL_USERS; if (uiAgent != null) { idListeningTo = uiAgent.getLocalContactId(); } boolean updateUI = PresenceDbUtils.updateDatabase(userSubset, idListeningTo, mDbHelper); userSubset.clear(); // Send the update notification to UI for every UPDATE_PRESENCE_PAGE_SIZE*NOTIFY_AGENT_PAGE_INTERVAL updates. if (updateUI) { if (mUsers.size() == 0 || NOTIFY_AGENT_PAGE_INTERVAL == mIterations) { if (uiAgent != null) { uiAgent.updatePresence(idListeningTo); } mIterations = 0; } else { mIterations++; } } this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } // Get presences Hashtable<String, String> presenceList = getPresencesForStatus(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now - LogUtils.logE(">>>>>>> Hello hello kitty " + presenceList); - addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** * Changes the user's availability. * * @param status - Hashtable<String, String> of pairs <communityName, statusName>. */ public void setMyAvailability(Hashtable<String, String> presenceHash) { if (presenceHash == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+ presenceHash.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceHash); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } /** * Changes the user's availability. * * @param network - SocialNetwork to set presence on. * @param status - OnlineStatus presence status to set. */ public void setMyAvailability(SocialNetwork network, OnlineStatus status) { LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+network + "=" + status); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); presenceList.add(new NetworkPresence(userId, network.ordinal(), status.ordinal())); User me = new User(userId, null); me.setPayload(presenceList); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now Hashtable<String, String> presenceHash = new Hashtable<String, String>(); presenceHash.put(network.toString(), status.toString()); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } @Override public void onConnectionStateChanged(int state) { if (mLoggedIn && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * This method gets the availability information for Me Profile from the Presence * table and updates the same to the server. */ public final void setMyAvailability() { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if(identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); for(Identity identity : identities) { presences.put(identity.mNetwork, statusString); } return presences; } @Override public void onReset() { // reset the engine as if it was just created super.onReset(); firstRun = true; mLoggedIn = false; mIterations = 0; mState = IDLE; mUsers = null; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } }
360/360-Engine-for-Android
496e4b4bbbb338ca5b9de33aafac2ea739fb4b8a
Changed check for facebook/hyves accounts
diff --git a/src/com/vodafone360/people/ApplicationCache.java b/src/com/vodafone360/people/ApplicationCache.java index 8685f9a..f79cfca 100644 --- a/src/com/vodafone360/people/ApplicationCache.java +++ b/src/com/vodafone360/people/ApplicationCache.java @@ -1,666 +1,666 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import java.security.InvalidParameterException; import java.util.ArrayList; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import com.vodafone360.people.R; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.engine.contactsync.SyncStatus; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.ThirdPartyAccount; import com.vodafone360.people.utils.LoginPreferences; import com.vodafone360.people.utils.LogUtils; /** * Caches information about the current state of the application. Stores most * recent activity and caches other information such as login details, so that * the application is returned to its most recent state when brought back to the * foreground or re-entered. The cached details can be cleared if required (as * part of 'Remove user data' for example). */ public class ApplicationCache { /** Text key for Terms of Service content. **/ private final static String TERMS_OF_SERVICE = "TERMS_OF_SERVICE"; /** Text key for Terms of Service last updated time. **/ private final static String TERMS_OF_SERVICE_TIME = "TERMS_OF_SERVICE_TIME"; /** Text key for Privacy content. **/ private final static String PRIVACY = "PRIVACY"; /** Text key for Privacy last updated time. **/ private final static String PRIVACY_TIME = "PRIVACY_TIME"; /** * Refresh any cached terms of service or privacy content after 10 minutes. */ private final static long REFRESH_TIME = 10 * 60 * 1000; private static final String TRUE = "true"; private static final String FALSE = "false"; /** * Login details are stored in the preferences file so that they can be used * to pre-populate the edit fields if the user is interrupted in the middle * of login/signup */ public static final String PREFS_FILE = "NOW_PLUS"; public static final String CONTACT_DATA = "ContactData"; public static final String CONTACT_SUMMARY = "ContactSummary"; public static final String CONTACT_ID = "CONTACTID"; public static final String CONTACT_NAME = "CONTACTNAME"; public static final String CONTACT_NUMBER = "CONTACTNUMBER"; public static final String CONTACT_NETWORK = "CONTACTNETWORK"; public static final String CONTACT_MODIFIED = "ContactModified"; public static final String STARTUP_LAUNCH_PATH_KEY = "LAUNCHED_FROM"; public static final int RESULT_DELETE = -100; public static final int CONTACT_PROFILE_VIEW = 0; public static final int CONTACT_PROFILE_EDIT = 1; public static final int CONTACT_PROFILE_ADD = 2; public static final int CONTACT_PROFILE_VIEW_ME = 3; public static final String THIRD_PARTY_ACCOUNT_NAME_KEY = "ThirdPartyAccountName"; public static final String THIRD_PARTY_ACCOUNT_NETWORK_KEY = "ThirdPartyNetworkName"; public static final String THIRD_PARTY_ACCOUNT_USERNAME_KEY = "ThirdPartyAccountUsername"; public static final String THIRD_PARTY_ACCOUNT_PASSWORD_KEY = "ThirdPartyAccountPassword"; public static final String THIRD_PARTY_ACCOUNT_CAPABILITIES = "ThirdPartyAccountCapabilities"; public static final String THIRD_PARTY_ACCOUNT_ERROR_CODE = "ThirdPartyAccountErrorCode"; private final static String FACEBOOK_SUBSCRIBED = "FacebookSubscribed"; private final static String HYVES_SUBSCRIBED = "HyvesSubscribed"; public final static String PREFS_NAME = "NowPlus_Prefs"; // Check settings public final static String PREFS_CHECK_FREQUENCY = "checkFrequency"; // Upgrade version - these values are deleted when the latest version is not // new public final static String PREFS_LAST_DIALOG_DATE = "lastDialogDate"; public final static String PREFS_LAST_CHECKED_DATE = "lastCheckedDate"; public final static String PREFS_UPGRADE_LATEST_VERSION = "upgradeLatestVersion"; public final static String PREFS_UPGRADE_URL = "upgradeUrl"; public final static String PREFS_UPGRADE_TEXT = "upgradeText"; public static String sWidgetProviderClassName = null; public static String sIsNewMessage = "isNewMessage"; // Frequency setting descriptions and defaults public final static long[] FREQUENCY_SETTING_LONG = { -1, // Off 7 * 24 * 60 * 60 * 1000, // Weekly 24 * 60 * 60 * 1000, // Daily 6 * 60 * 60 * 1000, // Every 6 hours 1 * 60 * 60 * 1000, // Hourly 10 * 60 * 1000 // Every 10 minutes }; /** In memory cache of the current contacts sync status. **/ private SyncStatus mSyncStatus = null; // Cached login flags private boolean mFirstTimeLogin = true; private boolean mScanThirdPartyAccounts = true; private boolean mAcceptedTermsAndConditions = false; private int mIdentityBeingProcessed = -1; private ArrayList<ThirdPartyAccount> mThirdPartyAccountsCache; private ContactSummary mMeProfileSummary; private Contact mCurrentContact; private ContactSummary mCurrentContactSummary; private ServiceStatus mServiceStatus = ServiceStatus.ERROR_UNKNOWN; private TimelineSummaryItem mCurrentTimelineSummary; private long mCurrentContactFilter; /** Cached whether ThirdPartyAccountsActivity is opened. */ private boolean mIsAddAccountActivityOpened; /*** * GETTER Whether "add Account" activity is opened * * @return True if "add Account" activity is opened */ public boolean addAccountActivityOpened() { return mIsAddAccountActivityOpened; } /*** * SETTER Whether "add Account" activity is opened. * * @param flag if "add Account" activity is opened */ public void setAddAccountActivityOpened(final boolean flag) { mIsAddAccountActivityOpened = flag; } /** * Whether this is a first time login (on this device) for current account. * * @return True if this is the first login for current account. */ public boolean firstTimeLogin() { return mFirstTimeLogin; } /** * Set whether this is a first time login (on this device) for current * account. If we have not logged in on this device (or after 'Remove user * data') we will need to perform the first time 'full' time contact sync. * * @param aState True if this is our 1st time sync. */ public void setFirstTimeLogin(boolean state) { mFirstTimeLogin = state; } /** * Set whether application should re-scan 3rd party accounts. * * @param state true if application should re-scan 3rd party accounts. */ public void setScanThirdPartyAccounts(boolean state) { mScanThirdPartyAccounts = state; } /** * Return whether application should re-scan 3rd party accounts. * * @return true if application should re-scan 3rd party accounts. */ public boolean getScanThirdPartyAccounts() { return mScanThirdPartyAccounts; } /** * Set index of Identity currently being processed. * * @param index Index of Identity currently being processed. */ public void setIdentityBeingProcessed(int index) { mIdentityBeingProcessed = index; } /** * Return index of the Identity currently being processed. * * @return index of the Identity currently being processed. */ public int getIdentityBeingProcessed() { return mIdentityBeingProcessed; } /** * Set whether user has accepted the Terms and Conditions on sign-up. * * @param state true if user has accepted terms and conditions. */ public void setAcceptedTermsAndConditions(boolean state) { mAcceptedTermsAndConditions = state; } /** * Return whether user has accepted the Terms and Conditions on sign-up. * * @return true if user has accepted terms and conditions. */ public boolean getAcceptedTermsAndConditions() { return mAcceptedTermsAndConditions; } /** * Clear all cached data currently stored in People application. */ protected void clearCachedData(Context context) { LoginPreferences.clearPreferencesFile(context); LoginPreferences.clearCachedLoginDetails(); mFirstTimeLogin = true; mScanThirdPartyAccounts = true; mIdentityBeingProcessed = -1; mAcceptedTermsAndConditions = false; mMeProfileSummary = null; mCurrentContact = null; mCurrentContactSummary = null; mServiceStatus = ServiceStatus.ERROR_UNKNOWN; mThirdPartyAccountsCache = null; mSyncStatus = null; mIsAddAccountActivityOpened = false; } /** * Gets the ME profile object. * * @return The ME profile object. */ public ContactSummary getMeProfile() { return mMeProfileSummary; } /** * Sets the ME profile object. * * @param summary ContyactSummary for Me profile. */ public void setMeProfile(ContactSummary summary) { mMeProfileSummary = summary; } /** * Gets the contact currently being viewed in the UI. * * @return The currently view contact. */ public Contact getCurrentContact() { return mCurrentContact; } /** * Sets the contact currently being viewed in the UI. * * @param contact The currently viewed contact. */ public void setCurrentContact(Contact contact) { mCurrentContact = contact; } /** * Gets the summary information of the contact currently being viewed in the * UI. * * @return Contact summary information. */ public ContactSummary getCurrentContactSummary() { return mCurrentContactSummary; } /** * Sets the summary information of the contact currently being viewed in the * UI. * * @param contactSummary Contact summary information. */ public void setCurrentContactSummary(ContactSummary contactSummary) { mCurrentContactSummary = contactSummary; } /** * Return status of request issued to People service. * * @return status of request issued to People service. */ public ServiceStatus getServiceStatus() { return mServiceStatus; } /** * Set status of request issued to People service. * * @param status of request issued to People service. */ public void setServiceStatus(ServiceStatus status) { mServiceStatus = status; } /** * Cache list of 3rd party accounts (Identities) associated with current * login. * * @param list List of ThirdPartyAccount items retrieved from current login. */ public void storeThirdPartyAccounts(Context context, ArrayList<ThirdPartyAccount> list) { setValue(context, FACEBOOK_SUBSCRIBED, isFacebookInThirdPartyAccountList(list) + ""); setValue(context, HYVES_SUBSCRIBED, isHyvesInThirdPartyAccountList(list) + ""); mThirdPartyAccountsCache = list; } /** * Return cached list of 3rd party accounts (Identities) associated with * current login. * * @return List of ThirdPartyAccount items retrieved from current login. */ public ArrayList<ThirdPartyAccount> getThirdPartyAccounts() { return mThirdPartyAccountsCache; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Facebook account. */ private static boolean isFacebookInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("facebook")) { - if (thirdPartyAccount.isChecked()) { + if (thirdPartyAccount.isVerified()) { LogUtils.logV("ApplicationCache." - + "isFacebookInThirdPartyAccountList() Facebook is checked"); + + "isFacebookInThirdPartyAccountList() Facebook is verified"); return true; } else { LogUtils.logV("ApplicationCache." - + "isFacebookInThirdPartyAccountList() Facebook is unchecked"); + + "isFacebookInThirdPartyAccountList() Facebook is not verified"); return false; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given ThirdPartyAccount contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Hyves account. */ private static boolean isHyvesInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("hyves")) { - if (thirdPartyAccount.isChecked()) { + if (thirdPartyAccount.isVerified()) { LogUtils - .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is checked"); + .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is verified"); return true; } else { LogUtils - .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is unchecked"); + .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is not verified"); return false; } } } } LogUtils.logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves not found in list"); return false; } /** * Get list of IDs of Home-screen widgets. * * @param context Current context. * @return list of IDs of Home-screen widgets. */ public int[] getWidgetIdList(Context context) { if(sWidgetProviderClassName != null) { return AppWidgetManager.getInstance(context).getAppWidgetIds( new ComponentName(context, sWidgetProviderClassName)); } return null; } /*** * Set a value in the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param value Preference value. */ private static void setValue(Context context, String key, String value) { SharedPreferences.Editor editor = context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(key, value); if (!editor.commit()) { throw new NullPointerException("MainApplication.setValue() Failed to set key[" + key + "] with value[" + value + "]"); } LogUtils.logV("ApplicationCache.setValue() key [" + key + "] value [" + value + "] saved to properties file"); } /*** * Gets the current sync state, or NULL if the state has not been set in * this JVM instance. * * @return SyncStatus or NULL. */ public SyncStatus getSyncStatus() { return mSyncStatus; } /*** * Sets the current sync status. * * @param syncStatus New sync status. */ public void setSyncStatus(SyncStatus syncStatus) { mSyncStatus = syncStatus; } /*** * Get a value from the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param defaultValue Preference value. * @return */ private static String getValue(Context context, String key, String defaultValue) { return context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).getString(key, defaultValue); } /*** * Return the resource ID for the SNS Subscribed warning (e.g. * facebook/hyves/etc posting), or -1 if no warning is necessary. * * @param context Android context. * @return Resource ID for textView or -1 is warning is not required. * @throws InvalidParameterException when context is NULL. */ public static int getSnsSubscribedWarningId(Context context) { if (context == null) { throw new InvalidParameterException("ApplicationCache.getSnsSubscribedWarningId() " + "context cannot be NULL"); } boolean facebook = getValue(context, FACEBOOK_SUBSCRIBED, "").equals("true"); boolean hyves = getValue(context, HYVES_SUBSCRIBED, "").equals("true"); if (facebook && hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves_and_facebook; } else if (facebook) { return R.string.ContactStatusListActivity_update_status_on_facebook; } else if (hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves; } else { return -1; } } public static boolean isBooleanValue(Context context, String key) { return TRUE.equals(getValue(context, key, FALSE)); } public static void setBooleanValue(Context context, String key, boolean value) { setValue(context, key, value ? TRUE : FALSE); } /** * Gets the summary information of the Timeline currently being viewed in the * UI. * * @return Timeline summary information. */ public TimelineSummaryItem getCurrentTimelineSummary() { return mCurrentTimelineSummary; } /** * Sets the summary information of the Timeline Item currently being viewed in the * UI. * * @param timelineSummary Timeline summary information. */ public void setCurrentTimelineSummary(TimelineSummaryItem timelineSummary) { mCurrentTimelineSummary = timelineSummary; } /*** * Set the Terms of Service content into the cache. * * @param value Terms of Service content. * @param context Android context. */ public static void setTermsOfService(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(TERMS_OF_SERVICE, value); editor.putLong(TERMS_OF_SERVICE_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setTermsOfService() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Set the Privacy content into the cache. * * @param value Privacy content. * @param context Android context. */ public static void setPrivacyStatemet(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(PRIVACY, value); editor.putLong(PRIVACY_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setPrivacyStatemet() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Get the Terms of Service content from the cache. Will return NULL if * there is no content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Terms of Service content */ public static String getTermsOfService(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(TERMS_OF_SERVICE_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME) { return null; } else { return sharedPreferences.getString(TERMS_OF_SERVICE, null); } } /*** * Get the Privacy content from the cache. Will return NULL if there is no * content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Privacy content */ public static String getPrivacyStatement(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(PRIVACY_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME) { return null; } else { return sharedPreferences.getString(PRIVACY, null); } } private static ServiceStatus sStatus = ServiceStatus.SUCCESS; public static void setTermsStatus(final ServiceStatus status) { sStatus = status; } public static ServiceStatus getTermsStatus() { return sStatus; } /** * @param currentContactFilter the mCurrentContactFilter to set */ public final void setCurrentContactFilter(final long currentContactFilter) { mCurrentContactFilter = currentContactFilter; } /** * @return the mCurrentContactFilter */ public final long getCurrentContactFilter() { return mCurrentContactFilter; } }
360/360-Engine-for-Android
15e6c493ca8247817de8d900c2753d22bfc56620
remove the reference to MyProfileUICache from ApplicationCache, which is in Engine project
diff --git a/src/com/vodafone360/people/ApplicationCache.java b/src/com/vodafone360/people/ApplicationCache.java index c7a886a..aaf4ac2 100644 --- a/src/com/vodafone360/people/ApplicationCache.java +++ b/src/com/vodafone360/people/ApplicationCache.java @@ -1,690 +1,668 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import java.security.InvalidParameterException; import java.util.ArrayList; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import com.vodafone360.people.R; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.engine.contactsync.SyncStatus; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.ui.contacts.MyProfileCache; import com.vodafone360.people.utils.ThirdPartyAccount; import com.vodafone360.people.utils.LoginPreferences; import com.vodafone360.people.utils.LogUtils; /** * Caches information about the current state of the application. Stores most * recent activity and caches other information such as login details, so that * the application is returned to its most recent state when brought back to the * foreground or re-entered. The cached details can be cleared if required (as * part of 'Remove user data' for example). */ public class ApplicationCache { /** Text key for Terms of Service content. **/ private final static String TERMS_OF_SERVICE = "TERMS_OF_SERVICE"; /** Text key for Terms of Service last updated time. **/ private final static String TERMS_OF_SERVICE_TIME = "TERMS_OF_SERVICE_TIME"; /** Text key for Privacy content. **/ private final static String PRIVACY = "PRIVACY"; /** Text key for Privacy last updated time. **/ private final static String PRIVACY_TIME = "PRIVACY_TIME"; /** * Refresh any cached terms of service or privacy content after 10 minutes. */ private final static long REFRESH_TIME = 10 * 60 * 1000; private static final String TRUE = "true"; private static final String FALSE = "false"; /** * Login details are stored in the preferences file so that they can be used * to pre-populate the edit fields if the user is interrupted in the middle * of login/signup */ public static final String PREFS_FILE = "NOW_PLUS"; public static final String CONTACT_DATA = "ContactData"; public static final String CONTACT_SUMMARY = "ContactSummary"; public static final String CONTACT_ID = "CONTACTID"; public static final String CONTACT_NAME = "CONTACTNAME"; public static final String CONTACT_NUMBER = "CONTACTNUMBER"; public static final String CONTACT_NETWORK = "CONTACTNETWORK"; public static final String CONTACT_MODIFIED = "ContactModified"; public static final String STARTUP_LAUNCH_PATH_KEY = "LAUNCHED_FROM"; public static final int RESULT_DELETE = -100; public static final int CONTACT_PROFILE_VIEW = 0; public static final int CONTACT_PROFILE_EDIT = 1; public static final int CONTACT_PROFILE_ADD = 2; public static final int CONTACT_PROFILE_VIEW_ME = 3; public static final String THIRD_PARTY_ACCOUNT_NAME_KEY = "ThirdPartyAccountName"; public static final String THIRD_PARTY_ACCOUNT_NETWORK_KEY = "ThirdPartyNetworkName"; public static final String THIRD_PARTY_ACCOUNT_USERNAME_KEY = "ThirdPartyAccountUsername"; public static final String THIRD_PARTY_ACCOUNT_PASSWORD_KEY = "ThirdPartyAccountPassword"; public static final String THIRD_PARTY_ACCOUNT_CAPABILITIES = "ThirdPartyAccountCapabilities"; public static final String THIRD_PARTY_ACCOUNT_ERROR_CODE = "ThirdPartyAccountErrorCode"; private final static String FACEBOOK_SUBSCRIBED = "FacebookSubscribed"; private final static String HYVES_SUBSCRIBED = "HyvesSubscribed"; public final static String PREFS_NAME = "NowPlus_Prefs"; // Check settings public final static String PREFS_CHECK_FREQUENCY = "checkFrequency"; // Upgrade version - these values are deleted when the latest version is not // new public final static String PREFS_LAST_DIALOG_DATE = "lastDialogDate"; public final static String PREFS_LAST_CHECKED_DATE = "lastCheckedDate"; public final static String PREFS_UPGRADE_LATEST_VERSION = "upgradeLatestVersion"; public final static String PREFS_UPGRADE_URL = "upgradeUrl"; public final static String PREFS_UPGRADE_TEXT = "upgradeText"; public static String sWidgetProviderClassName = null; public static String sIsNewMessage = "isNewMessage"; // Frequency setting descriptions and defaults public final static long[] FREQUENCY_SETTING_LONG = { -1, // Off 7 * 24 * 60 * 60 * 1000, // Weekly 24 * 60 * 60 * 1000, // Daily 6 * 60 * 60 * 1000, // Every 6 hours 1 * 60 * 60 * 1000, // Hourly 10 * 60 * 1000 // Every 10 minutes }; /** In memory cache of the current contacts sync status. **/ private SyncStatus mSyncStatus = null; // Cached login flags private boolean mFirstTimeLogin = true; private boolean mScanThirdPartyAccounts = true; private boolean mAcceptedTermsAndConditions = false; private int mIdentityBeingProcessed = -1; private ArrayList<ThirdPartyAccount> mThirdPartyAccountsCache; private ContactSummary mMeProfileSummary; private Contact mCurrentContact; private ContactSummary mCurrentContactSummary; private ServiceStatus mServiceStatus = ServiceStatus.ERROR_UNKNOWN; private TimelineSummaryItem mCurrentTimelineSummary; private long mCurrentContactFilter; /** Cached whether ThirdPartyAccountsActivity is opened. */ private boolean mIsAddAccountActivityOpened; - /** - * The My profile checkboxes states cache. - */ - private static MyProfileCache sMyProfileCache; - /*** * GETTER Whether "add Account" activity is opened * * @return True if "add Account" activity is opened */ public boolean addAccountActivityOpened() { return mIsAddAccountActivityOpened; } /*** * SETTER Whether "add Account" activity is opened. * * @param flag if "add Account" activity is opened */ public void setAddAccountActivityOpened(final boolean flag) { mIsAddAccountActivityOpened = flag; } /** * Whether this is a first time login (on this device) for current account. * * @return True if this is the first login for current account. */ public boolean firstTimeLogin() { return mFirstTimeLogin; } /** * Set whether this is a first time login (on this device) for current * account. If we have not logged in on this device (or after 'Remove user * data') we will need to perform the first time 'full' time contact sync. * * @param aState True if this is our 1st time sync. */ public void setFirstTimeLogin(boolean state) { mFirstTimeLogin = state; } /** * Set whether application should re-scan 3rd party accounts. * * @param state true if application should re-scan 3rd party accounts. */ public void setScanThirdPartyAccounts(boolean state) { mScanThirdPartyAccounts = state; } /** * Return whether application should re-scan 3rd party accounts. * * @return true if application should re-scan 3rd party accounts. */ public boolean getScanThirdPartyAccounts() { return mScanThirdPartyAccounts; } /** * Set index of Identity currently being processed. * * @param index Index of Identity currently being processed. */ public void setIdentityBeingProcessed(int index) { mIdentityBeingProcessed = index; } /** * Return index of the Identity currently being processed. * * @return index of the Identity currently being processed. */ public int getIdentityBeingProcessed() { return mIdentityBeingProcessed; } /** * Set whether user has accepted the Terms and Conditions on sign-up. * * @param state true if user has accepted terms and conditions. */ public void setAcceptedTermsAndConditions(boolean state) { mAcceptedTermsAndConditions = state; } /** * Return whether user has accepted the Terms and Conditions on sign-up. * * @return true if user has accepted terms and conditions. */ public boolean getAcceptedTermsAndConditions() { return mAcceptedTermsAndConditions; } /** * Clear all cached data currently stored in People application. */ protected void clearCachedData(Context context) { LoginPreferences.clearPreferencesFile(context); LoginPreferences.clearCachedLoginDetails(); mFirstTimeLogin = true; mScanThirdPartyAccounts = true; mIdentityBeingProcessed = -1; mAcceptedTermsAndConditions = false; mMeProfileSummary = null; mCurrentContact = null; mCurrentContactSummary = null; mServiceStatus = ServiceStatus.ERROR_UNKNOWN; mThirdPartyAccountsCache = null; mSyncStatus = null; mIsAddAccountActivityOpened = false; - - sMyProfileCache = null; } /** * Gets the ME profile object. * * @return The ME profile object. */ public ContactSummary getMeProfile() { return mMeProfileSummary; } /** * Sets the ME profile object. * * @param summary ContyactSummary for Me profile. */ public void setMeProfile(ContactSummary summary) { mMeProfileSummary = summary; } /** * Gets the contact currently being viewed in the UI. * * @return The currently view contact. */ public Contact getCurrentContact() { return mCurrentContact; } /** * Sets the contact currently being viewed in the UI. * * @param contact The currently viewed contact. */ public void setCurrentContact(Contact contact) { mCurrentContact = contact; } /** * Gets the summary information of the contact currently being viewed in the * UI. * * @return Contact summary information. */ public ContactSummary getCurrentContactSummary() { return mCurrentContactSummary; } /** * Sets the summary information of the contact currently being viewed in the * UI. * * @param contactSummary Contact summary information. */ public void setCurrentContactSummary(ContactSummary contactSummary) { mCurrentContactSummary = contactSummary; } /** * Return status of request issued to People service. * * @return status of request issued to People service. */ public ServiceStatus getServiceStatus() { return mServiceStatus; } /** * Set status of request issued to People service. * * @param status of request issued to People service. */ public void setServiceStatus(ServiceStatus status) { mServiceStatus = status; } /** * Cache list of 3rd party accounts (Identities) associated with current * login. * * @param list List of ThirdPartyAccount items retrieved from current login. */ public void storeThirdPartyAccounts(Context context, ArrayList<ThirdPartyAccount> list) { setValue(context, FACEBOOK_SUBSCRIBED, isFacebookInThirdPartyAccountList(list) + ""); setValue(context, HYVES_SUBSCRIBED, isHyvesInThirdPartyAccountList(list) + ""); mThirdPartyAccountsCache = list; } /** * Return cached list of 3rd party accounts (Identities) associated with * current login. * * @return List of ThirdPartyAccount items retrieved from current login. */ public ArrayList<ThirdPartyAccount> getThirdPartyAccounts() { return mThirdPartyAccountsCache; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Facebook account. */ private static boolean isFacebookInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("facebook")) { if (thirdPartyAccount.isChecked()) { LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook is checked"); return true; } else { LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook is unchecked"); return false; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given ThirdPartyAccount contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Hyves account. */ private static boolean isHyvesInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("hyves")) { if (thirdPartyAccount.isChecked()) { LogUtils .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is checked"); return true; } else { LogUtils .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is unchecked"); return false; } } } } LogUtils.logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves not found in list"); return false; } /** * Get list of IDs of Home-screen widgets. * * @param context Current context. * @return list of IDs of Home-screen widgets. */ public int[] getWidgetIdList(Context context) { if(sWidgetProviderClassName != null) { return AppWidgetManager.getInstance(context).getAppWidgetIds( new ComponentName(context, sWidgetProviderClassName)); } return null; } /*** * Set a value in the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param value Preference value. */ private static void setValue(Context context, String key, String value) { SharedPreferences.Editor editor = context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(key, value); if (!editor.commit()) { throw new NullPointerException("MainApplication.setValue() Failed to set key[" + key + "] with value[" + value + "]"); } LogUtils.logV("ApplicationCache.setValue() key [" + key + "] value [" + value + "] saved to properties file"); } /*** * Gets the current sync state, or NULL if the state has not been set in * this JVM instance. * * @return SyncStatus or NULL. */ public SyncStatus getSyncStatus() { return mSyncStatus; } /*** * Sets the current sync status. * * @param syncStatus New sync status. */ public void setSyncStatus(SyncStatus syncStatus) { mSyncStatus = syncStatus; } /*** * Get a value from the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param defaultValue Preference value. * @return */ private static String getValue(Context context, String key, String defaultValue) { return context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).getString(key, defaultValue); } /*** * Return the resource ID for the SNS Subscribed warning (e.g. * facebook/hyves/etc posting), or -1 if no warning is necessary. * * @param context Android context. * @return Resource ID for textView or -1 is warning is not required. * @throws InvalidParameterException when context is NULL. */ public static int getSnsSubscribedWarningId(Context context) { if (context == null) { throw new InvalidParameterException("ApplicationCache.getSnsSubscribedWarningId() " + "context cannot be NULL"); } boolean facebook = getValue(context, FACEBOOK_SUBSCRIBED, "").equals("true"); boolean hyves = getValue(context, HYVES_SUBSCRIBED, "").equals("true"); if (facebook && hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves_and_facebook; } else if (facebook) { return R.string.ContactStatusListActivity_update_status_on_facebook; } else if (hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves; } else { return -1; } } public static boolean isBooleanValue(Context context, String key) { return TRUE.equals(getValue(context, key, FALSE)); } public static void setBooleanValue(Context context, String key, boolean value) { setValue(context, key, value ? TRUE : FALSE); } /** * Gets the summary information of the Timeline currently being viewed in the * UI. * * @return Timeline summary information. */ public TimelineSummaryItem getCurrentTimelineSummary() { return mCurrentTimelineSummary; } /** * Sets the summary information of the Timeline Item currently being viewed in the * UI. * * @param timelineSummary Timeline summary information. */ public void setCurrentTimelineSummary(TimelineSummaryItem timelineSummary) { mCurrentTimelineSummary = timelineSummary; } /*** * Set the Terms of Service content into the cache. * * @param value Terms of Service content. * @param context Android context. */ public static void setTermsOfService(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(TERMS_OF_SERVICE, value); editor.putLong(TERMS_OF_SERVICE_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setTermsOfService() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Set the Privacy content into the cache. * * @param value Privacy content. * @param context Android context. */ public static void setPrivacyStatemet(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(PRIVACY, value); editor.putLong(PRIVACY_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setPrivacyStatemet() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Get the Terms of Service content from the cache. Will return NULL if * there is no content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Terms of Service content */ public static String getTermsOfService(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(TERMS_OF_SERVICE_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME) { return null; } else { return sharedPreferences.getString(TERMS_OF_SERVICE, null); } } /*** * Get the Privacy content from the cache. Will return NULL if there is no * content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Privacy content */ public static String getPrivacyStatement(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(PRIVACY_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME) { return null; } else { return sharedPreferences.getString(PRIVACY, null); } } private static ServiceStatus sStatus = ServiceStatus.SUCCESS; public static void setTermsStatus(final ServiceStatus status) { sStatus = status; } public static ServiceStatus getTermsStatus() { return sStatus; } /** * @param currentContactFilter the mCurrentContactFilter to set */ public final void setCurrentContactFilter(final long currentContactFilter) { mCurrentContactFilter = currentContactFilter; } /** * @return the mCurrentContactFilter */ public final long getCurrentContactFilter() { return mCurrentContactFilter; } - - /** - * Returns the cached checkboxes states on "My profile" screen. - * @return MyProfileCache object. - */ - public static MyProfileCache getMyProfileUiCache() { - return sMyProfileCache; - } - - /** - * This method sets the cache of checkboxes. - * @param cache MyProfileCache. - */ - public static void setMyProfileCache(MyProfileCache cache) { - sMyProfileCache = cache; - } + }
360/360-Engine-for-Android
f462053b1dfd2b33a82c9d6f4cea78a500ea3929
PAND-1852 send only chattable networks in setAvailability request
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 7d1bb0b..fd9018d 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,833 +1,831 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.ChatMessage; import com.vodafone360.people.datatypes.Conversation; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.PresenceList; import com.vodafone360.people.datatypes.PushAvailabilityEvent; import com.vodafone360.people.datatypes.PushChatMessageEvent; import com.vodafone360.people.datatypes.PushClosedConversationEvent; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.datatypes.SystemNotification.Tags; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Chat; import com.vodafone360.people.service.io.api.Presence; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; -import com.vodafone360.people.utils.HardcodedUtils; import com.vodafone360.people.utils.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, ITcpConnectionListener { /** Check every 24 hours **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private final List<TimelineSummaryItem> mFailedMessagesList; // (to, network) /** The list of Users still to be processed. **/ private List<User> mUsers = null; /** * This state indicates there are no more pending presence payload * information to be processed. **/ private static final int IDLE = 0; /** * This state indicates there are some pending presence payload information * to be processed. **/ private static final int UPDATE_PROCESSING_GOING_ON = 1; /** Timeout between each presence update processing. **/ private static final long UPDATE_PRESENCE_TIMEOUT_MILLS = 0; /** The page size i.e the number of presence updates processed at a time. **/ private static final int UPDATE_PRESENCE_PAGE_SIZE = 10; /** The number of pages after which the HandlerAgent is notified. **/ private static final int NOTIFY_AGENT_PAGE_INTERVAL = 5; /** The state of the presence Engine. **/ private int mState = IDLE; /** * Number of pages of presence Updates done. This is used to control when a * notification is sent to the UI. **/ private int mIterations = 0; /** * True if the engine runs for the 1st time. */ private boolean firstRun = true; /** * * @param eventCallback * @param databaseHelper */ public PresenceEngine(IEngineEventCallback eventCallback, DatabaseHelper databaseHelper) { super(eventCallback); mEngineId = EngineId.PRESENCE_ENGINE; mDbHelper = databaseHelper; mSendMessagesHash = new Hashtable<String, ChatMessage>(); mFailedMessagesList = new ArrayList<TimelineSummaryItem>(); } @Override public void onCreate() { } @Override public void onDestroy() { if (mDbHelper != null && SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper) != null) { PresenceDbUtils.resetPresenceStatesAcceptForMe(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), mDbHelper); } EngineManager.getInstance().getLoginEngine().removeListener(this); } /** * Checks if the SyncMe and ContactSync Engines have both completed first time sync. * * @return true if both engines have completed first time sync */ private boolean isFirstTimeSyncComplete() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!isFirstTimeSyncComplete()) { LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"); return -1; } /** * need isUiRequestOutstanding() because currently the worker thread is * running and finishing before PresenceEngine.setNextRuntime is called */ if (isCommsResponseOutstanding() || isUiRequestOutstanding()) { LogUtils.logV("PresenceEngine getNextRunTime() comms response outstanding"); return 0; } if (firstRun) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); firstRun = false; } return getCurrentTimeout(); } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + getCurrentTimeout() + "]"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logV("PresenceEngine.run() handled processCommsInQueue()"); return; } if (processTimeout()) { LogUtils.logV("PresenceEngine.run() handled processTimeout()"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logV("PresenceEngine.run(): AgentState.DISCONNECTED"); setPresenceOffline(); } /** * and the getNextRunTime must check the uiRequestReady() function and * return 0 if it is true */ if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { return isUiRequestOutstanding(); } private User getMyAvailabilityStatusFromDatabase() { return PresenceDbUtils.getMeProfilePresenceStatus(mDbHelper); } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setTimeout(CHECK_FREQUENCY); } } else { firstRun = true; mFailedMessagesList.clear(); mSendMessagesHash.clear(); setPresenceOffline(); } } /*** * Set the Global presence status to offline. */ private synchronized void setPresenceOffline() { PresenceDbUtils.setPresenceOfflineInDatabase(mDbHelper); // We clear the mUsers of any pending presence updates because this // Offline presence update request should take the highest priority. mUsers = null; mState = IDLE; mEventCallback.getUiAgent().updatePresence(UiAgent.ALL_USERS); } @Override protected void onRequestComplete() { LogUtils.logI("PresenceEngine.onRequestComplete()"); } @Override protected void onTimeoutEvent() { LogUtils.logI("PresenceEngine.onTimeoutEvent()"); switch (mState) { case UPDATE_PROCESSING_GOING_ON: updatePresenceDatabaseNextPage(); break; case IDLE: default: if (mLoggedIn) { if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setTimeout(CHECK_FREQUENCY); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); setTimeout(CHECK_FREQUENCY / 20); } } } } @Override protected void processCommsResponse(DecodedResponse resp) { handleServerResponse(resp.mDataTypes); } private void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg) { UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribedWithChat()) { uiAgent.sendUnsolicitedUiEvent(errorEvent, null); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users List of users that require updating. */ private synchronized void updatePresenceDatabase(List<User> users) { if (users == null || users.size() == 0) { LogUtils.logW("PresenceEngine.updatePresenceDatabase() users is NULL or zero size"); } else { if (mUsers == null) { mUsers = users; } else { // Doing an add one by one is not an efficient way but then // there is an issue in the addAll API. It crashes sometimes. // And the java code for the AddAll API seems to be erroneous. // More investigation is needed on this. for (User user : users) { mUsers.add(user); } } } mState = UPDATE_PROCESSING_GOING_ON; updatePresenceDatabaseNextPage(); } /** * This API makes the presence updates in pages of 10 with a timeout * after each page. The HandlerAgent is notified after every 10 pages. */ private synchronized void updatePresenceDatabaseNextPage(){ UiAgent uiAgent = mEventCallback.getUiAgent(); if(mUsers == null){ mState = IDLE; return; } int listSize = mUsers.size(); int start = 0; int end = UPDATE_PRESENCE_PAGE_SIZE; if(listSize == 0){ mState = IDLE; mUsers = null; return; } else if(listSize < end) { end = listSize; } List<User> userSubset = mUsers.subList(start, end); if ((userSubset != null)) { long idListeningTo = UiAgent.ALL_USERS; if (uiAgent != null) { idListeningTo = uiAgent.getLocalContactId(); } boolean updateUI = PresenceDbUtils.updateDatabase(userSubset, idListeningTo, mDbHelper); userSubset.clear(); // Send the update notification to UI for every UPDATE_PRESENCE_PAGE_SIZE*NOTIFY_AGENT_PAGE_INTERVAL updates. if (updateUI) { if (mUsers.size() == 0 || NOTIFY_AGENT_PAGE_INTERVAL == mIterations) { if (uiAgent != null) { uiAgent.updatePresence(idListeningTo); } mIterations = 0; } else { mIterations++; } } this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); - - LogUtils.logW("PresenceEngine processUiRequest() SEND_CHAT_MESSAGE :" + msg); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } // Get presences - // TODO: Fill up hashtable with identities and online statuses - Hashtable<String, String> presenceList = HardcodedUtils.createMyAvailabilityHashtable(status); + Hashtable<String, String> presenceList = getPresencesForStatus(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now + LogUtils.logE(">>>>>>> Hello hello kitty " + presenceList); + addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** * Changes the user's availability. * * @param status - Hashtable<String, String> of pairs <communityName, statusName>. */ public void setMyAvailability(Hashtable<String, String> presenceHash) { if (presenceHash == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+ presenceHash.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceHash); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } /** * Changes the user's availability. * * @param network - SocialNetwork to set presence on. * @param status - OnlineStatus presence status to set. */ public void setMyAvailability(SocialNetwork network, OnlineStatus status) { LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+network + "=" + status); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); presenceList.add(new NetworkPresence(userId, network.ordinal(), status.ordinal())); User me = new User(userId, null); me.setPayload(presenceList); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now Hashtable<String, String> presenceHash = new Hashtable<String, String>(); presenceHash.put(network.toString(), status.toString()); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } @Override public void onConnectionStateChanged(int state) { if (mLoggedIn && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * This method gets the availability information for Me Profile from the Presence * table and updates the same to the server. */ public final void setMyAvailability() { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if(identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); for(Identity identity : identities) { presences.put(identity.mNetwork, statusString); } return presences; } @Override public void onReset() { // reset the engine as if it was just created super.onReset(); firstRun = true; mLoggedIn = false; mIterations = 0; mState = IDLE; mUsers = null; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } }
360/360-Engine-for-Android
7b253e225d94de1d1f52fd5b6c2ad7d750e4a2da
Fix for PAND-2054: System Sync settings not enabled in case of application upgrade
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java index e053a02..ece39c1 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java @@ -1,408 +1,415 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.security.InvalidParameterException; import android.content.ContentResolver; import android.content.Context; import android.text.TextUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * Class that provides an abstraction layer for accessing the Native Contacts API. * The underlying API to be used should be the most suitable for the SDK version of the device. */ public abstract class NativeContactsApi { /** * 360 client account type. */ protected static final int PEOPLE_ACCOUNT_TYPE = 1; /** * Google account type. */ protected static final int GOOGLE_ACCOUNT_TYPE = 2; /** * Vendor specific type. */ protected static final int PHONE_ACCOUNT_TYPE = 3; /** * Account type for 360 People in the Native Accounts. * MUST be a copy of type in 'res/xml/authenticator.xml' */ protected static final String PEOPLE_ACCOUNT_TYPE_STRING = "com.vodafone360.people.android.account"; /** * Google account, there can be more than one of these */ protected static final String GOOGLE_ACCOUNT_TYPE_STRING = "com.google"; /** * There are devices with custom contact applications. For them we need * special handling of contacts. */ protected static final String[] VENDOR_SPECIFIC_ACCOUNTS = { "com.htc.android.pcsc", "vnd.sec.contact.phone", "com.motorola.blur.service.bsutils.MOTHER_USER_CREDS_TYPE" }; /** * {@link NativeContactsApi} the singleton instance providing access to the correct Contacts API interface */ private static NativeContactsApi sInstance; /** * {@link Context} to be used by the Instance */ protected Context mContext; /** * {@link ContentResolver} be used by the Instance */ protected ContentResolver mCr; /** * Sadly have to have this so that only one organization may be read from a * NAB Contact */ protected boolean mHaveReadOrganization = false; /** * Sadly have to have this because Organization detail is split into two * details in CAB */ protected int mMarkedOrganizationIndex = -1; /** * Sadly have to have this because Organization detail is split into two * details in CAB */ protected int mMarkedTitleIndex = -1; /** * Create NativeContactsApi singleton instance for later usage. The instance * can retrieved by calling getInstance(). * The instance can be destroyed * by calling destroyInstance() * * @see NativeContactsApi#getInstance() * @see NativeContactsApi#destroyInstance() * @param context The context to be used by the singleton */ public static void createInstance(Context context) { LogUtils.logW("NativeContactsApi.createInstance()"); String className; if (VersionUtils.is2XPlatform()) { className = "NativeContactsApi2"; LogUtils.logD("Using 2.X Native Contacts API"); } else { className = "NativeContactsApi1"; LogUtils.logD("Using 1.X Native Contacts API"); } try { Class<? extends NativeContactsApi> clazz = Class.forName( NativeContactsApi.class.getPackage().getName() + "." + className).asSubclass( NativeContactsApi.class); sInstance = clazz.newInstance(); } catch (Exception e) { throw new IllegalStateException("NativeContactsApi.createInstance()" + "Error creating a subclass of NativeContactsApi", e); } sInstance.mContext = context; sInstance.mCr = context.getContentResolver(); // Initialize the instance now (got Context and Content Resolver) sInstance.initialize(); } /** * Destroy NativeContactsApi singleton instance if created. The instance can * be recreated by calling createInstance() * * @see NativeContactsApi#createInstance() */ public static void destroyInstance() { if (sInstance != null) { sInstance.mCr = null; sInstance.mContext = null; sInstance = null; } } /** * Retrieves singleton instance providing access to the native contacts api. * * @return {@link NativeContactsApi} appropriate subclass instantiation */ public static NativeContactsApi getInstance() { if (sInstance == null) { throw new InvalidParameterException("Please call " + "NativeContactsApi.createInstance() " + "before NativeContactsApi.getInstance()"); } return sInstance; } /** * This Account class represents an available account on the device where * the native synchronization can be performed. */ public static class Account { /** * The name of the account. */ private String mName; /** * The type of the account. */ private String mType; /** * The Constructor. * * @param name the account name * @param type the account type */ public Account(String name, String type) { mName = name; mType = type; } /** * Gets the name of the account. * * @return the account name */ public String getName() { return mName; } /** * Gets the type of the accounts. * * @return the account type */ public String getType() { return mType; } /** * Checks if this account is a People Account * * @return true if this account is a People Account, false if not */ public boolean isPeopleAccount() { return TextUtils.equals(mType, PEOPLE_ACCOUNT_TYPE_STRING); } /** * Returns a String representation of the account. */ public String toString() { return "Account: name=" + mName + ", type=" + mType; } } /** * The Observer interface to receive notifications about changes in the * native address book. */ public static interface ContactsObserver { /** * Call-back to notify that a change happened in the native address * book. */ void onChange(); } /** * Method meant to be called only just after createInstance() is invoked. * This method effectively acts as a replacement for the constructor because * of the use of reflection. */ protected abstract void initialize(); /** * Registers a content observer. Note: the method only supports one observer * at a time. * * @param observer ContactsObserver currently observing native address book * changes * @throws RuntimeException if a new observer is being registered without * having unregistered the previous one */ public abstract void registerObserver(ContactsObserver observer); /** * Unregister the previously registered content observer. */ public abstract void unregisterObserver(); /** * Fetches all the existing Accounts on the device. Only supported on 2.X. * The 1.X implementation always returns null. * * @return An array containing all the Accounts on the device, or null if * none exist */ public abstract Account[] getAccounts(); /** * Fetches all the existing Accounts on the device corresponding to the * provided Type Only supported on 2.X. The 1.X implementation always * returns null. * * @param type The Type of Account to fetch * @return An array containing all the Accounts of the provided Type, or * null if none exist */ public abstract Account[] getAccountsByType(int type); /** * Adds the currently logged in user account to the NAB accounts. Only * supported on 2.X. The 1.X implementation does nothing. * * @return true if successful, false if not */ public abstract boolean addPeopleAccount(String username); /** * Checks if there is a People Account in the NAB Accounts. Only supported * on 2.X The 1.X implementation does nothing. * * @return true if an account exists, false if not. */ public abstract boolean isPeopleAccountCreated(); - + /** * Removes the (first found) People Account from the NAB accounts. Only * supported on 2.X. The 1.X implementation does nothing. */ public abstract void removePeopleAccount(); /** * Retrieves a list of contact IDs for a specific account. In 1.X devices * only the null account is supported, i.e., a non null account always uses * null as a return value. * * @param account The account to get contact IDs from (may be null) * @return List of contact IDs from the native address book */ public abstract long[] getContactIds(Account account); /** * Gets data for one Contact. * * @param nabContactId Native ID for the contact * @return A {@link ContactChange} array with contact's data or null */ public abstract ContactChange[] getContact(long nabContactId); /** * Adds a contact. Note that the returned ID data will be the same size of * ccList plus one change containing the NAB Contact ID (at the first * position). The remaining IDs correspond to the details in the original * change list. Null IDs among these remaining IDs are possible when these * correspond to unsupported details. On 1.X Devices only a null account * parameter is expected. * * @param account Account to be associated with the added contact (may be * null). * @param ccList The Contact data as a {@link ContactChange} array * @return A {@link ContactChange} array with contact's new ID data or null * in case of failure. */ public abstract ContactChange[] addContact(Account account, ContactChange[] ccList); /** * Updates an existing contact. The returned ID data will be the same size * of the ccList. However, if a null or empty ccList is passed as an * argument then null is returned. Null IDs among the ID data are also * possible when these correspond to unsupported details. * * @param ccList The Contact update data as a {@link ContactChange} array * @return A {@link ContactChange} array with the contact's new ID data or * null */ public abstract ContactChange[] updateContact(ContactChange[] ccList); /** * Removes a contact * * @param nabContactId Native ID of the contact to remove */ public abstract void removeContact(long nabContactId); /** * Used to retrieve the master Auto-sync setting for the system. * Method only exists to get around platform fragmentation. * Note that this method always returns true for 1.X devices! * @return true if the Master Auto-sync is enabled, false otherwise */ public abstract boolean getMasterSyncAutomatically(); + + /** + * Used to set the system syncable functionality on and off. + * This is really only useful for 2.X devices. + * @param syncable if true, false otherwise + */ + public abstract void setSyncable(boolean syncable); /** * Used to forcefully set the underlying Sync adapter to be Automatically Syncable or not. * This is really only useful for 2.X devices and for System UE. * @param syncAutomatically if true Sync is Automatic, false otherwise */ public abstract void setSyncAutomatically(boolean syncAutomatically); /** * Checks whether or not a {@link ContactChange} key is supported. Results * may vary in 1.X and 2.X * * @param key Key to check for support * @return true if supported, false if not */ public abstract boolean isKeySupported(int key); /** * Checks if this account is a vendor specific one. All vendor specific * accounts are held in the VENDOR_SPECIFIC_ACCOUNTS array. * * @param type to checks for * @return true if vendor specific account, false otherwise */ public boolean isVendorSpecificAccount(String type) { for (String vendorSpecificType : VENDOR_SPECIFIC_ACCOUNTS) { if (vendorSpecificType.equals(type)) { return true; } } return false; } } diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java index 39862b9..50e992e 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java @@ -1,933 +1,941 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.List; import android.content.ContentUris; import android.content.ContentValues; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.provider.Contacts; import android.provider.Contacts.ContactMethods; import android.provider.Contacts.Organizations; import android.provider.Contacts.People; import android.provider.Contacts.Phones; import android.text.TextUtils; import android.util.SparseIntArray; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.VCardHelper.Name; import com.vodafone360.people.datatypes.VCardHelper.Organisation; import com.vodafone360.people.datatypes.VCardHelper.PostalAddress; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.LogUtils; /** * The implementation of the NativeContactsApi for the Android 1.X platform. */ @SuppressWarnings("deprecation") // Needed to hide warnings because we are using deprecated 1.X native apis // APIs public class NativeContactsApi1 extends NativeContactsApi { /** * Convenience Contact ID Projection. */ private final static String[] CONTACTID_PROJECTION = { People._ID }; /** * Convenience Projection for the NATE and NOTES from the People table */ private final static String[] PEOPLE_PROJECTION = { People.NAME, People.NOTES }; /** * Contact methods table kind value for email. */ private static final int CONTACT_METHODS_KIND_EMAIL = 1; /** * Contact methods table kind value for postal address. */ private static final int CONTACT_METHODS_KIND_ADDRESS = 2; /** * Mapping of supported {@link ContactChange} Keys. */ private static final SparseIntArray sSupportedKeys; static { sSupportedKeys = new SparseIntArray(7); sSupportedKeys.append(ContactChange.KEY_VCARD_NAME, 0); sSupportedKeys.append(ContactChange.KEY_VCARD_PHONE, 0); sSupportedKeys.append(ContactChange.KEY_VCARD_EMAIL, 0); sSupportedKeys.append(ContactChange.KEY_VCARD_ADDRESS, 0); sSupportedKeys.append(ContactChange.KEY_VCARD_ORG, 0); sSupportedKeys.append(ContactChange.KEY_VCARD_TITLE, 0); sSupportedKeys.append(ContactChange.KEY_VCARD_NOTE, 0); } /** * Values used for writing to NAB */ private final ContentValues mValues = new ContentValues(); /** * The registered ContactsObserver. * * @see #registerObserver(ContactsObserver) */ private ContactsObserver mContactsObserver; /** * The observer for the native contacts. */ private ContentObserver mNativeObserver; /** * @see NativeContactsApi#initialize() */ @Override protected void initialize() { // Nothing to do } /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { if (mContactsObserver != null) { throw new RuntimeException( "NativeContactsApi1.registerObserver(): current implementation only supports one observer" + " at a time... Please unregister first."); } mContactsObserver = observer; mNativeObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { mContactsObserver.onChange(); } }; mCr.registerContentObserver(Contacts.CONTENT_URI, true, mNativeObserver); } /** * @see NativeContactsApi#unregisterObserver() */ @Override public void unregisterObserver() { if (mContactsObserver != null) { mContactsObserver = null; mCr.unregisterContentObserver(mNativeObserver); mNativeObserver = null; } } /** * @see NativeContactsApi#getAccounts() */ @Override public Account[] getAccounts() { // No accounts on 1.X NAB return null; } /** * @see NativeContactsApi#getAccountsByType(String) */ @Override public Account[] getAccountsByType(int type) { // No accounts on 1.X NAB return null; } /** * @see NativeContactsApi#addPeopleAccount(String) */ @Override public boolean addPeopleAccount(String username) { // No People Accounts on 1.X NAB return false; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { // No People Accounts on 1.X NAB return false; } /** * @see NativeContactsApi#removePeopleAccount() */ @Override public void removePeopleAccount() { // No People Accounts on 1.X NAB } /** * @see NativeContactsApi#getContactIds(Account) */ @Override public long[] getContactIds(Account account) { if (account != null) { // Accounts not supported in 1.X, just return null LogUtils.logE("NativeContactsApi1.getContactIds() Unexpected non-null Account(\"" + account.toString() + "\""); return null; } long[] ids = null; final Cursor cursor = mCr.query(People.CONTENT_URI, CONTACTID_PROJECTION, null, null, People._ID); try { final int idCount = cursor.getCount(); if (idCount > 0) { ids = new long[idCount]; int index = 0; while (cursor.moveToNext()) { ids[index] = cursor.getLong(0); index++; } } } finally { CursorUtils.closeCursor(cursor); } return ids; } /** * @see NativeContactsApi#getContact(long) */ @Override public ContactChange[] getContact(long nabContactId) { final List<ContactChange> ccList = new ArrayList<ContactChange>(); final Cursor cursor = mCr.query(ContentUris .withAppendedId(People.CONTENT_URI, nabContactId), PEOPLE_PROJECTION, null, null, null); try { if (cursor.moveToNext()) { final String displayName = CursorUtils.getString(cursor, People.NAME); if (!TextUtils.isEmpty(displayName)) { // TODO: Remove if really not necessary // final Name name = parseRawName(displayName); final Name name = new Name(); name.firstname = displayName; final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NAME, VCardHelper.makeName(name), ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); ccList.add(cc); } // Note final String note = CursorUtils.getString(cursor, People.NOTES); if (!TextUtils.isEmpty(note)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NOTE, note, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); ccList.add(cc); } // Remaining contact details readContactPhoneNumbers(ccList, nabContactId); readContactMethods(ccList, nabContactId); readContactOrganizations(ccList, nabContactId); } } finally { CursorUtils.closeCursor(cursor); } return ccList.toArray(new ContactChange[ccList.size()]); } /** * @see NativeContactsApi#addContact(Account, ContactChange[]) */ @Override public ContactChange[] addContact(Account account, ContactChange[] ccList) { if (account != null) { // Accounts not supported in 1.X, just return null return null; } /* * These details need special treatment: Name and Note (written to * people table); Organization/Title (written as one detail in NAB). */ mMarkedOrganizationIndex = mMarkedTitleIndex = -1; preprocessContactToAdd(ccList); Uri uri = mCr.insert(People.CONTENT_URI, mValues); if (uri != null) { // Change List to hold resulting changes for the add contact // (including +1 for contact id) final ContactChange[] idChangeList = new ContactChange[ccList.length + 1]; final long nabContactId = ContentUris.parseId(uri); idChangeList[0] = ContactChange.createIdsChange(ccList[0], ContactChange.TYPE_UPDATE_NAB_CONTACT_ID); idChangeList[0].setNabContactId(nabContactId); writeDetails(ccList, idChangeList, nabContactId); processOrganization(ccList, idChangeList, nabContactId); return idChangeList; } return null; } /** * @see NativeContactsApi#updateContact(ContactChange[]) */ @Override public ContactChange[] updateContact(ContactChange[] ccList) { if (ccList == null || ccList.length == 0) { LogUtils.logW("NativeContactsApi1.updateContact() nothing to update - empty ccList!"); return null; } mMarkedOrganizationIndex = mMarkedTitleIndex = -1; final long nabContactId = ccList[0].getNabContactId(); final int ccListSize = ccList.length; final ContactChange[] idCcList = new ContactChange[ccListSize]; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc.getKey() == ContactChange.KEY_VCARD_ORG) { if (mMarkedOrganizationIndex < 0) { mMarkedOrganizationIndex = i; } continue; } if (cc.getKey() == ContactChange.KEY_VCARD_TITLE) { if (mMarkedTitleIndex < 0) { mMarkedTitleIndex = i; } continue; } switch (cc.getType()) { case ContactChange.TYPE_ADD_DETAIL: final int key = cc.getKey(); if (key != ContactChange.KEY_VCARD_NAME && key != ContactChange.KEY_VCARD_NOTE) { final long nabDetailId = insertDetail(cc, nabContactId); if (nabDetailId != ContactChange.INVALID_ID) { idCcList[i] = ContactChange.createIdsChange(cc, ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idCcList[i].setNabDetailId(nabDetailId); } } else { // Name and Note are not inserted but updated because // they are always there! updateDetail(cc); } break; case ContactChange.TYPE_UPDATE_DETAIL: updateDetail(cc); break; case ContactChange.TYPE_DELETE_DETAIL: deleteDetail(cc.getKey(), nabContactId, cc.getNabDetailId()); break; default: break; } } final long orgDetailId = updateOrganization(ccList, nabContactId); if (orgDetailId != ContactChange.INVALID_ID) { if (mMarkedOrganizationIndex >= 0 && ccList[mMarkedOrganizationIndex].getType() == ContactChange.TYPE_ADD_DETAIL) { idCcList[mMarkedOrganizationIndex] = ContactChange.createIdsChange( ccList[mMarkedOrganizationIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idCcList[mMarkedOrganizationIndex].setNabDetailId(orgDetailId); } if (mMarkedTitleIndex >= 0 && ccList[mMarkedTitleIndex].getType() == ContactChange.TYPE_ADD_DETAIL) { idCcList[mMarkedTitleIndex] = ContactChange.createIdsChange( ccList[mMarkedTitleIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idCcList[mMarkedTitleIndex].setNabDetailId(orgDetailId); } } return idCcList; } /** * @see NativeContactsApi#removeContact(long) */ @Override public void removeContact(long nabContactId) { Uri rawContactUri = ContentUris.withAppendedId(People.CONTENT_URI, nabContactId); mCr.delete(rawContactUri, null, null); } - + + /** + * @see NativeContactsApi#setSyncAutomatically(boolean) + */ + @Override + public void setSyncAutomatically(boolean syncAutomatically) { + // Nothing to do + } + /** - * @see NativeContactsApi#getMasterSyncAutomatically + * @see NativeContactsApi#isKeySupported(int) */ @Override public boolean getMasterSyncAutomatically() { // Always true in 1.X return true; } - + /** - * @see NativeContactsApi#setSyncAutomatically(boolean) - */ + * @see NativeContactsApi#setSyncable(boolean) + */ @Override - public void setSyncAutomatically(boolean syncAutomatically) { + public void setSyncable(boolean syncable) { // Nothing to do } /** * @see NativeContactsApi#isKeySupported(int) */ @Override public boolean isKeySupported(int key) { return sSupportedKeys.indexOfKey(key) >= 0; } /** * Reads Phone Number details from a Contact into the provided * {@link ContactChange} List * * @param ccList {@link ContactChange} list to add details into * @param nabContactId ID of the NAB Contact */ private void readContactPhoneNumbers(List<ContactChange> ccList, long nabContactId) { final Uri contactUri = ContentUris.withAppendedId(People.CONTENT_URI, nabContactId); final Uri phoneUri = Uri.withAppendedPath(contactUri, People.Phones.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(phoneUri, null, null, null, null); if (cursor == null) { return; } try { while (cursor.moveToNext()) { final ContactChange cc = readContactPhoneNumber(cursor); if (cc != null) { cc.setNabContactId(nabContactId); ccList.add(cc); } } } finally { CursorUtils.closeCursor(cursor); } } /** * Reads one Phone Number Detail from the supplied cursor into a * {@link ContactChange} * * @param cursor Cursor to read from * @return Read Phone Number Detail or null */ private ContactChange readContactPhoneNumber(Cursor cursor) { ContactChange cc = null; final String phoneNumber = CursorUtils.getString(cursor, Phones.NUMBER); if (!TextUtils.isEmpty(phoneNumber)) { final long nabDetailId = CursorUtils.getLong(cursor, Phones._ID); final boolean isPrimary = CursorUtils.getInt(cursor, Phones.ISPRIMARY) != 0; final int rawType = CursorUtils.getInt(cursor, Phones.TYPE); int flags = mapFromNabPhoneType(rawType); if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } cc = new ContactChange(ContactChange.KEY_VCARD_PHONE, phoneNumber, flags); cc.setNabDetailId(nabDetailId); } return cc; } /** * Reads Contact Method details from a Contact into the provided * {@link ContactChange} List * * @param ccList {@link ContactChange} list to add details into * @param nabContactId ID of the NAB Contact */ private void readContactMethods(List<ContactChange> ccList, long nabContactId) { Uri contactUri = ContentUris.withAppendedId(People.CONTENT_URI, nabContactId); Uri contactMethodUri = Uri.withAppendedPath(contactUri, People.ContactMethods.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(contactMethodUri, null, null, null, null); if (cursor == null) { return; } try { while (cursor.moveToNext()) { final ContactChange cc = readContactMethod(cursor); if (cc != null) { cc.setNabContactId(nabContactId); ccList.add(cc); } } } finally { CursorUtils.closeCursor(cursor); } } /** * Reads one Contact Method Detail from the supplied cursor into a * {@link ContactChange} * * @param cursor Cursor to read from * @return Read Contact Method Detail or null */ private ContactChange readContactMethod(Cursor cursor) { ContactChange cc = null; final String value = CursorUtils.getString(cursor, ContactMethods.DATA); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, ContactMethods._ID); final boolean isPrimary = CursorUtils.getInt(cursor, ContactMethods.ISPRIMARY) != 0; final int kind = CursorUtils.getInt(cursor, ContactMethods.KIND); final int type = CursorUtils.getInt(cursor, ContactMethods.TYPE); int flags = mapFromNabContactMethodType(type); if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } if (kind == CONTACT_METHODS_KIND_EMAIL) { cc = new ContactChange(ContactChange.KEY_VCARD_EMAIL, value, flags); cc.setNabDetailId(nabDetailId); } else if (kind == CONTACT_METHODS_KIND_ADDRESS) { if (!TextUtils.isEmpty(value)) { cc = new ContactChange(ContactChange.KEY_VCARD_ADDRESS, VCardHelper .makePostalAddress(parseRawAddress(value)), flags); cc.setNabDetailId(nabDetailId); } } } return cc; } /** * Reads Organization details from a Contact into the provided * {@link ContactChange} List * * @param ccList {@link ContactChange} list to add details into * @param nabContactId ID of the NAB Contact */ private void readContactOrganizations(List<ContactChange> ccList, long nabContactId) { final Uri contactUri = ContentUris.withAppendedId(People.CONTENT_URI, nabContactId); final Uri contactOrganizationsUri = Uri.withAppendedPath(contactUri, Contacts.Organizations.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(contactOrganizationsUri, null, null, null, Organizations._ID); if (cursor == null) { return; } try { // Only loops while there is not Organization read (CAB limitation!) while (!mHaveReadOrganization && cursor.moveToNext()) { readContactOrganization(cursor, ccList, nabContactId); } } finally { CursorUtils.closeCursor(cursor); } // Reset the boolean flag mHaveReadOrganization = false; } /** * Reads one Organization Detail from the supplied cursor into a * {@link ContactChange} Note that this method may actually read up to 2 * into Contact Changes. However, Organization and Title may only be read if * a boolean flag is not set * * @param cursor Cursor to read from * @param ccList {@link ContactChange} list to add details to * @param nabContactId ID of the NAB Contact * @return Read Contact Method Detail or null */ private void readContactOrganization(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final long nabDetailId = CursorUtils.getLong(cursor, Organizations._ID); final boolean isPrimary = CursorUtils.getInt(cursor, Organizations.ISPRIMARY) != 0; final int type = CursorUtils.getInt(cursor, Organizations.TYPE); int flags = mapFromNabOrganizationType(type); if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } if (!mHaveReadOrganization) { // Company final String company = CursorUtils.getString(cursor, Organizations.COMPANY); if (!TextUtils.isEmpty(company)) { // Escaping the value (no need to involve the VCardHelper just // for the company) final String escapedCompany = company.replace(";", "\\;"); final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_ORG, escapedCompany, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } // Title final String title = CursorUtils.getString(cursor, Organizations.TITLE); if (!TextUtils.isEmpty(title)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_TITLE, title, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } } } /** * "Pre-processing" of {@link ContactChange} list before it can be added to * NAB. This needs to be done because of issues on the 1.X NAB and our CAB * In 1.X NAB: Name and Note which are stored differently from other details * In our CAB: Organization and Title are separate details contrary to the * NAB * * @param ccList {@link ContactChange} list for the add operation */ private void preprocessContactToAdd(ContactChange[] ccList) { final int ccListSize = ccList.length; boolean nameFound = false, noteFound = false; mValues.clear(); for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc != null) { if (!nameFound && cc.getKey() == ContactChange.KEY_VCARD_NAME) { final Name name = VCardHelper.getName(cc.getValue()); mValues.put(People.NAME, name.toString()); nameFound = true; } if (!noteFound && cc.getKey() == ContactChange.KEY_VCARD_NOTE) { mValues.put(People.NOTES, cc.getValue()); noteFound = true; } if (mMarkedOrganizationIndex < 0 && cc.getKey() == ContactChange.KEY_VCARD_ORG) { mMarkedOrganizationIndex = i; } if (mMarkedTitleIndex < 0 && cc.getKey() == ContactChange.KEY_VCARD_TITLE) { mMarkedTitleIndex = i; } } } } /** * Writes new details from a provided {@link ContactChange} list into the * NAB. The resulting detail IDs are put in another provided * {@link ContactChange} list. * * @param ccList {@link ContactChange} list to write from * @param idChangeList {@link ContatChange} list where IDs for the written * details are put * @param nabContactId ID of the NAB Contact */ private void writeDetails(ContactChange[] ccList, ContactChange[] idChangeList, long nabContactId) { final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc != null) { long nabDetailId = insertDetail(cc, nabContactId); if (nabDetailId != ContactChange.INVALID_ID) { // The +1 assumes prior addition of the contact id at // position 0 idChangeList[i + 1] = ContactChange.createIdsChange(cc, ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChangeList[i + 1].setNabDetailId(nabDetailId); } } } } /** * Inserts a new detail to NAB * * @param cc {@link ContactChange} to read data from * @param nabContactId ID of the NAB Contact * @return The created detail's ID */ private long insertDetail(ContactChange cc, long nabContactId) { mValues.clear(); Uri contentUri = null; switch (cc.getKey()) { case ContactChange.KEY_VCARD_PHONE: putPhoneValues(cc, nabContactId); contentUri = Phones.CONTENT_URI; break; case ContactChange.KEY_VCARD_EMAIL: putContactMethodValues(cc, CONTACT_METHODS_KIND_EMAIL, nabContactId); contentUri = ContactMethods.CONTENT_URI; break; case ContactChange.KEY_VCARD_ADDRESS: putContactMethodValues(cc, CONTACT_METHODS_KIND_ADDRESS, nabContactId); contentUri = ContactMethods.CONTENT_URI; break; } if (contentUri != null) { Uri uri = mCr.insert(contentUri, mValues); if (uri != null) { return ContentUris.parseId(uri); } } return ContactChange.INVALID_ID; } /** * Updates a detail. * * @param cc {@link ContactChange} to read data from * @param nabContactId ID of the NAB Contact * @return true if the detail was updated, false if not */ private boolean updateDetail(ContactChange cc) { mValues.clear(); Uri contentUri = null; long nabDetailId = cc.getNabDetailId(); final long nabContactId = cc.getNabContactId(); switch (cc.getKey()) { case ContactChange.KEY_VCARD_PHONE: putPhoneValues(cc, nabContactId); contentUri = Phones.CONTENT_URI; break; case ContactChange.KEY_VCARD_EMAIL: putContactMethodValues(cc, CONTACT_METHODS_KIND_EMAIL, nabContactId); contentUri = ContactMethods.CONTENT_URI; break; case ContactChange.KEY_VCARD_ADDRESS: putContactMethodValues(cc, CONTACT_METHODS_KIND_ADDRESS, nabContactId); contentUri = ContactMethods.CONTENT_URI; break; case ContactChange.KEY_VCARD_NAME: final Name name = VCardHelper.getName(cc.getValue()); mValues.put(People.NAME, name.toString()); contentUri = People.CONTENT_URI; nabDetailId = nabContactId; break; case ContactChange.KEY_VCARD_NOTE: mValues.put(People.NOTES, cc.getValue()); contentUri = People.CONTENT_URI; nabDetailId = nabContactId; break; } if (contentUri != null) { Uri uri = ContentUris.withAppendedId(contentUri, nabDetailId); return mCr.update(uri, mValues, null, null) > 0; } return false; } /** * Deletes a detail from NAB * * @param key The detail key * @param nabContactId ID of the NAB Contact * @param nabDetailId ID of the NAB Detail * @return true if the detail was deleted, false if not */ private boolean deleteDetail(int key, long nabContactId, long nabDetailId) { mValues.clear(); Uri contentUri = null; switch (key) { case ContactChange.KEY_VCARD_PHONE: contentUri = Phones.CONTENT_URI; break; case ContactChange.KEY_VCARD_EMAIL: case ContactChange.KEY_VCARD_ADDRESS: contentUri = ContactMethods.CONTENT_URI; break; case ContactChange.KEY_VCARD_NAME: mValues.putNull(People.NAME); contentUri = People.CONTENT_URI; nabDetailId = nabContactId; break; case ContactChange.KEY_VCARD_NOTE: mValues.putNull(People.NOTES); contentUri = People.CONTENT_URI; nabDetailId = nabContactId; break; } if (contentUri != null) { final Uri uri = ContentUris.withAppendedId(contentUri, nabDetailId); if (mValues.size() > 0) { return mCr.update(uri, mValues, null, null) > 0; } else { return mCr.delete(uri, null, null) > 0; } } return false; } /** * Put Phone detail into the values * * @param cc * @param nabContactId ID of the NAB Contact */ private void putPhoneValues(ContactChange cc, long nabContactId) { mValues.put(Phones.PERSON_ID, nabContactId); mValues.put(Phones.NUMBER, cc.getValue()); int flags = cc.getFlags(); mValues.put(Phones.TYPE, mapToNabPhoneType(flags)); mValues.put(Phones.ISPRIMARY, flags & ContactChange.FLAG_PREFERRED); /* * Forcing the label field to be null because we don't support custom * labels and in case we replace from a custom label to home or private * type without setting label to null, mCr.update() will throw a SQL * constraint exception. */ mValues.put(Phones.LABEL, (String)null); } /** * Put Contact Methods detail into the values * * @param cc {@link ContactChange} to read values from * @param kind The kind of contact method (email or address) * @param nabContactId ID of the NAB Contact */ private void putContactMethodValues(ContactChange cc, int kind, long nabContactId) { mValues.put(ContactMethods.PERSON_ID, nabContactId); if (kind == CONTACT_METHODS_KIND_EMAIL) { mValues.put(ContactMethods.DATA, cc.getValue()); } else { // Must be Address, once again need to use VCardHelper to extract // address PostalAddress address = VCardHelper.getPostalAddress(cc.getValue()); mValues.put(ContactMethods.DATA, address.toString()); } mValues.put(ContactMethods.KIND, kind); int flags = cc.getFlags(); mValues.put(ContactMethods.TYPE, mapToNabContactMethodType(flags)); mValues.put(ContactMethods.ISPRIMARY, flags & ContactChange.FLAG_PREFERRED); } /** * Ugly method to process organization for writing to NAB * * @param ccList {@link ContactChange} list to fetch organization from * @param idChangeList {@link ContatChange} list where IDs for the written * organization are put * @param nabContactId ID of the NAB Contact */ private void processOrganization(ContactChange[] ccList, ContactChange[] idChangeList, long nabContactId) { final long organizationId = writeOrganization(ccList, nabContactId); if (organizationId != ContactChange.INVALID_ID) { if (mMarkedOrganizationIndex >= 0) { idChangeList[mMarkedOrganizationIndex + 1] = ContactChange.createIdsChange( ccList[mMarkedOrganizationIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChangeList[mMarkedOrganizationIndex + 1].setNabDetailId(organizationId); } if (mMarkedTitleIndex >= 0) { idChangeList[mMarkedTitleIndex + 1] = ContactChange.createIdsChange( ccList[mMarkedTitleIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChangeList[mMarkedTitleIndex + 1].setNabDetailId(organizationId); } } } /** * Write Organization detail to NAB * * @param ccList {@link ContactChange} list where Organization and Title are * found * @param nabContactId ID of the NAB Contact * @return ID of the NAB Contact */ private long writeOrganization(ContactChange[] ccList, long nabContactId) { mValues.clear(); int flags = ContactChange.FLAG_NONE; if (mMarkedOrganizationIndex >= 0) { final ContactChange cc = ccList[mMarkedOrganizationIndex]; final Organisation organization = VCardHelper.getOrg(cc.getValue()); if (!TextUtils.isEmpty(organization.name)) { mValues.put(Organizations.COMPANY, organization.name); flags |= cc.getFlags(); } } if (mMarkedTitleIndex >= 0) { final ContactChange cc = ccList[mMarkedTitleIndex]; // No need to check for empty values as there is only one flags |= cc.getFlags(); mValues.put(Organizations.TITLE, cc.getValue()); } if (mValues.size() > 0) { mValues.put(Organizations.PERSON_ID, nabContactId); mValues.put(Organizations.TYPE, mapToNabOrganizationType(flags)); final Uri uri = mCr.insert(Organizations.CONTENT_URI, mValues); if (uri != null) { diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index 9fe0e9d..3aa4137 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -32,1265 +32,1273 @@ import java.util.List; import android.accounts.AccountManager; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.OperationApplicationException; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.provider.ContactsContract; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.Settings; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Event; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.Website; import android.text.TextUtils; import android.util.SparseArray; import com.vodafone360.people.R; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.VCardHelper.Name; import com.vodafone360.people.datatypes.VCardHelper.Organisation; import com.vodafone360.people.datatypes.VCardHelper.PostalAddress; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * The implementation of the NativeContactsApi for the Android 2.X platform. */ public class NativeContactsApi2 extends NativeContactsApi { /** * Convenience Projection to fetch only a Raw Contact's ID and Native * Account Type */ private static final String[] CONTACTID_PROJECTION = new String[] { RawContacts._ID, RawContacts.ACCOUNT_TYPE }; /** * Raw ID Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_RAW_ID = 0; /** * Account Type Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_ACCOUNT_TYPE = 1; /** * Group ID Projection */ private static final String[] GROUPID_PROJECTION = new String[] { Groups._ID }; /** * Vendor specific account. Only used in 2.x API. */ private static Account sPhoneAccount = null; /** * Regular expression for a date that can be handled by the People Client at * present. Matches the following cases: N-n-n n-n-N Where: - 'n' * corresponds to one or two digits - 'N' corresponds to two or 4 digits */ private static final String COMPLETE_DATE_REGEX = "(?:^\\d{2,4}-\\d{1,2}-\\d{1,2}$|^\\d{1,2}-\\d{1,2}-\\d{2,4}$)"; /** * 'My Contacts' System group where clause */ private static final String MY_CONTACTS_GROUP_WHERE_CLAUSE = Groups.SYSTEM_ID + "=\"Contacts\""; /** * 'My Contacts' System Group Membership where in clause (Multiple 'My * Contacts' IDs) */ private static final String MY_CONTACTS_MULTI_GROUP_MEMBERSHIP = Data.MIMETYPE + "=\"" + GroupMembership.CONTENT_ITEM_TYPE + "\" AND " + Data.DATA1 + " IN ("; /** * Selection where clause for a NULL Account */ private static final String NULL_ACCOUNT_WHERE_CLAUSE = RawContacts.ACCOUNT_NAME + " IS NULL AND " + RawContacts.ACCOUNT_TYPE + " IS NULL"; /** * Selection where clause for an Organization detail. */ private static final String ORGANIZATION_DETAIL_WHERE_CLAUSE = RawContacts.Data.MIMETYPE + "=\"" + Organization.CONTENT_ITEM_TYPE + "\""; /** * The list of Uri that need to be listened to for contacts changes on * native side. */ private static final Uri[] sUri = { ContactsContract.RawContacts.CONTENT_URI, ContactsContract.Data.CONTENT_URI }; /** * Holds mapping from a NAB type (MIME) to a VCard Key */ private static final HashMap<String, Integer> sFromNabContentTypeToKeyMap; /** * Holds mapping from a VCard Key to a NAB type (MIME) */ private static final SparseArray<String> sFromKeyToNabContentTypeArray; static { sFromNabContentTypeToKeyMap = new HashMap<String, Integer>(9, 1); sFromNabContentTypeToKeyMap.put(StructuredName.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NAME); sFromNabContentTypeToKeyMap.put(Nickname.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NICKNAME); sFromNabContentTypeToKeyMap.put(Phone.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_PHONE); sFromNabContentTypeToKeyMap.put(Email.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_EMAIL); sFromNabContentTypeToKeyMap.put(StructuredPostal.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ADDRESS); sFromNabContentTypeToKeyMap .put(Organization.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ORG); sFromNabContentTypeToKeyMap.put(Website.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_URL); sFromNabContentTypeToKeyMap.put(Note.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NOTE); sFromNabContentTypeToKeyMap.put(Event.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_DATE); // sFromNabContentTypeToKeyMap.put( // Photo.CONTENT_ITEM_TYPE, ContactChange.KEY_PHOTO); sFromKeyToNabContentTypeArray = new SparseArray<String>(10); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NAME, StructuredName.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NICKNAME, Nickname.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_PHONE, Phone.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_EMAIL, Email.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ADDRESS, StructuredPostal.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ORG, Organization.CONTENT_ITEM_TYPE); // Special case: VCARD_TITLE maps to the same NAB type as sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_TITLE, Organization.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_URL, Website.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NOTE, Note.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_DATE, Event.CONTENT_ITEM_TYPE); // sFromKeyToNabContentTypeArray.append( // ContactChange.KEY_PHOTO, Photo.CONTENT_ITEM_TYPE); } /** * The observer registered by the upper layer. */ private ContactsObserver mAbstractedObserver; /** * Content values used for writing to NAB. */ private final ContentValues mValues = new ContentValues(); /** * The content observers that listens for native contacts changes. */ private final ContentObserver[] mContentObservers = new ContentObserver[sUri.length]; /** * Array of row ID in the groups table to the "My Contacts" System Group. * The reason for this being an array is because there may be multiple * "My Contacts" groups (Platform Bug!?). */ private long[] mMyContactsGroupRowIds = null; /** * Arguably another example where Organization and Title force us into extra * effort. We use this value to pass the correct detail ID when an 'add * detail' is done for one the two although the other is already present. * Make sure to reset this value for every UpdateContact operation */ private long mExistingOrganizationId = ContactChange.INVALID_ID; /** * Flag to check if we have already read a Birthday detail */ private boolean mHaveReadBirthday = false; /** * Yield value for our ContentProviderOperations. */ private boolean mYield = true; /** * Batch used for Contact Writing operations. */ private BatchOperation mBatch = new BatchOperation(); /** * Inner class for applying batches. TODO: Move to own class if batches * become supported in other areas */ private class BatchOperation { // List for storing the batch mOperations ArrayList<ContentProviderOperation> mOperations; /** * Default constructor */ public BatchOperation() { mOperations = new ArrayList<ContentProviderOperation>(); } /** * Current size of the batch * * @return Size of the batch */ public int size() { return mOperations.size(); } /** * Adds a new operation to the batch * * @param cpo The */ public void add(ContentProviderOperation cpo) { mOperations.add(cpo); } /** * Clears all operations in the batch Effectively resets the batch. */ public void clear() { mOperations.clear(); } public ContentProviderResult[] execute() { ContentProviderResult[] resultArray = null; if (mOperations.size() > 0) { // Apply the mOperations to the content provider try { resultArray = mCr.applyBatch(ContactsContract.AUTHORITY, mOperations); } catch (final OperationApplicationException e1) { LogUtils.logE("storing contact data failed", e1); } catch (final RemoteException e2) { LogUtils.logE("storing contact data failed", e2); } mOperations.clear(); } return resultArray; } } /** * Convenience interface to map the generic DATA column names to the People * profile detail column names. */ private interface PeopleProfileColumns { /** * 360 People profile MIME Type */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/com.vodafone360.people.profile"; /** * 360 People Contact's profile ID (Corresponds to Contact's Internal * Contact ID) */ public static final String DATA_PID = Data.DATA1; /** * 360 People Contact profile Summary */ public static final String DATA_SUMMARY = Data.DATA2; /** * 360 People Contact profile detail */ public static final String DATA_DETAIL = Data.DATA3; } /** * This class holds a native content observer that will be notified in case * of changes on the registered URI. */ private class NativeContentObserver extends ContentObserver { public NativeContentObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { LogUtils.logI("NativeContactsApi2.NativeContentObserver.onChange(" + selfChange + ")"); mAbstractedObserver.onChange(); } } /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { LogUtils.logI("NativeContactsApi2.registerObserver()"); if (mAbstractedObserver != null) { throw new RuntimeException( "Only one observer at a time supported... Please unregister first."); } mAbstractedObserver = observer; final ContentResolver cr = mContext.getContentResolver(); for (int i = 0; i < mContentObservers.length; i++) { mContentObservers[i] = new NativeContentObserver(); cr.registerContentObserver(sUri[i], true, mContentObservers[i]); } } /** * @see NativeContactsApi#unregisterObserver(ContactsObserver) */ @Override public void unregisterObserver() { LogUtils.logI("NativeContactsApi2.unregisterObserver()"); if (mCr != null) { mAbstractedObserver = null; for (int i = 0; i < mContentObservers.length; i++) { if (mContentObservers[i] != null) { mCr.unregisterContentObserver(mContentObservers[i]); mContentObservers[i] = null; } } } } /** * @see NativeContactsApi#initialize() */ @Override protected void initialize() { // perform here any one time initialization sPhoneAccount = getVendorSpecificAccount(); } /** * @see NativeContactsApi#getAccounts() */ @Override public Account[] getAccounts() { AccountManager accountManager = AccountManager.get(mContext); final android.accounts.Account[] accounts2xApi = accountManager.getAccounts(); Account[] accounts = null; if (accounts2xApi.length > 0) { accounts = new Account[accounts2xApi.length]; for (int i = 0; i < accounts2xApi.length; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } } return accounts; } /** * Reads vendor specific accounts from settings and through accountmanager. * Some phones with custom ui like sense have additional account that we * have to take care of. This method tryes to read them * * @return Account object if vendor specific account is found, null * otherwise */ public Account getVendorSpecificAccount() { // first read the settings String[] PROJECTION = { Settings.ACCOUNT_NAME, Settings.ACCOUNT_TYPE, Settings.UNGROUPED_VISIBLE }; // Get a cursor with all people Cursor cursor = mCr.query(Settings.CONTENT_URI, PROJECTION, null, null, null); // Got no cursor? Return with null! if (null == cursor) { return null; } try { String[] values = new String[cursor.getCount()]; for (int i = 0; i < values.length; i++) { cursor.moveToNext(); if (isVendorSpecificAccount(cursor.getString(1))) { return new Account(cursor.getString(0), cursor.getString(1)); } } } catch (Exception exc) { return null; } CursorUtils.closeCursor(cursor); // nothing found in the settings? try accountmanager Account[] accounts = getAccounts(); if (accounts == null) { return null; } for (Account account : accounts) { if (isVendorSpecificAccount(account.getType())) { return account; } } return null; } /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override public Account[] getAccountsByType(int type) { switch (type) { // people and google type lead to the same block the difference is // then handled inside in two if statements. // Otherwise we would have a lot of redundant code, case PEOPLE_ACCOUNT_TYPE: case GOOGLE_ACCOUNT_TYPE: { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts2xApi = null; // For people account set the people account type string... if (PEOPLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); } // .. and for google the same only with google string. if (GOOGLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(GOOGLE_ACCOUNT_TYPE_STRING); } final int numAccounts = accounts2xApi.length; if (numAccounts > 0) { Account[] accounts = new Account[numAccounts]; for (int i = 0; i < numAccounts; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } return accounts; } else { return null; } } case PHONE_ACCOUNT_TYPE: { if (sPhoneAccount == null) { return null; } return new Account[] { sPhoneAccount }; } default: return null; } } /** * @see NativeContactsApi#addPeopleAccount(String) */ @Override public boolean addPeopleAccount(String username) { boolean isAdded = false; try { android.accounts.Account account = new android.accounts.Account(username, PEOPLE_ACCOUNT_TYPE_STRING); AccountManager accountMan = AccountManager.get(mContext); isAdded = accountMan.addAccountExplicitly(account, null, null); if (isAdded) { if (VersionUtils.isHtcSenseDevice(mContext)) { createSettingsEntryForAccount(username); } } } catch (Exception ex) { LogUtils.logE("People Account creation failed because of exception:\n", ex); } if (isAdded) { // Updating MyContacts Group IDs here for now because it needs to be // done one time just before first time sync. // In the future, this code may change if we modify // the way we retrieve contact IDs. fetchMyContactsGroupRowIds(); } return isAdded; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { - AccountManager accountMan = AccountManager.get(mContext); - android.accounts.Account[] accounts = accountMan - .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); - return accounts != null && accounts.length > 0; + return getPeopleAccount() != null; } /** * @see NativeContactsApi#removePeopleAccount() */ @Override public void removePeopleAccount() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); if (accounts != null && accounts.length > 0) { accountMan.removeAccount(accounts[0], null, null); } } /** * @see NativeContactsApi#getContactIds(Account) */ @Override public long[] getContactIds(Account account) { // Need to construct a where clause if (account != null) { final StringBuffer clauseBuffer = new StringBuffer(); clauseBuffer.append(RawContacts.ACCOUNT_NAME); clauseBuffer.append("=\""); clauseBuffer.append(account.getName()); clauseBuffer.append("\" AND "); clauseBuffer.append(RawContacts.ACCOUNT_TYPE); clauseBuffer.append("=\""); clauseBuffer.append(account.getType()); clauseBuffer.append('\"'); return getContactIds(clauseBuffer.toString()); } else { return getContactIds(NULL_ACCOUNT_WHERE_CLAUSE); } } /** * @see NativeContactsApi#getContact(long) */ @Override public ContactChange[] getContact(long nabContactId) { // Reset the boolean flags mHaveReadOrganization = false; mHaveReadBirthday = false; final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, nabContactId); final Uri dataUri = Uri.withAppendedPath(rawContactUri, RawContacts.Data.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(dataUri, null, null, null, null); try { if (cursor != null && cursor.getCount() > 0) { final List<ContactChange> ccList = new ArrayList<ContactChange>(); while (cursor.moveToNext()) { readDetail(cursor, ccList, nabContactId); } return ccList.toArray(new ContactChange[ccList.size()]); } } finally { CursorUtils.closeCursor(cursor); } return null; } /** * @see NativeContactsApi#addContact(Account, ContactChange[]) */ @Override public ContactChange[] addContact(Account account, ContactChange[] ccList) { // Make sure to reset all the member variables we need mYield = true; mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mValues.clear(); mBatch.clear(); mValues.put(RawContacts.ACCOUNT_TYPE, account.getType()); mValues.put(RawContacts.ACCOUNT_NAME, account.getName()); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI)).withYieldAllowed(mYield) .withValues(mValues); mBatch.add(builder.build()); // according to the calling method ccList here has at least 1 element, ccList[0] is not null final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc != null) { final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } putDetail(cc); addValuesToBatch(ContactChange.INVALID_ID); } } // Special case for the organization/title if it was flagged in the // putDetail call putOrganization(ccList); addValuesToBatch(ContactChange.INVALID_ID); // Add 360 profile detail addProfileAction(ccList[0].getInternalContactId()); // Execute the batch and Generate ID changes from it return executeNewContactBatch(ccList); } /** * @see NativeContactsApi#updateContact(ContactChange[]) */ @Override public ContactChange[] updateContact(ContactChange[] ccList) { if (ccList == null || ccList.length == 0) { LogUtils.logW("NativeContactsApi2.updateContact() nothing to update - empty ccList!"); return null; } // Make sure to reset all the member variables we need mYield = true; mBatch.clear(); mValues.clear(); mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mExistingOrganizationId = ContactChange.INVALID_ID; final long nabContactId = ccList[0].getNabContactId(); if (nabContactId == ContactChange.INVALID_ID) { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update request because of invalid NAB Contact ID. Internal Contact ID is " + ccList[0].getInternalContactId()); return null; } final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } switch (cc.getType()) { case ContactChange.TYPE_ADD_DETAIL: putDetail(cc); addValuesToBatch(nabContactId); // not a new contact break; case ContactChange.TYPE_UPDATE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { putDetail(cc); addUpdateValuesToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update to detail for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; case ContactChange.TYPE_DELETE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { addDeleteDetailToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring detail deletion for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; default: break; } } updateOrganization(ccList, nabContactId); // Execute the batch and Generate ID changes from it return executeUpdateContactBatch(ccList); } /** * @see NativeContactsApi#removeContact(long) */ @Override public void removeContact(long nabContactId) { mCr.delete(addCallerIsSyncAdapterParameter(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId)), null, null); } /** * @see NativeContactsApi#getMasterSyncAutomatically */ @Override public boolean getMasterSyncAutomatically() { // Always true in 1.X return ContentResolver.getMasterSyncAutomatically(); } + /** + * @see NativeContactsApi#setSyncable(boolean) + */ + @Override + public void setSyncable(boolean syncable) { + android.accounts.Account account = getPeopleAccount(); + if(account != null) { + ContentResolver. + setIsSyncable(account, ContactsContract.AUTHORITY, syncable ? 1 : 0); + } + } + /** * @see NativeContactsApi#setSyncAutomatically(boolean) */ @Override public void setSyncAutomatically(boolean syncAutomatically) { - android.accounts.Account[] accounts = - AccountManager.get(mContext).getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); - if(accounts != null && accounts.length > 0) { - ContentResolver.setSyncAutomatically(accounts[0], ContactsContract.AUTHORITY, syncAutomatically); + android.accounts.Account account = getPeopleAccount(); + if(account != null) { + ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, syncAutomatically); if(syncAutomatically) { // Kick start sync - ContentResolver.requestSync(accounts[0], ContactsContract.AUTHORITY, new Bundle()); + ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); } else { // Cancel ongoing just in case - ContentResolver.cancelSync(accounts[0], ContactsContract.AUTHORITY); + ContentResolver.cancelSync(account, ContactsContract.AUTHORITY); } } } /** * @see NativeContactsApi#isKeySupported(int) */ @Override public boolean isKeySupported(int key) { // Only supported if in the SparseArray return sFromKeyToNabContentTypeArray.indexOfKey(key) >= 0; } /** * Inner (private) method for getting contact ids. Allows a cleaner * separation the public API method. * * @param selection The where clause for the operation * @return An array containing the Contact IDs that have been found */ private long[] getContactIds(final String selection) { // Store ids in a temporary array because of possible null values long[] tempIds = null; int idCount = 0; final Cursor cursor = mCr.query(RawContacts.CONTENT_URI, CONTACTID_PROJECTION, selection, null, null); if (cursor == null) { return null; } try { final int cursorCount = cursor.getCount(); if (cursorCount > 0) { tempIds = new long[cursorCount]; while (cursor.moveToNext()) { final long id = cursor.getLong(CONTACTID_PROJECTION_RAW_ID); final String accountType = cursor.getString(CONTACTID_PROJECTION_ACCOUNT_TYPE); // TODO: Remove hardcoding (if statement) if (TextUtils.isEmpty(accountType) || accountType.equals(NativeContactsApi.PEOPLE_ACCOUNT_TYPE_STRING) || isVendorSpecificAccount(accountType) || isContactInMyContactsGroup(id)) { tempIds[idCount] = id; idCount++; } } } } finally { CursorUtils.closeCursor(cursor); } if (idCount > 0) { // Here we copy the array to strip any eventual nulls at the end of // the tempIds array final long[] ids = new long[idCount]; System.arraycopy(tempIds, 0, ids, 0, idCount); return ids; } return null; } /** * Fetches the IDs corresponding to the "My Contacts" System Group The * reason why we return an array is because there may be multiple * "My Contacts" groups. * * @return Array containing all IDs of the "My Contacts" group or null if * none exist */ private void fetchMyContactsGroupRowIds() { final Cursor cursor = mCr.query(Groups.CONTENT_URI, GROUPID_PROJECTION, MY_CONTACTS_GROUP_WHERE_CLAUSE, null, null); if (cursor == null) { return; } try { final int count = cursor.getCount(); if (count > 0) { mMyContactsGroupRowIds = new long[count]; for (int i = 0; i < count; i++) { cursor.moveToNext(); mMyContactsGroupRowIds[i] = cursor.getLong(0); } } } finally { CursorUtils.closeCursor(cursor); } } /** * Checks if a Contact is in the "My Contacts" System Group * * @param nabContactId ID of the Contact to check * @return true if the Contact is in the Group, false if not */ private boolean isContactInMyContactsGroup(long nabContactId) { boolean belongs = false; if (mMyContactsGroupRowIds != null) { final Uri dataUri = Uri.withAppendedPath(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId), RawContacts.Data.CONTENT_DIRECTORY); // build query containing row ID values final StringBuilder sb = new StringBuilder(); sb.append(MY_CONTACTS_MULTI_GROUP_MEMBERSHIP); final int rowIdCount = mMyContactsGroupRowIds.length; for (int i = 0; i < rowIdCount; i++) { sb.append(mMyContactsGroupRowIds[i]); if (i < rowIdCount - 1) { sb.append(','); } } sb.append(')'); final Cursor cursor = mCr.query(dataUri, null, sb.toString(), null, null); try { belongs = cursor != null && cursor.getCount() > 0; } finally { CursorUtils.closeCursor(cursor); } } return belongs; } /** * Reads a Contact Detail from a Cursor into the supplied Contact Change * List. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to read Detail into * @param nabContactId NAB ID of the Contact */ private void readDetail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String mimetype = CursorUtils.getString(cursor, Data.MIMETYPE); final Integer key = sFromNabContentTypeToKeyMap.get(mimetype); if (key != null) { switch (key.intValue()) { case ContactChange.KEY_VCARD_NAME: readName(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_NICKNAME: readNickname(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_PHONE: readPhone(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_EMAIL: readEmail(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ADDRESS: readAddress(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ORG: // Only one Organization can be read (CAB limitation!) if (!mHaveReadOrganization) { readOrganization(cursor, ccList, nabContactId); } break; case ContactChange.KEY_VCARD_URL: readWebsite(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_DATE: if (!mHaveReadBirthday) { readBirthday(cursor, ccList, nabContactId); } break; default: // The default case is also a valid key final String value = CursorUtils.getString(cursor, Data.DATA1); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Data._ID); final ContactChange cc = new ContactChange(key, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } break; } } } /** * Reads an name detail as a {@link ContactChange} from the provided cursor. * For this type of detail we need to use a VCARD (semicolon separated) * value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readName(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using display name only to check if there is a valid name to read final String displayName = CursorUtils.getString(cursor, StructuredName.DISPLAY_NAME); if (!TextUtils.isEmpty(displayName)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredName._ID); // VCard Helper data type (CAB) final Name name = new Name(); // NAB: Given name -> CAB: First name name.firstname = CursorUtils.getString(cursor, StructuredName.GIVEN_NAME); // NAB: Family name -> CAB: Surname name.surname = CursorUtils.getString(cursor, StructuredName.FAMILY_NAME); // NAB: Prefix -> CAB: Title name.title = CursorUtils.getString(cursor, StructuredName.PREFIX); // NAB: Middle name -> CAB: Middle name name.midname = CursorUtils.getString(cursor, StructuredName.MIDDLE_NAME); // NAB: Suffix -> CAB: Suffixes name.suffixes = CursorUtils.getString(cursor, StructuredName.SUFFIX); // NOTE: Ignoring Phonetics (DATA7, DATA8 and DATA9)! // TODO: Need to get middle name and concatenate into value final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NAME, VCardHelper .makeName(name), ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an nickname detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readNickname(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Nickname.NAME); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Nickname._ID); /* * TODO: Decide what to do with nickname: Can only have one in VF360 * but NAB Allows more than one! */ final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NICKNAME, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an phone detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readPhone(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Phone.NUMBER); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Phone._ID); final int type = CursorUtils.getInt(cursor, Phone.TYPE); int flags = mapFromNabPhoneType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Phone.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // assuming raw value is good enough for us final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_PHONE, value, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an email detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readEmail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Email.DATA); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Email._ID); final int type = CursorUtils.getInt(cursor, Email.TYPE); int flags = mapFromNabEmailType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Email.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // assuming raw value is good enough for us final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_EMAIL, value, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an address detail as a {@link ContactChange} from the provided * cursor. For this type of detail we need to use a VCARD (semicolon * separated) value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readAddress(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using formatted address only to check if there is a valid address to // read final String formattedAddress = CursorUtils.getString(cursor, StructuredPostal.FORMATTED_ADDRESS); if (!TextUtils.isEmpty(formattedAddress)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredPostal._ID); final int type = CursorUtils.getInt(cursor, StructuredPostal.TYPE); int flags = mapFromNabAddressType(type); final boolean isPrimary = CursorUtils.getInt(cursor, StructuredPostal.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // VCard Helper data type (CAB) final PostalAddress address = new PostalAddress(); // NAB: Street -> CAB: AddressLine1 address.addressLine1 = CursorUtils.getString(cursor, StructuredPostal.STREET); // NAB: PO Box -> CAB: postOfficeBox address.postOfficeBox = CursorUtils.getString(cursor, StructuredPostal.POBOX); // NAB: Neighborhood -> CAB: AddressLine2 address.addressLine2 = CursorUtils.getString(cursor, StructuredPostal.NEIGHBORHOOD); // NAB: City -> CAB: City address.city = CursorUtils.getString(cursor, StructuredPostal.CITY); // NAB: Region -> CAB: County address.county = CursorUtils.getString(cursor, StructuredPostal.REGION); // NAB: Post code -> CAB: Post code address.postCode = CursorUtils.getString(cursor, StructuredPostal.POSTCODE); // NAB: Country -> CAB: Country address.country = CursorUtils.getString(cursor, StructuredPostal.COUNTRY); final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_ADDRESS, VCardHelper .makePostalAddress(address), flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an organization detail as a {@link ContactChange} from the provided * cursor. For this type of detail we need to use a VCARD (semicolon * separated) value. In reality two different changes may be read if a title * is also present. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readOrganization(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final int type = CursorUtils.getInt(cursor, Organization.TYPE); int flags = mapFromNabOrganizationType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Organization.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } final long nabDetailId = CursorUtils.getLong(cursor, Organization._ID); if (!mHaveReadOrganization) { // VCard Helper data type (CAB) final Organisation organization = new Organisation(); // Company organization.name = CursorUtils.getString(cursor, Organization.COMPANY); // Department final String department = CursorUtils.getString(cursor, Organization.DEPARTMENT); if (!TextUtils.isEmpty(department)) { organization.unitNames.add(department); } if ((organization.unitNames != null && organization.unitNames.size() > 0) || !TextUtils.isEmpty(organization.name)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_ORG, VCardHelper .makeOrg(organization), flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } // Title final String title = CursorUtils.getString(cursor, Organization.TITLE); if (!TextUtils.isEmpty(title)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_TITLE, title, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } } } /** * Reads an Website detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readWebsite(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String url = CursorUtils.getString(cursor, Website.URL); if (!TextUtils.isEmpty(url)) { final long nabDetailId = CursorUtils.getLong(cursor, Website._ID); final int type = CursorUtils.getInt(cursor, Website.TYPE); int flags = mapFromNabWebsiteType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Website.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_URL, url, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an Birthday detail as a {@link ContactChange} from the provided * cursor. Note that since the Android Type is the Generic "Event", it may * be the case that nothing is read if this is not actually a Birthday * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ public void readBirthday(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final int type = CursorUtils.getInt(cursor, Event.TYPE); if (type == Event.TYPE_BIRTHDAY) { final String date = CursorUtils.getString(cursor, Event.START_DATE); // Ignoring birthdays without year, day and month! // FIXME: Remove this check when/if the backend becomes able to // handle incomplete birthdays if (date != null && date.matches(COMPLETE_DATE_REGEX)) { final long nabDetailId = CursorUtils.getLong(cursor, Event._ID); final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_DATE, date, ContactChange.FLAG_BIRTHDAY); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadBirthday = true; } } } /** * Adds current values to the batch. * * @param nabContactId The existing NAB Contact ID if it is an update or an * invalid id if a new contact */ private void addValuesToBatch(long nabContactId) { // Add to batch if (mValues.size() > 0) { final boolean isNewContact = nabContactId == ContactChange.INVALID_ID; if (!isNewContact) { // Updating a Contact, need to add the ID to the Values mValues.put(Data.RAW_CONTACT_ID, nabContactId); } ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( addCallerIsSyncAdapterParameter(Data.CONTENT_URI)).withYieldAllowed(mYield) .withValues(mValues); if (isNewContact) { // New Contact needs Back Reference builder.withValueBackReference(Data.RAW_CONTACT_ID, 0); } mYield = false; mBatch.add(builder.build()); } } /** * Adds current update values to the batch. * * @param nabDetailId The NAB ID of the detail to update */ private void addUpdateValuesToBatch(long nabDetailId) { if (mValues.size() > 0) { final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, nabDetailId); ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate( addCallerIsSyncAdapterParameter(uri)).withYieldAllowed(mYield).withValues( mValues); mYield = false; mBatch.add(builder.build()); } } @@ -1677,513 +1685,528 @@ public class NativeContactsApi2 extends NativeContactsApi { * inserted, updated or deleted depending on the update data. For example, * if the title is deleted but there is also a company name then the * Organization is just updated. However, if there was no company name then * the detail should be deleted altogether. * * @param ccList {@link ContactChange} list where Organization and Title may * be found * @param nabContactId The NAB ID of the Contact */ private void updateOrganization(ContactChange[] ccList, long nabContactId) { if (mMarkedOrganizationIndex < 0 && mMarkedTitleIndex < 0) { // no organization or title to update - do nothing return; } // First we check if there is an existing Organization detail in NAB final Uri uri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI, nabContactId), RawContacts.Data.CONTENT_DIRECTORY); Cursor cursor = mCr.query(uri, null, ORGANIZATION_DETAIL_WHERE_CLAUSE, null, RawContacts.Data._ID); String company = null; String department = null; String title = null; int flags = ContactChange.FLAG_NONE; try { if (cursor != null && cursor.moveToNext()) { // Found an organization detail company = CursorUtils.getString(cursor, Organization.COMPANY); department = CursorUtils.getString(cursor, Organization.DEPARTMENT); title = CursorUtils.getString(cursor, Organization.TITLE); flags = mapFromNabOrganizationType(CursorUtils.getInt(cursor, Organization.TYPE)); final boolean isPrimary = CursorUtils.getInt(cursor, Organization.IS_PRIMARY) > 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } mExistingOrganizationId = CursorUtils.getLong(cursor, Organization._ID); } } finally { CursorUtils.closeCursor(cursor); cursor = null; // make it a candidate for the GC } if (mMarkedOrganizationIndex >= 0) { // Have an Organization (Company + Department) to update final ContactChange cc = ccList[mMarkedOrganizationIndex]; if (cc.getType() != ContactChange.TYPE_DELETE_DETAIL) { final String value = cc.getValue(); if (value != null) { final Organisation organization = VCardHelper.getOrg(value); company = organization.name; if (organization.unitNames.size() > 0) { department = organization.unitNames.get(0); } } flags = cc.getFlags(); } else { // Delete case company = null; department = null; } } if (mMarkedTitleIndex >= 0) { // Have a Title to update final ContactChange cc = ccList[mMarkedTitleIndex]; title = cc.getValue(); if (cc.getType() != ContactChange.TYPE_UPDATE_DETAIL) { flags = cc.getFlags(); } } if (company != null || department != null || title != null) { /* * If any of the above are present we assume a insert or update is * needed. */ mValues.clear(); mValues.put(Organization.LABEL, (String)null); mValues.put(Organization.COMPANY, company); mValues.put(Organization.DEPARTMENT, department); mValues.put(Organization.TITLE, title); mValues.put(Organization.TYPE, mapToNabOrganizationType(flags)); mValues.put(Organization.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED); mValues.put(Organization.MIMETYPE, Organization.CONTENT_ITEM_TYPE); if (mExistingOrganizationId != ContactChange.INVALID_ID) { // update is needed addUpdateValuesToBatch(mExistingOrganizationId); } else { // insert is needed addValuesToBatch(nabContactId); // not a new contact } } else if (mExistingOrganizationId != ContactChange.INVALID_ID) { /* * Had an Organization but now all values are null, delete is in * order. */ addDeleteDetailToBatch(mExistingOrganizationId); } } /** * Executes a pending Batch Operation related to adding a new Contact. * * @param ccList The original {@link ContactChange} for the new Contact * @return {@link ContactChange} array containing new IDs (may contain some * null elements) */ private ContactChange[] executeNewContactBatch(ContactChange[] ccList) { if (mBatch.size() == 0) { // Nothing to execute return null; } final ContentProviderResult[] results = mBatch.execute(); if (results == null || results.length == 0) { LogUtils.logE("NativeContactsApi2.executeNewContactBatch()" + "Batch execution result is null or empty!"); return null; } // -1 because we skip the Profile detail final int resultsSize = results.length - 1; if (results[0].uri == null) { // Contact was not created LogUtils.logE("NativeContactsApi2.executeNewContactBatch()" + "NAB Contact ID not found for created contact"); return null; } final long nabContactId = ContentUris.parseId(results[0].uri); final ContactChange[] idChangeList = new ContactChange[ccList.length + 1]; // Update NAB Contact ID CC idChangeList[0] = ContactChange.createIdsChange(ccList[0], ContactChange.TYPE_UPDATE_NAB_CONTACT_ID); idChangeList[0].setNabContactId(nabContactId); // Start after contact id in the results index int resultsIndex = 1, ccListIndex = 0; final boolean haveOrganization = mMarkedOrganizationIndex != -1 || mMarkedTitleIndex != -1; while (resultsIndex < resultsSize) { if (ccListIndex == mMarkedOrganizationIndex || ccListIndex == mMarkedTitleIndex) { ccListIndex++; continue; } if (results[resultsIndex].uri == null) { throw new RuntimeException("NativeContactsApi2.executeNewContactBatch()" + "Unexpected null URI for NAB Contact:" + nabContactId); } if (resultsIndex == resultsSize - 1 && haveOrganization) { // for readability we leave Organization/Title for outside the // loop break; } final ContactChange cc = ccList[ccListIndex]; // Check if the key is one that is supported in the 2.X NAB if (sFromKeyToNabContentTypeArray.indexOfKey(cc.getKey()) >= 0) { final long nabDetailId = ContentUris.parseId(results[resultsIndex].uri); final ContactChange idChange = ContactChange.createIdsChange(ccList[ccListIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChange.setNabContactId(nabContactId); idChange.setNabDetailId(nabDetailId); idChangeList[ccListIndex + 1] = idChange; resultsIndex++; } ccListIndex++; } if (haveOrganization) { final long nabDetailId = ContentUris.parseId(results[resultsIndex].uri); if (mMarkedOrganizationIndex > -1) { final ContactChange idChange = ContactChange.createIdsChange( ccList[mMarkedOrganizationIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChange.setNabContactId(nabContactId); idChange.setNabDetailId(nabDetailId); idChangeList[mMarkedOrganizationIndex + 1] = idChange; } if (mMarkedTitleIndex > -1) { final ContactChange idChange = ContactChange.createIdsChange( ccList[mMarkedTitleIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChange.setNabContactId(nabContactId); idChange.setNabDetailId(nabDetailId); idChangeList[mMarkedTitleIndex + 1] = idChange; } } return idChangeList; } /** * Executes a pending Batch Operation related to updating a Contact. * * @param ccList The original {@link ContactChange} for the Contact update * @return {@link ContactChange} array containing new IDs (may contain some * null elements) */ private ContactChange[] executeUpdateContactBatch(ContactChange[] ccList) { if (mBatch.size() == 0) { // Nothing to execute return null; } final ContentProviderResult[] results = mBatch.execute(); final int resultsSize = results.length; if (results == null || resultsSize == 0) { // Assuming this can happen in case of no added details return null; } // Start after contact id in the results index int resultsIndex = 0, ccListIndex = 0; final boolean haveOrganization = mMarkedOrganizationIndex != -1 || mMarkedTitleIndex != -1; final ContactChange[] idChangeList = new ContactChange[ccList.length]; while (resultsIndex < resultsSize) { if (ccListIndex == mMarkedOrganizationIndex || ccListIndex == mMarkedTitleIndex) { ccListIndex++; continue; } if (results[resultsIndex].uri == null) { // Assuming detail was updated or deleted (not added) resultsIndex++; continue; } if (resultsIndex == resultsSize - 1 && haveOrganization) { // for readability we leave Organization/Title for outside the // loop break; } final ContactChange cc = ccList[ccListIndex]; // Check if the key is one that is supported in the 2.X NAB if (sFromKeyToNabContentTypeArray.indexOfKey(cc.getKey()) >= 0 && cc.getType() == ContactChange.TYPE_ADD_DETAIL) { final long nabDetailId = ContentUris.parseId(results[resultsIndex].uri); final ContactChange idChange = ContactChange.createIdsChange(ccList[ccListIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChange.setNabDetailId(nabDetailId); idChangeList[ccListIndex] = idChange; resultsIndex++; } ccListIndex++; } if (haveOrganization) { long nabDetailId = ContactChange.INVALID_ID; if (mExistingOrganizationId != nabDetailId) { nabDetailId = mExistingOrganizationId; } else if (results[resultsIndex].uri != null) { nabDetailId = ContentUris.parseId(results[resultsIndex].uri); } else { throw new RuntimeException("NativeContactsApi2.executeUpdateContactBatch()" + "Unexpected null Organization URI for NAB Contact:" + ccList[0].getNabContactId()); } if (mMarkedOrganizationIndex > -1 && ccList[mMarkedOrganizationIndex].getType() == ContactChange.TYPE_ADD_DETAIL) { final ContactChange idChange = ContactChange.createIdsChange( ccList[mMarkedOrganizationIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChange.setNabDetailId(nabDetailId); idChangeList[mMarkedOrganizationIndex] = idChange; } if (mMarkedTitleIndex > -1 && ccList[mMarkedTitleIndex].getType() == ContactChange.TYPE_ADD_DETAIL) { final ContactChange idChange = ContactChange.createIdsChange( ccList[mMarkedTitleIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChange.setNabDetailId(nabDetailId); idChangeList[mMarkedTitleIndex] = idChange; } } return idChangeList; } /** * Static utility method that adds the Sync Adapter flag to the provided URI * * @param uri URI to add the flag to * @return URI with the flag */ private static Uri addCallerIsSyncAdapterParameter(Uri uri) { return uri.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true") .build(); } /** * Utility method used to create an entry in the ContactsContract.Settings * database table for the 360 People Account. This method only exists to * compensate for HTC devices such as Legend or Desire that don't create the * entry automatically like the Nexus One. * * @param username The username of the 360 People Account. */ private void createSettingsEntryForAccount(String username) { mValues.clear(); mValues.put(Settings.ACCOUNT_NAME, username); mValues.put(Settings.ACCOUNT_TYPE, PEOPLE_ACCOUNT_TYPE_STRING); mValues.put(Settings.UNGROUPED_VISIBLE, true); mValues.put(Settings.SHOULD_SYNC, false); // TODO Unsupported for now mCr.insert(Settings.CONTENT_URI, mValues); } /** * Maps a phone type from the native value to the {@link ContactChange} * flags. * * @param nabType Given native phone number type * @return {@link ContactChange} flags */ private static int mapFromNabPhoneType(int nabType) { switch (nabType) { case Phone.TYPE_HOME: return ContactChange.FLAG_HOME; case Phone.TYPE_MOBILE: return ContactChange.FLAG_CELL; case Phone.TYPE_WORK: return ContactChange.FLAG_WORK; case Phone.TYPE_WORK_MOBILE: return ContactChange.FLAGS_WORK_CELL; case Phone.TYPE_FAX_WORK: return ContactChange.FLAGS_WORK_FAX; case Phone.TYPE_FAX_HOME: return ContactChange.FLAGS_HOME_FAX; case Phone.TYPE_OTHER_FAX: return ContactChange.FLAG_FAX; } return ContactChange.FLAG_NONE; } /** * Maps {@link ContactChange} flags into the native phone type. * * @param flags {@link ContactChange} flags * @return Native phone type */ private static int mapToNabPhoneType(int flags) { if ((flags & ContactChange.FLAGS_WORK_CELL) == ContactChange.FLAGS_WORK_CELL) { return Phone.TYPE_WORK_MOBILE; } if ((flags & ContactChange.FLAGS_HOME_FAX) == ContactChange.FLAGS_HOME_FAX) { return Phone.TYPE_FAX_HOME; } if ((flags & ContactChange.FLAGS_WORK_FAX) == ContactChange.FLAGS_WORK_FAX) { return Phone.TYPE_FAX_WORK; } if ((flags & ContactChange.FLAG_HOME) == ContactChange.FLAG_HOME) { return Phone.TYPE_HOME; } if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return Phone.TYPE_WORK; } if ((flags & ContactChange.FLAG_CELL) == ContactChange.FLAG_CELL) { return Phone.TYPE_MOBILE; } if ((flags & ContactChange.FLAG_FAX) == ContactChange.FLAG_FAX) { return Phone.TYPE_OTHER_FAX; } return Phone.TYPE_OTHER; } /** * Maps a email type from the native value into the {@link ContactChange} * flags * * @param nabType Native email type * @return {@link ContactChange} flags */ private static int mapFromNabEmailType(int nabType) { switch (nabType) { case Email.TYPE_HOME: return ContactChange.FLAG_HOME; case Email.TYPE_MOBILE: return ContactChange.FLAG_CELL; case Email.TYPE_WORK: return ContactChange.FLAG_WORK; } return ContactChange.FLAG_NONE; } /** * Maps {@link ContactChange} flags into the native email type. * * @param flags {@link ContactChange} flags * @return Native email type */ private static int mapToNabEmailType(int flags) { if ((flags & ContactChange.FLAG_HOME) == ContactChange.FLAG_HOME) { return Email.TYPE_HOME; } if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return Email.TYPE_WORK; } return Email.TYPE_OTHER; } /** * Maps a address type from the native value into the {@link ContactChange} * flags * * @param nabType Native email type * @return {@link ContactChange} flags */ private static int mapFromNabAddressType(int nabType) { switch (nabType) { case StructuredPostal.TYPE_HOME: return ContactChange.FLAG_HOME; case StructuredPostal.TYPE_WORK: return ContactChange.FLAG_WORK; } return ContactChange.FLAG_NONE; } /** * Maps {@link ContactChange} flags into the native address type. * * @param flags {@link ContactChange} flags * @return Native address type */ private static int mapToNabAddressType(int flags) { if ((flags & ContactChange.FLAG_HOME) == ContactChange.FLAG_HOME) { return StructuredPostal.TYPE_HOME; } if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return StructuredPostal.TYPE_WORK; } return StructuredPostal.TYPE_OTHER; } /** * Maps a organization type from the native value into the * {@link ContactChange} flags * * @param nabType Given native organization type * @return {@link ContactChange} flags */ private static int mapFromNabOrganizationType(int nabType) { if (nabType == Organization.TYPE_WORK) { return ContactChange.FLAG_WORK; } return ContactChange.FLAG_NONE; } /** * Maps {@link ContactChange} flags into the native organization type. * * @param flags {@link ContactChange} flags * @return Native Organization type */ private static int mapToNabOrganizationType(int flags) { if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return Organization.TYPE_WORK; } return Organization.TYPE_OTHER; } /** * Maps a Website type from the native value into the {@link ContactChange} * flags * * @param nabType Native email type * @return {@link ContactChange} flags */ private static int mapFromNabWebsiteType(int nabType) { switch (nabType) { case Website.TYPE_HOME: return ContactChange.FLAG_HOME; case Website.TYPE_WORK: return ContactChange.FLAG_WORK; } return ContactChange.FLAG_NONE; } /** * Maps {@link ContactChange} flags into the native Website type. * * @param flags {@link ContactChange} flags * @return Native Website type */ private static int mapToNabWebsiteType(int flags) { if ((flags & ContactChange.FLAG_HOME) == ContactChange.FLAG_HOME) { return Website.TYPE_HOME; } if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return Website.TYPE_WORK; } return Website.TYPE_OTHER; } + + /** + * Gets the first People Account found on the device or + * null if none is found + * @return The Android People account found or null + */ + public android.accounts.Account getPeopleAccount() { + android.accounts.Account[] accounts = + AccountManager.get(mContext).getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); + if(accounts != null && accounts.length > 0) { + return accounts[0]; + } + + return null; + } } diff --git a/src/com/vodafone360/people/service/SyncAdapter.java b/src/com/vodafone360/people/service/SyncAdapter.java index 430e17b..9bdf5b1 100644 --- a/src/com/vodafone360/people/service/SyncAdapter.java +++ b/src/com/vodafone360/people/service/SyncAdapter.java @@ -1,264 +1,281 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import android.accounts.Account; -import android.accounts.AccountManager; import android.content.AbstractThreadedSyncAdapter; import android.content.BroadcastReceiver; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SyncResult; import android.content.SyncStatusObserver; import android.os.Bundle; import android.os.Handler; import android.provider.ContactsContract; import com.vodafone360.people.MainApplication; import com.vodafone360.people.engine.contactsync.NativeContactsApi; +import com.vodafone360.people.engine.contactsync.NativeContactsApi2; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; import com.vodafone360.people.service.PersistSettings.InternetAvail; /** * SyncAdapter implementation which basically just ties in with * the old Contacts Sync Engine code for the moment and waits for the sync to be finished. * In the future we may want to improve this, particularly if the sync * is actually be done in this thread which would also enable disable sync altogether. */ public class SyncAdapter extends AbstractThreadedSyncAdapter implements IContactSyncObserver { // TODO: RE-ENABLE SYNC VIA SYSTEM // /** // * Direct access to Sync Engine stored for convenience // */ // private final ContactSyncEngine mSyncEngine = EngineManager.getInstance().getContactSyncEngine(); // // /** // * Boolean used to remember if we have requested a sync. // * Useful to ignore events // */ // private boolean mPerformSyncRequested = false; // /** * Delay when checking our Sync Setting when there is a authority auto-sync setting change. * This waiting time is necessary because in case it is our sync adapter authority setting * that changes we cannot query in the callback because the value is not yet changed! */ private static final int SYNC_SETTING_CHECK_DELAY = 500; /** * Same as ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS * The reason we have this is just because the constant is not publicly defined before 2.2. */ private static final int SYNC_OBSERVER_TYPE_SETTINGS = 1; /** * Application object instance */ private final MainApplication mApplication; /** * Broadcast receiver used to listen for changes in the Master Auto Sync setting * intent: com.android.sync.SYNC_CONN_STATUS_CHANGED */ private final BroadcastReceiver mAutoSyncChangeBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { setConnectionSettingForAutoSyncSetting(); } }; /** * Observer for the global sync status setting. * There is no known way to only observe our sync adapter's setting. */ private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() { @Override public void onStatusChanged(int which) { mHandler.postDelayed(mRunnable, SYNC_SETTING_CHECK_DELAY); } }; /** * Handler used to post to a runnable in order to wait * for a short time before checking the sync adapter * authority sync setting after a global change occurs. */ private final Handler mHandler = new Handler(); /** * Cached Account we use to query this Sync Adapter instance's Auto-sync setting. */ private Account mAccount; /** * Runnable used to post to a runnable in order to wait * for a short time before checking the sync adapter * authority sync setting after a global change occurs. * The reason we use this kind of mechanism is because: * a) There is an intent(com.android.sync.SYNC_CONN_STATUS_CHANGED) * we can listen to for the Master Auto-sync but, * b) The authority auto-sync observer pattern using ContentResolver * listens to EVERY sync adapter setting on the device AND * when the callback is received the value is not yet changed so querying for it is useless. */ private final Runnable mRunnable = new Runnable() { @Override public void run() { setConnectionSettingForAutoSyncSetting(); } }; public SyncAdapter(Context context, MainApplication application) { // No automatic initialization (false) super(context, false); mApplication = application; context.registerReceiver(mAutoSyncChangeBroadcastReceiver, new IntentFilter( "com.android.sync.SYNC_CONN_STATUS_CHANGED")); ContentResolver.addStatusChangeListener( SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver); + // Necessary in case of Application udpate + forceSyncSettingsInCaseOfAppUpdate(); + // Register for sync event callbacks // TODO: RE-ENABLE SYNC VIA SYSTEM // mSyncEngine.addEventCallback(this); } /** * {@inheritDoc} */ @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { if(extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false)) { initializeSyncAdapter(account, authority); return; } setConnectionSettingForAutoSyncSetting(); // TODO: RE-ENABLE SYNC VIA SYSTEM // try { // synchronized(this) { // mPerformSyncRequested = true; // if(!mSyncEngine.isSyncing()) { // mSyncEngine.startFullSync(); // } // // while(mSyncEngine.isSyncing()) { // wait(POOLING_WAIT_INTERVAL); // } // mPerformSyncRequested = false; // } // } catch (InterruptedException e) { // e.printStackTrace(); // } } /** * @see IContactSyncObserver#onContactSyncStateChange(Mode, State, State) */ @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { // TODO: RE-ENABLE SYNC VIA SYSTEM // synchronized(this) { // /* // * This check is done so that we can also update the native UI // * when the client devices to sync on it own // */ // if(!mPerformSyncRequested && // mode != Mode.NONE) { // mPerformSyncRequested = true; // Account account = new Account( // LoginPreferences.getUsername(), // NativeContactsApi2.PEOPLE_ACCOUNT_TYPE); // ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); // } // } } /** * @see IContactSyncObserver#onProgressEvent(State, int) */ @Override public void onProgressEvent(State currentState, int percent) { // Nothing to do } /** * @see IContactSyncObserver#onSyncComplete(ServiceStatus) */ @Override public void onSyncComplete(ServiceStatus status) { // Nothing to do } /** * Initializes Sync settings for this Sync Adapter * @param account The account associated with the initialization * @param authority The authority of the content */ private void initializeSyncAdapter(Account account, String authority) { mAccount = account; // caching ContentResolver.setIsSyncable(account, authority, 1); ContentResolver.setSyncAutomatically(account, authority, true); } /** * Checks if this Sync Adapter is allowed to Sync Automatically * Basically just checking if the Master and its own Auto-sync are on. * The Master Auto-sync takes precedence over the authority Auto-sync. * @return true if the settings are enabled, false otherwise */ private boolean canSyncAutomatically() { if(!ContentResolver.getMasterSyncAutomatically()) { return false; } return mAccount != null && ContentResolver.getSyncAutomatically(mAccount, ContactsContract.AUTHORITY); } /** * Sets the application data connection setting depending on the Auto-Sync Setting. * If Auto-sync is enabled then connection is to online ("always connect") * Otherwise connection is set to offline ("manual connect") */ private synchronized void setConnectionSettingForAutoSyncSetting() { if(canSyncAutomatically()) { // Enable data connection mApplication.setInternetAvail(InternetAvail.ALWAYS_CONNECT); } else { // Disable data connection mApplication.setInternetAvail(InternetAvail.MANUAL_CONNECT); } } + + /** + * This method is essentially needed to force the sync settings + * to a consistent state in case of an Application Update. + * This is because old versions of the client do not set + * the sync adapter to syncable for the contacts authority. + */ + private void forceSyncSettingsInCaseOfAppUpdate() { + NativeContactsApi2 nabApi = (NativeContactsApi2) NativeContactsApi.getInstance(); + nabApi.setSyncable(true); + mAccount = nabApi.getPeopleAccount(); + nabApi.setSyncAutomatically( + mApplication.getInternetAvail() == InternetAvail.ALWAYS_CONNECT); + } }
360/360-Engine-for-Android
d04c47a6fa290de2f7e7d9e31574475ff861a739
more changes
diff --git a/src/com/vodafone360/people/ApplicationCache.java b/src/com/vodafone360/people/ApplicationCache.java index f956a51..c7a886a 100644 --- a/src/com/vodafone360/people/ApplicationCache.java +++ b/src/com/vodafone360/people/ApplicationCache.java @@ -1,683 +1,690 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import java.security.InvalidParameterException; import java.util.ArrayList; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import com.vodafone360.people.R; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.engine.contactsync.SyncStatus; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.ui.contacts.MyProfileCache; import com.vodafone360.people.utils.ThirdPartyAccount; import com.vodafone360.people.utils.LoginPreferences; import com.vodafone360.people.utils.LogUtils; /** * Caches information about the current state of the application. Stores most * recent activity and caches other information such as login details, so that * the application is returned to its most recent state when brought back to the * foreground or re-entered. The cached details can be cleared if required (as * part of 'Remove user data' for example). */ public class ApplicationCache { /** Text key for Terms of Service content. **/ private final static String TERMS_OF_SERVICE = "TERMS_OF_SERVICE"; /** Text key for Terms of Service last updated time. **/ private final static String TERMS_OF_SERVICE_TIME = "TERMS_OF_SERVICE_TIME"; /** Text key for Privacy content. **/ private final static String PRIVACY = "PRIVACY"; /** Text key for Privacy last updated time. **/ private final static String PRIVACY_TIME = "PRIVACY_TIME"; /** * Refresh any cached terms of service or privacy content after 10 minutes. */ private final static long REFRESH_TIME = 10 * 60 * 1000; private static final String TRUE = "true"; private static final String FALSE = "false"; /** * Login details are stored in the preferences file so that they can be used * to pre-populate the edit fields if the user is interrupted in the middle * of login/signup */ public static final String PREFS_FILE = "NOW_PLUS"; public static final String CONTACT_DATA = "ContactData"; public static final String CONTACT_SUMMARY = "ContactSummary"; public static final String CONTACT_ID = "CONTACTID"; public static final String CONTACT_NAME = "CONTACTNAME"; public static final String CONTACT_NUMBER = "CONTACTNUMBER"; public static final String CONTACT_NETWORK = "CONTACTNETWORK"; public static final String CONTACT_MODIFIED = "ContactModified"; public static final String STARTUP_LAUNCH_PATH_KEY = "LAUNCHED_FROM"; public static final int RESULT_DELETE = -100; public static final int CONTACT_PROFILE_VIEW = 0; public static final int CONTACT_PROFILE_EDIT = 1; public static final int CONTACT_PROFILE_ADD = 2; public static final int CONTACT_PROFILE_VIEW_ME = 3; public static final String THIRD_PARTY_ACCOUNT_NAME_KEY = "ThirdPartyAccountName"; public static final String THIRD_PARTY_ACCOUNT_NETWORK_KEY = "ThirdPartyNetworkName"; public static final String THIRD_PARTY_ACCOUNT_USERNAME_KEY = "ThirdPartyAccountUsername"; public static final String THIRD_PARTY_ACCOUNT_PASSWORD_KEY = "ThirdPartyAccountPassword"; public static final String THIRD_PARTY_ACCOUNT_CAPABILITIES = "ThirdPartyAccountCapabilities"; public static final String THIRD_PARTY_ACCOUNT_ERROR_CODE = "ThirdPartyAccountErrorCode"; private final static String FACEBOOK_SUBSCRIBED = "FacebookSubscribed"; private final static String HYVES_SUBSCRIBED = "HyvesSubscribed"; public final static String PREFS_NAME = "NowPlus_Prefs"; // Check settings public final static String PREFS_CHECK_FREQUENCY = "checkFrequency"; // Upgrade version - these values are deleted when the latest version is not // new public final static String PREFS_LAST_DIALOG_DATE = "lastDialogDate"; public final static String PREFS_LAST_CHECKED_DATE = "lastCheckedDate"; public final static String PREFS_UPGRADE_LATEST_VERSION = "upgradeLatestVersion"; public final static String PREFS_UPGRADE_URL = "upgradeUrl"; public final static String PREFS_UPGRADE_TEXT = "upgradeText"; public static String sWidgetProviderClassName = null; public static String sIsNewMessage = "isNewMessage"; // Frequency setting descriptions and defaults public final static long[] FREQUENCY_SETTING_LONG = { -1, // Off 7 * 24 * 60 * 60 * 1000, // Weekly 24 * 60 * 60 * 1000, // Daily 6 * 60 * 60 * 1000, // Every 6 hours 1 * 60 * 60 * 1000, // Hourly 10 * 60 * 1000 // Every 10 minutes }; /** In memory cache of the current contacts sync status. **/ private SyncStatus mSyncStatus = null; // Cached login flags private boolean mFirstTimeLogin = true; private boolean mScanThirdPartyAccounts = true; private boolean mAcceptedTermsAndConditions = false; private int mIdentityBeingProcessed = -1; private ArrayList<ThirdPartyAccount> mThirdPartyAccountsCache; private ContactSummary mMeProfileSummary; private Contact mCurrentContact; private ContactSummary mCurrentContactSummary; private ServiceStatus mServiceStatus = ServiceStatus.ERROR_UNKNOWN; private TimelineSummaryItem mCurrentTimelineSummary; private long mCurrentContactFilter; /** Cached whether ThirdPartyAccountsActivity is opened. */ private boolean mIsAddAccountActivityOpened; /** * The My profile checkboxes states cache. */ private static MyProfileCache sMyProfileCache; /*** * GETTER Whether "add Account" activity is opened * * @return True if "add Account" activity is opened */ public boolean addAccountActivityOpened() { return mIsAddAccountActivityOpened; } /*** * SETTER Whether "add Account" activity is opened. * * @param flag if "add Account" activity is opened */ public void setAddAccountActivityOpened(final boolean flag) { mIsAddAccountActivityOpened = flag; } /** * Whether this is a first time login (on this device) for current account. * * @return True if this is the first login for current account. */ public boolean firstTimeLogin() { return mFirstTimeLogin; } /** * Set whether this is a first time login (on this device) for current * account. If we have not logged in on this device (or after 'Remove user * data') we will need to perform the first time 'full' time contact sync. * * @param aState True if this is our 1st time sync. */ public void setFirstTimeLogin(boolean state) { mFirstTimeLogin = state; } /** * Set whether application should re-scan 3rd party accounts. * * @param state true if application should re-scan 3rd party accounts. */ public void setScanThirdPartyAccounts(boolean state) { mScanThirdPartyAccounts = state; } /** * Return whether application should re-scan 3rd party accounts. * * @return true if application should re-scan 3rd party accounts. */ public boolean getScanThirdPartyAccounts() { return mScanThirdPartyAccounts; } /** * Set index of Identity currently being processed. * * @param index Index of Identity currently being processed. */ public void setIdentityBeingProcessed(int index) { mIdentityBeingProcessed = index; } /** * Return index of the Identity currently being processed. * * @return index of the Identity currently being processed. */ public int getIdentityBeingProcessed() { return mIdentityBeingProcessed; } /** * Set whether user has accepted the Terms and Conditions on sign-up. * * @param state true if user has accepted terms and conditions. */ public void setAcceptedTermsAndConditions(boolean state) { mAcceptedTermsAndConditions = state; } /** * Return whether user has accepted the Terms and Conditions on sign-up. * * @return true if user has accepted terms and conditions. */ public boolean getAcceptedTermsAndConditions() { return mAcceptedTermsAndConditions; } /** * Clear all cached data currently stored in People application. */ protected void clearCachedData(Context context) { LoginPreferences.clearPreferencesFile(context); LoginPreferences.clearCachedLoginDetails(); mFirstTimeLogin = true; mScanThirdPartyAccounts = true; mIdentityBeingProcessed = -1; mAcceptedTermsAndConditions = false; mMeProfileSummary = null; mCurrentContact = null; mCurrentContactSummary = null; mServiceStatus = ServiceStatus.ERROR_UNKNOWN; mThirdPartyAccountsCache = null; mSyncStatus = null; mIsAddAccountActivityOpened = false; + + sMyProfileCache = null; } /** * Gets the ME profile object. * * @return The ME profile object. */ public ContactSummary getMeProfile() { return mMeProfileSummary; } /** * Sets the ME profile object. * * @param summary ContyactSummary for Me profile. */ public void setMeProfile(ContactSummary summary) { mMeProfileSummary = summary; } /** * Gets the contact currently being viewed in the UI. * * @return The currently view contact. */ public Contact getCurrentContact() { return mCurrentContact; } /** * Sets the contact currently being viewed in the UI. * * @param contact The currently viewed contact. */ public void setCurrentContact(Contact contact) { mCurrentContact = contact; } /** * Gets the summary information of the contact currently being viewed in the * UI. * * @return Contact summary information. */ public ContactSummary getCurrentContactSummary() { return mCurrentContactSummary; } /** * Sets the summary information of the contact currently being viewed in the * UI. * * @param contactSummary Contact summary information. */ public void setCurrentContactSummary(ContactSummary contactSummary) { mCurrentContactSummary = contactSummary; } /** * Return status of request issued to People service. * * @return status of request issued to People service. */ public ServiceStatus getServiceStatus() { return mServiceStatus; } /** * Set status of request issued to People service. * * @param status of request issued to People service. */ public void setServiceStatus(ServiceStatus status) { mServiceStatus = status; } /** * Cache list of 3rd party accounts (Identities) associated with current * login. * * @param list List of ThirdPartyAccount items retrieved from current login. */ public void storeThirdPartyAccounts(Context context, ArrayList<ThirdPartyAccount> list) { setValue(context, FACEBOOK_SUBSCRIBED, isFacebookInThirdPartyAccountList(list) + ""); setValue(context, HYVES_SUBSCRIBED, isHyvesInThirdPartyAccountList(list) + ""); mThirdPartyAccountsCache = list; } /** * Return cached list of 3rd party accounts (Identities) associated with * current login. * * @return List of ThirdPartyAccount items retrieved from current login. */ public ArrayList<ThirdPartyAccount> getThirdPartyAccounts() { return mThirdPartyAccountsCache; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Facebook account. */ private static boolean isFacebookInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("facebook")) { if (thirdPartyAccount.isChecked()) { LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook is checked"); return true; } else { LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook is unchecked"); return false; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given ThirdPartyAccount contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Hyves account. */ private static boolean isHyvesInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("hyves")) { if (thirdPartyAccount.isChecked()) { LogUtils .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is checked"); return true; } else { LogUtils .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is unchecked"); return false; } } } } LogUtils.logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves not found in list"); return false; } /** * Get list of IDs of Home-screen widgets. * * @param context Current context. * @return list of IDs of Home-screen widgets. */ public int[] getWidgetIdList(Context context) { if(sWidgetProviderClassName != null) { return AppWidgetManager.getInstance(context).getAppWidgetIds( new ComponentName(context, sWidgetProviderClassName)); } return null; } /*** * Set a value in the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param value Preference value. */ private static void setValue(Context context, String key, String value) { SharedPreferences.Editor editor = context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(key, value); if (!editor.commit()) { throw new NullPointerException("MainApplication.setValue() Failed to set key[" + key + "] with value[" + value + "]"); } LogUtils.logV("ApplicationCache.setValue() key [" + key + "] value [" + value + "] saved to properties file"); } /*** * Gets the current sync state, or NULL if the state has not been set in * this JVM instance. * * @return SyncStatus or NULL. */ public SyncStatus getSyncStatus() { return mSyncStatus; } /*** * Sets the current sync status. * * @param syncStatus New sync status. */ public void setSyncStatus(SyncStatus syncStatus) { mSyncStatus = syncStatus; } /*** * Get a value from the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param defaultValue Preference value. * @return */ private static String getValue(Context context, String key, String defaultValue) { return context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).getString(key, defaultValue); } /*** * Return the resource ID for the SNS Subscribed warning (e.g. * facebook/hyves/etc posting), or -1 if no warning is necessary. * * @param context Android context. * @return Resource ID for textView or -1 is warning is not required. * @throws InvalidParameterException when context is NULL. */ public static int getSnsSubscribedWarningId(Context context) { if (context == null) { throw new InvalidParameterException("ApplicationCache.getSnsSubscribedWarningId() " + "context cannot be NULL"); } boolean facebook = getValue(context, FACEBOOK_SUBSCRIBED, "").equals("true"); boolean hyves = getValue(context, HYVES_SUBSCRIBED, "").equals("true"); if (facebook && hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves_and_facebook; } else if (facebook) { return R.string.ContactStatusListActivity_update_status_on_facebook; } else if (hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves; } else { return -1; } } public static boolean isBooleanValue(Context context, String key) { return TRUE.equals(getValue(context, key, FALSE)); } public static void setBooleanValue(Context context, String key, boolean value) { setValue(context, key, value ? TRUE : FALSE); } /** * Gets the summary information of the Timeline currently being viewed in the * UI. * * @return Timeline summary information. */ public TimelineSummaryItem getCurrentTimelineSummary() { return mCurrentTimelineSummary; } /** * Sets the summary information of the Timeline Item currently being viewed in the * UI. * * @param timelineSummary Timeline summary information. */ public void setCurrentTimelineSummary(TimelineSummaryItem timelineSummary) { mCurrentTimelineSummary = timelineSummary; } /*** * Set the Terms of Service content into the cache. * * @param value Terms of Service content. * @param context Android context. */ public static void setTermsOfService(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(TERMS_OF_SERVICE, value); editor.putLong(TERMS_OF_SERVICE_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setTermsOfService() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Set the Privacy content into the cache. * * @param value Privacy content. * @param context Android context. */ public static void setPrivacyStatemet(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(PRIVACY, value); editor.putLong(PRIVACY_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setPrivacyStatemet() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Get the Terms of Service content from the cache. Will return NULL if * there is no content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Terms of Service content */ public static String getTermsOfService(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(TERMS_OF_SERVICE_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME) { return null; } else { return sharedPreferences.getString(TERMS_OF_SERVICE, null); } } /*** * Get the Privacy content from the cache. Will return NULL if there is no * content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Privacy content */ public static String getPrivacyStatement(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(PRIVACY_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME) { return null; } else { return sharedPreferences.getString(PRIVACY, null); } } private static ServiceStatus sStatus = ServiceStatus.SUCCESS; public static void setTermsStatus(final ServiceStatus status) { sStatus = status; } public static ServiceStatus getTermsStatus() { return sStatus; } /** * @param currentContactFilter the mCurrentContactFilter to set */ public final void setCurrentContactFilter(final long currentContactFilter) { mCurrentContactFilter = currentContactFilter; } /** * @return the mCurrentContactFilter */ public final long getCurrentContactFilter() { return mCurrentContactFilter; } + /** + * Returns the cached checkboxes states on "My profile" screen. + * @return MyProfileCache object. + */ public static MyProfileCache getMyProfileUiCache() { - if (sMyProfileCache == null) { - sMyProfileCache = new MyProfileCache(); - } return sMyProfileCache; } - - public static void setMyProfileUiCache(MyProfileCache cache) { + + /** + * This method sets the cache of checkboxes. + * @param cache MyProfileCache. + */ + public static void setMyProfileCache(MyProfileCache cache) { sMyProfileCache = cache; } } diff --git a/src/com/vodafone360/people/Settings.java b/src/com/vodafone360/people/Settings.java index c33a9ce..ecd66d0 100644 --- a/src/com/vodafone360/people/Settings.java +++ b/src/com/vodafone360/people/Settings.java @@ -1,296 +1,296 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; /** * All application settings. */ public final class Settings { /* * LogCat. */ /** LogCat TAG prefix. **/ public static final String LOG_TAG = "People_"; /* * Transport. */ /** Milliseconds until HTTP connection will time out. */ public static final int HTTP_CONNECTION_TIMEOUT = 30000; /** Maximum number of HTTP connection attempts. */ public static final int HTTP_MAX_RETRY_COUNT = 3; /** HTTP header content type. */ public static final String HTTP_HEADER_CONTENT_TYPE = "application/binary"; /** Number of empty RPG poll responses before stopping RPG poll. */ public static final int BLANK_RPG_HEADER_COUNT = 4; /** TCP Heartbeat interval (10 seconds). */ public static final long TCP_VF_HEARTBEAT_INTERVAL = 10 * 60 * 1000; /** TCP retry interval if we have lost the connection (30 seconds). */ public static final long TCP_RETRY_BROKEN_CONNECTION_INTERVAL = 30 * 60 * 1000; /** TCP socket read time out for the read-operation. */ public static final int TCP_SOCKET_READ_TIMEOUT = 10 * 60 * 1000; /* * Notifications. */ /** LED colour. */ public static final int NOTIFICATION_LED_COLOR = 0xff00ff00; // Green /** LED on time. */ public static final int NOTIFICATION_LED_OFF_TIME = 300; /** LED on time. */ public static final int NOTIFICATION_LED_ON_TIME = 1000; /* * Upgrade Engine */ /** * See UpdateSettingsActivity.FREQUENCY_SETTING_LONG array for meaning (i.e. * Every 6 hours) */ public static final int PREFS_CHECK_FREQUENCY_DEFAULT = 3; /** Show the upgrade dialog box every 10 minutes. */ public static final int DIALOG_CHECK_FREQUENCY_MILLIS = 10 * 60 * 1000; /** * Component trace flags (always checked in as false, not part of build * script). */ /** Trace output for engine components. **/ public static final boolean ENABLED_ENGINE_TRACE = false; /** Trace output for database components. **/ public static final boolean ENABLED_DATABASE_TRACE = false; /** Trace output for transport (i.e. network IO) components. **/ - public static final boolean ENABLED_TRANSPORT_TRACE = true; + public static final boolean ENABLED_TRANSPORT_TRACE = false; /** Trace output for contact synchronisation components. **/ public static final boolean ENABLED_CONTACTS_SYNC_TRACE = false; /** Log engine runtime information to file for profiling. **/ public static final boolean ENABLED_PROFILE_ENGINES = false; /** * This is a list of strings containing the names of engines to be * deactivated in the build. A de-activated engine is constructed but will * never be run (nor will onCreate or onDestroy be called). Any UI requests * will be automatically completed by the framework with a * ServiceStatus.ERROR_NOT_IMPLEMENTED error. */ public static final String DEACTIVATE_ENGINE_LIST_KEY = "deactivated-engines-list"; /* * Hard coded settings */ /** Enable dialler cheat code. **/ public static final boolean DIALER_CHEATCODES_ENABLED = true; /** Enable SMS account activation. **/ public static final boolean ENABLE_ACTIVATION = false; /** * Enable SIM inserted check. Always set to TRUE. Makes the application * unusable if there is no valid SIM card inserted into the device. */ public static final boolean ENABLE_SIM_CHECK = true; /** Enable fetching native contacts. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS = true; /** Enable fetching native contacts on change. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS_ON_CHANGE = true; /** Enable ME profile synchronisation. **/ public static final boolean ENABLE_ME_PROFILE_SYNC = true; /** Enable server contact synchronisation. **/ public static final boolean ENABLE_SERVER_CONTACT_SYNC = true; /** Enable server thumbnail synchronisation. **/ public static final boolean ENABLE_THUMBNAIL_SYNC = true; /** Enable update native contacts synchronisation. **/ public static final boolean ENABLE_UPDATE_NATIVE_CONTACTS = true; /** Enable hiding of connected friends group. **/ public static final boolean HIDE_CONNECTED_FRIENDS_GROUP = true; /** Disable the native sync after the first time import for Android 1.X devices only **/ public static final boolean DISABLE_NATIVE_SYNC_AFTER_IMPORT_ON_ANDROID_1X = true; /* * Keys for properties that can be changed at build time. */ /** Key for application ID setting. **/ public static final String APP_KEY_ID = "app-key-id"; /** Key for application secret key setting. **/ public static final String APP_SECRET_KEY = "app-secret-key"; /** Key for enable logging setting. **/ protected static final String ENABLE_LOGCAT_KEY = "enable-logcat"; /** Key for enable RPG setting. **/ public static final String ENABLE_RPG_KEY = "use-rpg"; /** Key for enable SNS resource icon setting. **/ public static final String ENABLE_SNS_RESOURCE_ICON_KEY = "enable-sns-resource-icon"; /** Key for RPG server URL setting. **/ public static final String RPG_SERVER_KEY = "rpg-url"; /** Key for Hessian URL setting. **/ public static final String SERVER_URL_HESSIAN_KEY = "hessian-url"; /* * Keys without defaults. */ /** Key for TCP server URL setting. **/ public static final String TCP_RPG_URL_KEY = "rpg-tcp-url"; /** Key for TCP port setting. **/ public static final String TCP_RPG_PORT_KEY = "rpg-tcp-port"; /** Key for upgrade check URL setting. **/ public static final String UPGRADE_CHECK_URL_KEY = "upgrade-url"; /* * Default for properties that can be changed at build time. */ /** Default for logging enabled setting. **/ protected static final String DEFAULT_ENABLE_LOGCAT = "true"; /** Default for RPG enabled setting. **/ protected static final String DEFAULT_ENABLE_RPG = "true"; /** Default for SNS resource icon setting. **/ protected static final String DEFAULT_ENABLE_SNS_RESOURCE_ICON = "true"; /** Default for RPG server URL setting. **/ protected static final String DEFAULT_RPG_SERVER = "http://rpg.vodafone360.com/rpg/mcomet/"; /** Default for Hessian URL setting. **/ protected static final String DEFAULT_SERVER_URL_HESSIAN = "http://api.vodafone360.com/services/hessian/"; /* * Request timeouts for all engines and requests, except for fire and * forget calls to RPG: SET_AVAILABILITY and SEND_CHAT_MSG. */ /** Do not handle timeouts for this API. **/ private static final long DONT_HANDLE_TIMEOUTS = -1; /** Generic timeout for requests. **/ private static final long ALL_ENGINES_REQUESTS_TIMEOUT = 60000; /** Timeout for all presence API requests. **/ private static final long PRESENCE_ENGINE_REQUESTS_TIMEOUT = 120000; /** Number of milliseconds in a week. **/ public static final long HISTORY_IS_WEEK_LONG = 7 * 24 * 60 * 60 * 1000; /** Timeout for request waiting in queue. **/ public static final long REMOVE_REQUEST_FROM_QUEUE_MILLIS = 15 * 60 * 1000; /* * The timeouts in milliseconds for the different APIs. */ /** Timeout for activities API. **/ public static final long API_REQUESTS_TIMEOUT_ACTIVITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for authentication API. **/ public static final long API_REQUESTS_TIMEOUT_AUTH = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat create conversation API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_CREATE_CONV = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat send message API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_SEND_MESSAGE = DONT_HANDLE_TIMEOUTS; /** Timeout for contacts API. **/ public static final long API_REQUESTS_TIMEOUT_CONTACTS = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for group privacy API. **/ public static final long API_REQUESTS_TIMEOUT_GROUP_PRIVACY = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for identities API. **/ public static final long API_REQUESTS_TIMEOUT_IDENTITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for presence list API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_LIST = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Timeout for presence set availability API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Enable Facebook chat. **/ public static boolean sEnableFacebookChat = true; /** * Danger! Only set to true if you know what you are doing! This logs each * response no matter if gzipped or not to the SD card under the given * request ID. */ public static boolean sEnableSuperExpensiveResponseFileLogging = false; /** * Private constructor to prevent instantiation. */ private Settings() { } } \ No newline at end of file diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 9a915ba..7d1bb0b 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -26,814 +26,808 @@ package com.vodafone360.people.engine.presence; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.ChatMessage; import com.vodafone360.people.datatypes.Conversation; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.PresenceList; import com.vodafone360.people.datatypes.PushAvailabilityEvent; import com.vodafone360.people.datatypes.PushChatMessageEvent; import com.vodafone360.people.datatypes.PushClosedConversationEvent; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.datatypes.SystemNotification.Tags; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Chat; import com.vodafone360.people.service.io.api.Presence; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.HardcodedUtils; import com.vodafone360.people.utils.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, ITcpConnectionListener { /** Check every 24 hours **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private final List<TimelineSummaryItem> mFailedMessagesList; // (to, network) /** The list of Users still to be processed. **/ private List<User> mUsers = null; /** * This state indicates there are no more pending presence payload * information to be processed. **/ private static final int IDLE = 0; /** * This state indicates there are some pending presence payload information * to be processed. **/ private static final int UPDATE_PROCESSING_GOING_ON = 1; /** Timeout between each presence update processing. **/ private static final long UPDATE_PRESENCE_TIMEOUT_MILLS = 0; /** The page size i.e the number of presence updates processed at a time. **/ private static final int UPDATE_PRESENCE_PAGE_SIZE = 10; /** The number of pages after which the HandlerAgent is notified. **/ private static final int NOTIFY_AGENT_PAGE_INTERVAL = 5; /** The state of the presence Engine. **/ private int mState = IDLE; /** * Number of pages of presence Updates done. This is used to control when a * notification is sent to the UI. **/ private int mIterations = 0; /** * True if the engine runs for the 1st time. */ private boolean firstRun = true; /** * * @param eventCallback * @param databaseHelper */ public PresenceEngine(IEngineEventCallback eventCallback, DatabaseHelper databaseHelper) { super(eventCallback); mEngineId = EngineId.PRESENCE_ENGINE; mDbHelper = databaseHelper; mSendMessagesHash = new Hashtable<String, ChatMessage>(); mFailedMessagesList = new ArrayList<TimelineSummaryItem>(); } @Override public void onCreate() { } @Override public void onDestroy() { if (mDbHelper != null && SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper) != null) { PresenceDbUtils.resetPresenceStatesAcceptForMe(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), mDbHelper); } EngineManager.getInstance().getLoginEngine().removeListener(this); } /** * Checks if the SyncMe and ContactSync Engines have both completed first time sync. * * @return true if both engines have completed first time sync */ private boolean isFirstTimeSyncComplete() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!isFirstTimeSyncComplete()) { LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"); return -1; } /** * need isUiRequestOutstanding() because currently the worker thread is * running and finishing before PresenceEngine.setNextRuntime is called */ if (isCommsResponseOutstanding() || isUiRequestOutstanding()) { LogUtils.logV("PresenceEngine getNextRunTime() comms response outstanding"); return 0; } if (firstRun) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); firstRun = false; } return getCurrentTimeout(); } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + getCurrentTimeout() + "]"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logV("PresenceEngine.run() handled processCommsInQueue()"); return; } if (processTimeout()) { LogUtils.logV("PresenceEngine.run() handled processTimeout()"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logV("PresenceEngine.run(): AgentState.DISCONNECTED"); setPresenceOffline(); } /** * and the getNextRunTime must check the uiRequestReady() function and * return 0 if it is true */ if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { return isUiRequestOutstanding(); } private User getMyAvailabilityStatusFromDatabase() { return PresenceDbUtils.getMeProfilePresenceStatus(mDbHelper); } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setTimeout(CHECK_FREQUENCY); } } else { firstRun = true; mFailedMessagesList.clear(); mSendMessagesHash.clear(); setPresenceOffline(); } } /*** * Set the Global presence status to offline. */ private synchronized void setPresenceOffline() { PresenceDbUtils.setPresenceOfflineInDatabase(mDbHelper); // We clear the mUsers of any pending presence updates because this // Offline presence update request should take the highest priority. mUsers = null; mState = IDLE; mEventCallback.getUiAgent().updatePresence(UiAgent.ALL_USERS); } @Override protected void onRequestComplete() { LogUtils.logI("PresenceEngine.onRequestComplete()"); } @Override protected void onTimeoutEvent() { LogUtils.logI("PresenceEngine.onTimeoutEvent()"); switch (mState) { case UPDATE_PROCESSING_GOING_ON: updatePresenceDatabaseNextPage(); break; case IDLE: default: if (mLoggedIn) { if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setTimeout(CHECK_FREQUENCY); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); setTimeout(CHECK_FREQUENCY / 20); } } } } @Override protected void processCommsResponse(DecodedResponse resp) { handleServerResponse(resp.mDataTypes); } private void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg) { UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribedWithChat()) { uiAgent.sendUnsolicitedUiEvent(errorEvent, null); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users List of users that require updating. */ private synchronized void updatePresenceDatabase(List<User> users) { if (users == null || users.size() == 0) { LogUtils.logW("PresenceEngine.updatePresenceDatabase() users is NULL or zero size"); } else { if (mUsers == null) { mUsers = users; } else { // Doing an add one by one is not an efficient way but then // there is an issue in the addAll API. It crashes sometimes. // And the java code for the AddAll API seems to be erroneous. // More investigation is needed on this. for (User user : users) { mUsers.add(user); } } } mState = UPDATE_PROCESSING_GOING_ON; updatePresenceDatabaseNextPage(); } /** * This API makes the presence updates in pages of 10 with a timeout * after each page. The HandlerAgent is notified after every 10 pages. */ private synchronized void updatePresenceDatabaseNextPage(){ UiAgent uiAgent = mEventCallback.getUiAgent(); if(mUsers == null){ mState = IDLE; return; } int listSize = mUsers.size(); int start = 0; int end = UPDATE_PRESENCE_PAGE_SIZE; if(listSize == 0){ mState = IDLE; mUsers = null; return; } else if(listSize < end) { end = listSize; } List<User> userSubset = mUsers.subList(start, end); if ((userSubset != null)) { long idListeningTo = UiAgent.ALL_USERS; if (uiAgent != null) { idListeningTo = uiAgent.getLocalContactId(); } boolean updateUI = PresenceDbUtils.updateDatabase(userSubset, idListeningTo, mDbHelper); userSubset.clear(); // Send the update notification to UI for every UPDATE_PRESENCE_PAGE_SIZE*NOTIFY_AGENT_PAGE_INTERVAL updates. if (updateUI) { if (mUsers.size() == 0 || NOTIFY_AGENT_PAGE_INTERVAL == mIterations) { if (uiAgent != null) { uiAgent.updatePresence(idListeningTo); } mIterations = 0; } else { mIterations++; } } this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: - LogUtils.logE(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SET_MY_AVAILABILITY:"+ data); Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); LogUtils.logW("PresenceEngine processUiRequest() SEND_CHAT_MESSAGE :" + msg); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } // Get presences // TODO: Fill up hashtable with identities and online statuses Hashtable<String, String> presenceList = HardcodedUtils.createMyAvailabilityHashtable(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** - * Changes the user's availability and therefore the state of the engine. - * Also displays the login notification if necessary. + * Changes the user's availability. * - * @param status Availability to set for all identities we have. + * @param status - Hashtable<String, String> of pairs <communityName, statusName>. */ - public void setMyAvailability(Hashtable<String, String> presenceList) { - if (presenceList == null) { + public void setMyAvailability(Hashtable<String, String> presenceHash) { + if (presenceHash == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } - LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+ presenceList.toString()); + LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+ presenceHash.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } - // Get presences - // TODO: Fill up hashtable with identities and online statuses - User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), - presenceList); + presenceHash); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now - addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); + addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } /** - * Changes the user's availability and therefore the state of the engine. - * Also displays the login notification if necessary. + * Changes the user's availability. * - * @param presence Network-presence to set + * @param network - SocialNetwork to set presence on. + * @param status - OnlineStatus presence status to set. */ public void setMyAvailability(SocialNetwork network, OnlineStatus status) { LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+network + "=" + status); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); presenceList.add(new NetworkPresence(userId, network.ordinal(), status.ordinal())); User me = new User(userId, null); me.setPayload(presenceList); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now - Hashtable<String, String> presence = new Hashtable<String, String>(); - presence.put(network.toString(), status.toString()); - addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presence); + Hashtable<String, String> presenceHash = new Hashtable<String, String>(); + presenceHash.put(network.toString(), status.toString()); + + addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceHash); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { - LogUtils.logW("PresenceEngine.sendMessage() to:" + toLocalContactId + ", body:" + body - + ", at:" + networkId); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } @Override public void onConnectionStateChanged(int state) { if (mLoggedIn && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * This method gets the availability information for Me Profile from the Presence * table and updates the same to the server. */ public final void setMyAvailability() { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if(identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); for(Identity identity : identities) { presences.put(identity.mNetwork, statusString); } return presences; } @Override public void onReset() { // reset the engine as if it was just created super.onReset(); firstRun = true; mLoggedIn = false; mIterations = 0; mState = IDLE; mUsers = null; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } diff --git a/src/com/vodafone360/people/engine/presence/User.java b/src/com/vodafone360/people/engine/presence/User.java index 5ad72f9..b81cfba 100644 --- a/src/com/vodafone360/people/engine/presence/User.java +++ b/src/com/vodafone360/people/engine/presence/User.java @@ -1,277 +1,275 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; -import com.vodafone360.people.utils.LogUtils; /** * User is a class encapsulating the information about a user's presence state. */ public class User { private static final String COLUMNS = "::"; private long mLocalContactId; // the database id of the contact, which // corresponds to, e.g. "[email protected]" private int mOverallOnline; // the overall presence state displayed in the // common contact list private ArrayList<NetworkPresence> mPayload; // communities presence status // {google:online, pc:online, // mobile:online} /** * Default Constructor. */ public User() { } /** * Constructor. * * @param userId - user id in the contact list, e.g. * "google::[email protected]" or "882339" * @param payload - communities presence status {google:online, pc:online, * mobile:online} */ public User(String userId, Hashtable<String, String> payload) { - LogUtils.logE("user id " + userId + ": "+ payload); if (payload != null) { mOverallOnline = isOverallOnline(payload); mPayload = createPayload(userId, payload); } } /** * This method returns the localContactId for this contact in DB across the * application . * * @return the localContactId for this contact in DB */ public long getLocalContactId() { return mLocalContactId; } public void setLocalContactId(long mLocalContactId) { this.mLocalContactId = mLocalContactId; } /** * Returns communities presence status * * @return communities presence status, e.g. {google:online, pc:online, * mobile:online} */ public ArrayList<NetworkPresence> getPayload() { return mPayload; } public OnlineStatus getStatusForNetwork(SocialNetwork network) { if (network == null) { return null; } OnlineStatus os = OnlineStatus.OFFLINE; if (mPayload != null) { if (network == SocialNetwork.VODAFONE) { int aggregated = 0; // aggregated state for "mobile" and "pc" for (NetworkPresence np : mPayload) { if (np.getNetworkId() == SocialNetwork.MOBILE.ordinal() || (np.getNetworkId() == SocialNetwork.PC.ordinal())) { if (aggregated < np.getOnlineStatusId()) { aggregated += np.getOnlineStatusId(); } } } os = OnlineStatus.getValue(aggregated); } else { for (NetworkPresence np : mPayload) { if (np.getNetworkId() == network.ordinal()) { os = OnlineStatus.getValue(np.getOnlineStatusId()); break; } } } } return os; } /** * Returns communities presence status * * @return communities presence status, e.g. {google:online, pc:online, * mobile:online} */ public void setPayload(ArrayList<NetworkPresence> payload) { mPayload = payload; } /** * Returns the overall user presence status * * @return true if user is online at least at one community, e.g. true if * {google:offline, pc:offline, mobile:online} */ private int isOverallOnline(Hashtable<String, String> payload) { if (payload != null) { if (payload.values().contains(ContactSummary.OnlineStatus.ONLINE.toString())) return ContactSummary.OnlineStatus.ONLINE.ordinal(); if (payload.values().contains(ContactSummary.OnlineStatus.INVISIBLE.toString())) return ContactSummary.OnlineStatus.INVISIBLE.ordinal(); if (payload.values().contains(ContactSummary.OnlineStatus.IDLE.toString())) return ContactSummary.OnlineStatus.IDLE.ordinal(); } return ContactSummary.OnlineStatus.OFFLINE.ordinal(); } /** * Returns the overall user presence status: in fact the one from the below * status states first encountered for all known user accounts next: * INVISIBLE, ONLINE, IDLE, OFFLINE * * @return presence state */ public int isOnline() { return mOverallOnline; } /** * @param payload * @return */ private ArrayList<NetworkPresence> createPayload(String userId, Hashtable<String, String> payload) { ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(payload.size()); String parsedUserId = parseUserName(userId); String key = null; SocialNetwork network = null; String value = null; OnlineStatus status = null; for (Enumeration<String> en = payload.keys(); en.hasMoreElements();) { key = en.nextElement(); network = SocialNetwork.getValue(key); if (network != null) { int keyIdx = network.ordinal(); value = payload.get(key); if (value != null) { status = OnlineStatus.getValue(value); if (status != null) { int valueIdx = status.ordinal(); presenceList.add(new NetworkPresence(parsedUserId, keyIdx, valueIdx)); } } } } return presenceList; } /** * @param user * @return */ private static String parseUserName(String userId) { if (userId != null) { int columnsIndex = userId.indexOf(COLUMNS); if (columnsIndex > -1) { return userId.substring(columnsIndex + COLUMNS.length()); } else { return userId; } } return null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mOverallOnline; result = prime * result + ((mPayload == null) ? 0 : mPayload.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User)obj; if (mOverallOnline != other.mOverallOnline) return false; if (mPayload == null) { if (other.mPayload != null) return false; } else if (!mPayload.equals(other.mPayload)) return false; return true; } @Override public String toString() { final StringBuffer sb = new StringBuffer("User [mLocalContactId="); sb.append(mLocalContactId); sb.append(", mOverallOnline="); sb.append(mOverallOnline); sb.append(", mPayload="); sb.append(mPayload); sb.append("]"); return sb.toString(); } /** * This method sets the overall user presence status, * @parameter the online status id - the ordinal, see @OnlineStatus */ public void setOverallOnline(int overallOnline) { this.mOverallOnline = overallOnline; } /** * This method removes the network presence information with the given presence id from the User. * @param ordinal - the network id, ordinal in @see SocialNetworks */ public void removeNetwork(int ordinal) { Iterator<NetworkPresence> itr = mPayload.iterator(); NetworkPresence presence = null; while (itr.hasNext()) { presence = itr.next(); if (presence.getNetworkId() == ordinal) { itr.remove(); break; } } } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index e7759cd..c3e5a44 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,368 +1,371 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.interfaces; import java.util.ArrayList; import java.util.Hashtable; import android.os.Bundle; import android.os.Handler; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.agent.NetworkAgentState; /*** * Interface to expose service functionality to the UI classes. */ public interface IPeopleService { /*** * Allows the Activity to register a Handler, so that it can receive new * call back events from the Service layer. * * @param Handler to listen for call back events. */ void addEventCallback(Handler uiHandler); /*** * Allows the Activity to unregister a Handler, so it will no longer receive * call back events from the Service layer. Usually called on an Activity's * onDestroy() method. * * @param Handler to listen for call back events. */ void removeEventCallback(Handler uiHandler); /*** * Called by the UI to determine if the Service is currently logged into the * Vodafone 360 back end. Called by the StartActivity and other key classes, * so the work flow can be diverted back to the Landing page if the user has * been signed out for any reason. * * @return TRUE Service is logged into the back end system, FALSE user must * log in before they can use the Application. */ boolean getLoginRequired(); /*** * Sets a preference that disables the showing of further roaming * notifications. * * @param TRUE show further roaming notifications, FALSE stop showing */ void setShowRoamingNotificationAgain(boolean showAgain); /*** * Gets the type of roaming notification to show to the user * * @return ROAMING_DIALOG_GLOBAL_ON Data roaming is on, * ROAMING_DIALOG_GLOBAL_OFF Data roaming is off */ int getRoamingNotificationType(); /*** * Gets the current IS_ROAMING_ALLOWED value for the device, which is set by * the user in the * "Menu > Settings > Wireless Controls > Mobile network settings > Data roaming" * check box. * * @return TRUE when roaming is permitted, FALSE when roaming is not * permitted. */ boolean getRoamingDeviceSetting(); /*** * Sets the current Data connectivity preference (i.e. connect, connect when * not roaming, or never connect), although this value is ignored during * initial sign up. * * @see com.vodafone360.people.service.PersistSettings.InternetAvail * @param InternetAvail New data Settings changes */ void notifyDataSettingChanged(InternetAvail internetAvail); /*** * Fetched the current Terms of Service information from the Vodafone 360 * back end system. The result is sent to the registered Handler some time * later after the download process has finished. */ void fetchTermsOfService(); /*** * Fetched the current Privacy Statement information from the Vodafone 360 * back end system. The result is sent to the registered Handler some time * later after the download process has finished. */ void fetchPrivacyStatement(); /*** * Log into the Vodafone 360 back end system using the given credentials. * * @param LoginDetails object containing user name, password, etc. */ void logon(LoginDetails loginDetails); /*** * Asks the back end server to check the validity of the given user name. * * @param String User name to check. */ void fetchUsernameState(String username); /*** * Signs up a new user to the Vodafone 360 back end using the given * Registration details. * * @param RegistrationDetails Registration details */ void register(RegistrationDetails details); /*** * Begins the process of synchronising contacts with the Vodafone 360 back * end. This is designed to run in the foreground and be shown to the user * during the initial sign up process. */ void startContactSync(); /*** * Begins the process of synchronising contacts with the Vodafone 360 back * end. This is designed to run in the background and is called every time * the ContactListActivity is shown to the user. * * @param delay the delay in milliseconds from now when the sync should * start */ void startBackgroundContactSync(long delay); /** * Pings the service about user activity. */ void pingUserActivity(); /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities(); /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities(); /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities(); /*** * Begins the process of retrieving all Third party Accounts from the * Vodafone 360 back end. The response is sent to any currently registered * Activity handlers. * * @param Bundle filter the kind of identities to return. */ //void fetchAvailableIdentities(Bundle data); /*** * Calls the set identity capability status API * * @param network Social Network Name * @param identityId Social Network Identifier * @param identityCapabilityStatus Social Network capability status Bundle */ void setIdentityStatus(String network, String identityId, boolean identityStatus); /*** * Validate the given Social Network identity * * @param dryRun Set to true to validate credentials without actually * signing the server up. * @param network Social Network Name * @param username Login user name * @param password Login password * @param identityCapabilityStatus Social Network capability status Bundle */ void validateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus); /*** * Push the UpdateEngine to immediately check for an updated version of the * client. */ void checkForUpdates(); /*** * Push the UpdateEngine to check if a new update frequency has been set and * to act accordingly. */ void setNewUpdateFrequency(); /*** * Push the ActivitiesEngine Engine to begin synchronising Activities */ void startStatusesSync(); /*** * Returns the current state of the Network Agent. Used for testing only. */ NetworkAgentState getNetworkAgentState(); /*** * Overrides the current state of the Network Agent. Used for testing only. * * @param state A new overriding state. */ void setNetworkAgentState(NetworkAgentState state); /*** * Request a refresh of the currently known Presence information (used for * testing only) * * @param contactId Provide a contactId to receive detailed presence * information for the given contact only * @param contactId Set this to -1 to receive less detailed presence * information but for every contact */ void getPresenceList(long contactId); /** * Change current global (all identities) availability state. * @param status Availability to set for all identities we have. */ void setAvailability(OnlineStatus status); /** - * Change current global (all identities) availability state. - * @param status Availability to set for all identities we have. + * Changes the user's availability. + * + * @param status - Hashtable<String, String> is the hash of pairs <networkName, statusName>. */ void setAvailability(Hashtable<String, String> status); /** - * Change current availability state for a single network. - * @param presence Network-presence to set + * Changes the user's availability. + * + * @param network - SocialNetwork to set presence on. + * @param status - OnlineStatus presence status to set. */ void setAvailability(SocialNetwork network, OnlineStatus status); /*** * Allows an Activity to indicate to the Service that it is ready and able * to handle incoming unsolicited UI events. This should be called in an * Activities onResume() method, to indicate that the activity is currently * on screen. * * @param handler to accept incoming unsolicited UI events from the Service. * @param contactId Provide a contactId to receive updates for the given * contact only. Set this to -1 to receive updates for every * contact. Set this to NULL not to receive contact updates. * @param chat - TRUE if the Handler expects chat messages. */ void subscribe(Handler handler, Long contactId, boolean chat); /*** * Allows the Activity to indicate that it is no longer in the foreground * and will not handle incoming UI events correctly. This should be called * in an Activities onPause() method, to indicate that the Activity is not * on screen. * * @param handler that should no longer receive incoming unsolicited UI * events from the Service */ void unsubscribe(Handler handler); /** * This method should be used to send a message to a contact * * @param to LocalContactIds of ContactSummary/TimelineSummary items the * message is intended for. Current protocol version only * supports a single recipient. * @param body Message text */ void sendMessage(long toLocalContactId, String body, int socialNetworkId); /** * This method should be called to retrieve status updates in * StatusListActivity, @see ActivitiesEngine. */ void getStatuses(); /** * This method should be called to retrieve older timelines in * TimelineListActivity, @see ActivitiesEngine. */ void getMoreTimelines(); /** * This method should be called to retrieve older statuses in * StatusListActivity, @see ActivitiesEngine. */ void getOlderStatuses(); /** * This method triggers the Me Profile upload */ void uploadMeProfile(); /** * This method triggers the Me Profile status text upload * * @param statusText String - new Me Profile status text */ void uploadMyStatus(String statusText); /** * This method triggers the Me Profile download, is currently called by UI */ void downloadMeProfileFirstTime(); /** * This method should be called to update the Chat Notifications. */ void updateChatNotification(long localContactId); } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java index 895ddbe..9b9a392 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,440 +1,439 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.interfaces; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import android.os.Bundle; import android.os.Handler; import android.os.Message; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.MainApplication; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback; -import com.vodafone360.people.engine.presence.NetworkPresence; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.agent.NetworkAgentState; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.utils.LogUtils; /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback * @see com.vodafone360.people.service.interfaces.IPeopleService */ public class IPeopleServiceImpl implements IPeopleService, IEngineEventCallback { private final List<Handler> mUiEventCallbackList = new ArrayList<Handler>(); private IWorkerThreadControl mWorkerThreadControl; private RemoteService mService; private NetworkAgent mNetworkAgent; private UiAgent mHandlerAgent; private ApplicationCache mApplicationCache; /** * Initialises the object, creating the UiAgent. * * @param workerThreadControl Provides access to worker thread control * functions. * @param service Provides access to remote service functions (mainly used * to retrieve context). */ public IPeopleServiceImpl(IWorkerThreadControl workerThreadControl, RemoteService service) { mWorkerThreadControl = workerThreadControl; mService = service; mHandlerAgent = new UiAgent((MainApplication)service.getApplication(), service); mApplicationCache = ((MainApplication)service.getApplication()).getCache(); } /*** * Sets the ServiceAgent, as this needs to be called after the constructor. * * @param agent Handle to ServiceAgent. */ public void setNetworkAgent(NetworkAgent agent) { mNetworkAgent = agent; } /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#onUiEvent(UiEvent, * int, int, Object) */ @Override public void onUiEvent(ServiceUiRequest event, int arg1, int arg2, Object data) { synchronized (mUiEventCallbackList) { for (Handler handler : mUiEventCallbackList) { Message msg = handler.obtainMessage(event.ordinal(), data); msg.arg1 = arg1; msg.arg2 = arg2; if (!handler.sendMessage(msg)) { LogUtils.logE("IPeopleServiceImpl.onUiEvent() Sending msg FAILED"); } } } } /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#kickWorkerThread() */ @Override public void kickWorkerThread() { mWorkerThreadControl.kickWorkerThread(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#addEventCallback(Handler) */ @Override public void addEventCallback(Handler uiHandler) { synchronized (mUiEventCallbackList) { if (!mUiEventCallbackList.contains(uiHandler)) { mUiEventCallbackList.add(uiHandler); } } } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#removeEventCallback(Handler) */ @Override public void removeEventCallback(Handler uiHandler) { synchronized (mUiEventCallbackList) { mUiEventCallbackList.remove(uiHandler); } } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#checkForUpdates() */ @Override public void checkForUpdates() { EngineManager.getInstance().getUpgradeEngine().checkForUpdates(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMyThirdPartyIdentities() */ public ArrayList<Identity> getMyThirdPartyIdentities() { return EngineManager.getInstance().getIdentityEngine().getMyThirdPartyIdentities(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyIdentities() */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { return EngineManager.getInstance().getIdentityEngine().getAvailableThirdPartyIdentities(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyChattableIdentities() */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { return EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchPrivacyStatement() */ @Override public void fetchPrivacyStatement() { EngineManager.getInstance().getLoginEngine().addUiFetchPrivacyStatementRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchTermsOfService() */ @Override public void fetchTermsOfService() { EngineManager.getInstance().getLoginEngine().addUiFetchTermsOfServiceRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchUsernameState(String) */ @Override public void fetchUsernameState(String userName) { EngineManager.getInstance().getLoginEngine().addUiGetUsernameStateRequest(userName); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getLoginRequired() */ @Override public boolean getLoginRequired() { EngineManager manager = EngineManager.getInstance(); return manager.getLoginEngine().getLoginRequired(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getRoamingNotificationType() */ @Override public int getRoamingNotificationType() { return mService.getNetworkAgent().getRoamingNotificationType(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getRoamingDeviceSetting() */ @Override public boolean getRoamingDeviceSetting() { return mService.getNetworkAgent().getRoamingDeviceSetting(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#notifyDataSettingChanged(InternetAvail) */ @Override public void notifyDataSettingChanged(InternetAvail val) { mService.getNetworkAgent().notifyDataSettingChanged(val); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#logon(LoginDetails) */ @Override public void logon(LoginDetails loginDetails) { EngineManager manager = EngineManager.getInstance(); manager.getLoginEngine().addUiLoginRequest(loginDetails); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#register(RegistrationDetails) */ @Override public void register(RegistrationDetails details) { EngineManager.getInstance().getLoginEngine().addUiRegistrationRequest(details); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setNewUpdateFrequency() */ @Override public void setNewUpdateFrequency() { EngineManager.getInstance().getUpgradeEngine().setNewUpdateFrequency(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setShowRoamingNotificationAgain(boolean) */ @Override public void setShowRoamingNotificationAgain(boolean showAgain) { mService.getNetworkAgent().setShowRoamingNotificationAgain(showAgain); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startContactSync() */ @Override public void startContactSync() { EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); EngineManager.getInstance().getContactSyncEngine().addUiStartFullSync(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startBackgroundContactSync(long) */ @Override public void startBackgroundContactSync(long delay) { EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); EngineManager.getInstance().getContactSyncEngine().addUiStartServerSync(delay); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#pingUserActivity() */ @Override public void pingUserActivity() { EngineManager.getInstance().getContactSyncEngine().pingUserActivity(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#validateIdentityCredentials(boolean, * String, String, String, Bundle) */ @Override public void validateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { EngineManager.getInstance().getIdentityEngine().addUiValidateIdentityCredentials(dryRun, network, username, password, identityCapabilityStatus); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startStatusesSync() */ @Override public void startStatusesSync() { EngineManager.getInstance().getActivitiesEngine().addStatusesSyncRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getNetworkAgentState() */ @Override public NetworkAgentState getNetworkAgentState() { return mNetworkAgent.getNetworkAgentState(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setNetowrkAgentState(NetworkAgentState) */ @Override public void setNetworkAgentState(NetworkAgentState state) { mNetworkAgent.setNetworkAgentState(state); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getPresenceList(long) */ @Override public void getPresenceList(long contactId) { EngineManager.getInstance().getPresenceEngine().getPresenceList(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(OnlineStatus) */ @Override public void setAvailability(OnlineStatus status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** - * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(NetworkPresence) + * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(SocialNetwork, OnlineStatus) */ @Override public void setAvailability(SocialNetwork network, OnlineStatus status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(network, status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(Hashtable<String, String> status) */ @Override public void setAvailability(Hashtable<String, String> status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#subscribe(Handler, * long, boolean) */ @Override public void subscribe(Handler handler, Long contactId, boolean chat) { mHandlerAgent.subscribe(handler, contactId, chat); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#unsubscribe(Handler) */ @Override public void unsubscribe(Handler handler) { mHandlerAgent.unsubscribe(handler); } /** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#getUiAgent() */ @Override public UiAgent getUiAgent() { return mHandlerAgent; } /** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#getApplicationCache() */ @Override public ApplicationCache getApplicationCache() { return mApplicationCache; } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#sendMessage(long, * String, int) */ @Override public void sendMessage(long localContactId, String body, int networkId) { EngineManager.getInstance().getPresenceEngine() .sendMessage(localContactId, body, networkId); } @Override public void setIdentityStatus(String network, String identityId, boolean identityStatus) { EngineManager.getInstance().getIdentityEngine().addUiSetIdentityStatus(network, identityId, identityStatus); } @Override public void getStatuses() { EngineManager.getInstance().getActivitiesEngine().addStatusesSyncRequest(); } @Override public void getMoreTimelines() { EngineManager.getInstance().getActivitiesEngine().addOlderTimelinesRequest(); } @Override public void getOlderStatuses() { EngineManager.getInstance().getActivitiesEngine().addGetOlderStatusesRequest(); } @Override public void uploadMeProfile() { EngineManager.getInstance().getSyncMeEngine().addUpdateMeProfileContactRequest(); } @Override public void uploadMyStatus(String statusText) { EngineManager.getInstance().getSyncMeEngine().addUpdateMyStatusRequest(statusText); } @Override public void downloadMeProfileFirstTime() { EngineManager.getInstance().getSyncMeEngine().addGetMeProfileContactFirstTimeRequest(); } @Override public void updateChatNotification(long localContactId) { mHandlerAgent.updateChat(localContactId, false); } } \ No newline at end of file
360/360-Engine-for-Android
2517d30560f6a9a4479180d4291337d58a30c741
PAND-1952: Skipping unknown contacts.
diff --git a/src/com/vodafone360/people/database/tables/ActivitiesTable.java b/src/com/vodafone360/people/database/tables/ActivitiesTable.java index 943c4bc..42ad971 100644 --- a/src/com/vodafone360/people/database/tables/ActivitiesTable.java +++ b/src/com/vodafone360/people/database/tables/ActivitiesTable.java @@ -99,1053 +99,1061 @@ public abstract class ActivitiesTable { FLAG("flag"), /** Parent Activity. **/ PARENT_ACTIVITY("parentactivity"), /** Has children. **/ HAS_CHILDREN("haschildren"), /** Visibility. **/ VISIBILITY("visibility"), /** More info. **/ MORE_INFO("moreinfo"), /** Contact ID. **/ CONTACT_ID("contactid"), /** User ID. **/ USER_ID("userid"), /** Contact name or the alternative. **/ CONTACT_NAME("contactname"), /** Other contact's localContactId. **/ LOCAL_CONTACT_ID("contactlocalid"), /** @see SocialNetwork. **/ CONTACT_NETWORK("contactnetwork"), /** Contact address. **/ CONTACT_ADDRESS("contactaddress"), /** Contact avatar URL. **/ CONTACT_AVATAR_URL("contactavatarurl"), /** Native item type. **/ NATIVE_ITEM_TYPE("nativeitemtype"), /** Native item ID. **/ NATIVE_ITEM_ID("nativeitemid"), /** Latest contact status. **/ LATEST_CONTACT_STATUS("latestcontactstatus"), /** Native thread ID. **/ NATIVE_THREAD_ID("nativethreadid"), /** For chat messages: if this message is incoming. **/ INCOMING("incoming"); /** Name of the field as it appears in the database. **/ private final String mField; /** * Constructor. * * @param field - The name of the field (see list above) */ private Field(final String field) { mField = field; } /** * @return the name of the field as it appears in the database. */ public String toString() { return mField; } } /** * An enumeration of supported timeline types. */ public static enum TimelineNativeTypes { /** Call log type. **/ CallLog, /** SMS log type. **/ SmsLog, /** MMS log type. **/ MmsLog, /** Chat log type. **/ ChatLog } /** * This class encapsulates a timeline activity item. */ public static class TimelineSummaryItem { /*** * Enum of Timeline types. */ public enum Type { /** Incoming type. **/ INCOMING, /** Outgoing type. **/ OUTGOING, /** Unsent type. **/ UNSENT, /** Unknown type (do not use). **/ UNKNOWN } /*** * Get the Type from a given Integer value. * @param input Integer.ordinal value of the Type * @return Relevant Type or UNKNOWN if the Integer is not known. */ public static Type getType(final int input) { if (input < 0 || input > Type.UNKNOWN.ordinal()) { return Type.UNKNOWN; } else { return Type.values()[input]; } } /** Maps to the local activity ID (primary key). **/ private Long mLocalActivityId; /** Maps to the activity timestamp in the table. **/ public Long mTimestamp; /** Maps to the contact name in the table. **/ public String mContactName; /** Set to true if there is an avatar URL stored in the table. **/ private boolean mHasAvatar; /** Maps to type in the table. **/ public ActivityItem.Type mType; /** Maps to local contact id in the table. **/ public Long mLocalContactId; /** Maps to contact network stored in the table. **/ public String mContactNetwork; /** Maps to title stored in the table. **/ public String mTitle; /** Maps to description stored in the table. **/ public String mDescription; /** * Maps to native item type in the table Can be an ordinal from the * {@link ActivitiesTable#TimelineNativeTypes}. */ public Integer mNativeItemType; /** * Key linking to the call-log or message-log item in the native * database. */ public Integer mNativeItemId; /** Server contact ID. **/ public Long mContactId; /** User ID from the server. **/ public Long mUserId; /** Thread ID from the native database (for messages). **/ public Integer mNativeThreadId; /** Contact address (phone number or email address). **/ public String mContactAddress; /** Messages can be incoming and outgoing. **/ public Type mIncoming; /** * Returns a string describing the timeline summary item. * * @return String describing the timeline summary item. */ @Override public final String toString() { final StringBuilder sb = new StringBuilder("TimeLineSummaryItem [mLocalActivityId["); sb.append(mLocalActivityId); sb.append("], mTimestamp["); sb.append(mTimestamp); sb.append("], mContactName["); sb.append(mContactName); sb.append("], mHasAvatar["); sb.append(mHasAvatar); sb.append("], mType["); sb.append(mType); sb.append("], mLocalContactId["); sb.append(mLocalContactId); sb.append("], mContactNetwork["); sb.append(mContactNetwork); sb.append("], mTitle["); sb.append(mTitle); sb.append("], mDescription["); sb.append(mDescription); sb.append("], mNativeItemType["); sb.append(mNativeItemType); sb.append("], mNativeItemId["); sb.append(mNativeItemId); sb.append("], mContactId["); sb.append(mContactId); sb.append("], mUserId["); sb.append(mUserId); sb.append("], mNativeThreadId["); sb.append(mNativeThreadId); sb.append("], mContactAddress["); sb.append(mContactAddress); sb.append("], mIncoming["); sb.append(mIncoming); sb.append("]]");; return sb.toString(); } @Override public final boolean equals(final Object object) { if (TimelineSummaryItem.class != object.getClass()) { return false; } TimelineSummaryItem item = (TimelineSummaryItem) object; return mLocalActivityId.equals(item.mLocalActivityId) && mTimestamp.equals(item.mTimestamp) && mContactName.equals(item.mContactName) && mHasAvatar == item.mHasAvatar && mType.equals(item.mType) && mLocalContactId.equals(item.mLocalContactId) && mContactNetwork.equals(item.mContactNetwork) && mTitle.equals(item.mTitle) && mDescription.equals(item.mDescription) && mNativeItemType.equals(item.mNativeItemType) && mNativeItemId.equals(item.mNativeItemId) && mContactId.equals(item.mContactId) && mUserId.equals(item.mUserId) && mNativeThreadId.equals(item.mNativeThreadId) && mContactAddress.equals(item.mContactAddress) && mIncoming.equals(item.mIncoming); } }; /** Number of milliseconds in a day. **/ private static final int NUMBER_OF_MS_IN_A_DAY = 24 * 60 * 60 * 1000; /** Number of milliseconds in a second. **/ private static final int NUMBER_OF_MS_IN_A_SECOND = 1000; /*** * Private constructor to prevent instantiation. */ private ActivitiesTable() { // Do nothing. } /** * Create Activities Table. * * @param writeableDb A writable SQLite database. */ public static void create(final SQLiteDatabase writeableDb) { DatabaseHelper.trace(true, "DatabaseHelper.create()"); writeableDb.execSQL("CREATE TABLE " + TABLE_NAME + " (" + Field.LOCAL_ACTIVITY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.ACTIVITY_ID + " LONG, " + Field.TIMESTAMP + " LONG, " + Field.TYPE + " TEXT, " + Field.URI + " TEXT, " + Field.TITLE + " TEXT, " + Field.DESCRIPTION + " TEXT, " + Field.PREVIEW_URL + " TEXT, " + Field.STORE + " TEXT, " + Field.FLAG + " INTEGER, " + Field.PARENT_ACTIVITY + " LONG, " + Field.HAS_CHILDREN + " INTEGER, " + Field.VISIBILITY + " INTEGER, " + Field.MORE_INFO + " TEXT, " + Field.CONTACT_ID + " LONG, " + Field.USER_ID + " LONG, " + Field.CONTACT_NAME + " TEXT, " + Field.LOCAL_CONTACT_ID + " LONG, " + Field.CONTACT_NETWORK + " TEXT, " + Field.CONTACT_ADDRESS + " TEXT, " + Field.CONTACT_AVATAR_URL + " TEXT, " + Field.LATEST_CONTACT_STATUS + " INTEGER, " + Field.NATIVE_ITEM_TYPE + " INTEGER, " + Field.NATIVE_ITEM_ID + " INTEGER, " + Field.NATIVE_THREAD_ID + " INTEGER, " + Field.INCOMING + " INTEGER);"); writeableDb.execSQL("CREATE INDEX " + TABLE_INDEX_NAME + " ON " + TABLE_NAME + " ( " + Field.TIMESTAMP + " )"); } /** * Fetches a comma separated list of table fields which can be used in an * SQL SELECT statement as the query projection. One of the * {@link #getQueryData} methods can used to fetch data from the cursor. * * @return SQL string */ private static String getFullQueryList() { DatabaseHelper.trace(false, "DatabaseHelper.getFullQueryList()"); final StringBuffer fullQuery = StringBufferPool.getStringBuffer(); fullQuery.append(Field.LOCAL_ACTIVITY_ID).append(SqlUtils.COMMA). append(Field.ACTIVITY_ID).append(SqlUtils.COMMA). append(Field.TIMESTAMP).append(SqlUtils.COMMA). append(Field.TYPE).append(SqlUtils.COMMA). append(Field.URI).append(SqlUtils.COMMA). append(Field.TITLE).append(SqlUtils.COMMA). append(Field.DESCRIPTION).append(SqlUtils.COMMA). append(Field.PREVIEW_URL).append(SqlUtils.COMMA). append(Field.STORE).append(SqlUtils.COMMA). append(Field.FLAG).append(SqlUtils.COMMA). append(Field.PARENT_ACTIVITY).append(SqlUtils.COMMA). append(Field.HAS_CHILDREN).append(SqlUtils.COMMA). append(Field.VISIBILITY).append(SqlUtils.COMMA). append(Field.MORE_INFO).append(SqlUtils.COMMA). append(Field.CONTACT_ID).append(SqlUtils.COMMA). append(Field.USER_ID).append(SqlUtils.COMMA). append(Field.CONTACT_NAME).append(SqlUtils.COMMA). append(Field.LOCAL_CONTACT_ID).append(SqlUtils.COMMA). append(Field.CONTACT_NETWORK).append(SqlUtils.COMMA). append(Field.CONTACT_ADDRESS).append(SqlUtils.COMMA). append(Field.CONTACT_AVATAR_URL).append(SqlUtils.COMMA). append(Field.INCOMING); return StringBufferPool.toStringThenRelease(fullQuery); } /** * Fetches activities information from a cursor at the current position. The * {@link #getFullQueryList()} method should be used to make the query. * * @param cursor The cursor returned by the query * @param activityItem An empty activity object that will be filled with the * result * @param activityContact An empty activity contact object that will be * filled */ public static void getQueryData(final Cursor cursor, final ActivityItem activityItem, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityItem. **/ activityItem.localActivityId = SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); activityItem.activityId = SqlUtils.setLong(cursor, Field.ACTIVITY_ID.toString(), null); activityItem.time = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); activityItem.type = SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); activityItem.uri = SqlUtils.setString(cursor, Field.URI.toString()); activityItem.title = SqlUtils.setString(cursor, Field.TITLE.toString()); activityItem.description = SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); activityItem.previewUrl = SqlUtils.setString(cursor, Field.PREVIEW_URL.toString()); activityItem.store = SqlUtils.setString(cursor, Field.STORE.toString()); activityItem.activityFlags = SqlUtils.setInt(cursor, Field.FLAG.toString(), null); activityItem.parentActivity = SqlUtils.setLong(cursor, Field.PARENT_ACTIVITY.toString(), null); activityItem.hasChildren = SqlUtils.setBoolean(cursor, Field.HAS_CHILDREN.toString(), activityItem.hasChildren); activityItem.visibilityFlags = SqlUtils.setInt(cursor, Field.VISIBILITY.toString(), null); // TODO: Field MORE_INFO is not used, consider deleting. /** Populate ActivityContact. **/ getQueryData(cursor, activityContact); } /** * Fetches activities information from a cursor at the current position. The * {@link #getFullQueryList()} method should be used to make the query. * * @param cursor The cursor returned by the query. * @param activityContact An empty activity contact object that will be * filled */ public static void getQueryData(final Cursor cursor, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityContact. **/ activityContact.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); activityContact.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); activityContact.mName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); activityContact.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); activityContact.mNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); activityContact.mAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); activityContact.mAvatarUrl = SqlUtils.setString(cursor, Field.CONTACT_AVATAR_URL.toString()); } /*** * Provides a ContentValues object that can be used to update the table. * * @param item The source activity item * @param contactIdx The index of the contact to use for the update, or null * to exclude contact specific information. * @return ContentValues for use in an SQL update or insert. * @note Items that are NULL will be not modified in the database. */ private static ContentValues fillUpdateData(final ActivityItem item, final Integer contactIdx) { DatabaseHelper.trace(false, "DatabaseHelper.fillUpdateData()"); ContentValues activityItemValues = new ContentValues(); ActivityContact ac = null; if (contactIdx != null) { ac = item.contactList.get(contactIdx); } activityItemValues.put(Field.ACTIVITY_ID.toString(), item.activityId); activityItemValues.put(Field.TIMESTAMP.toString(), item.time); if (item.type != null) { activityItemValues.put(Field.TYPE.toString(), item.type.getTypeCode()); } if (item.uri != null) { activityItemValues.put(Field.URI.toString(), item.uri); } /** TODO: Not sure if we need this. **/ // activityItemValues.put(Field.INCOMING.toString(), false); activityItemValues.put(Field.TITLE.toString(), item.title); activityItemValues.put(Field.DESCRIPTION.toString(), item.description); if (item.previewUrl != null) { activityItemValues.put(Field.PREVIEW_URL.toString(), item.previewUrl); } if (item.store != null) { activityItemValues.put(Field.STORE.toString(), item.store); } if (item.activityFlags != null) { activityItemValues.put(Field.FLAG.toString(), item.activityFlags); } if (item.parentActivity != null) { activityItemValues.put(Field.PARENT_ACTIVITY.toString(), item.parentActivity); } if (item.hasChildren != null) { activityItemValues.put(Field.HAS_CHILDREN.toString(), item.hasChildren); } if (item.visibilityFlags != null) { activityItemValues.put(Field.VISIBILITY.toString(), item.visibilityFlags); } if (ac != null) { activityItemValues.put(Field.CONTACT_ID.toString(), ac.mContactId); activityItemValues.put(Field.USER_ID.toString(), ac.mUserId); activityItemValues.put(Field.CONTACT_NAME.toString(), ac.mName); activityItemValues.put(Field.LOCAL_CONTACT_ID.toString(), ac.mLocalContactId); if (ac.mNetwork != null) { activityItemValues.put(Field.CONTACT_NETWORK.toString(), ac.mNetwork); } if (ac.mAddress != null) { activityItemValues.put(Field.CONTACT_ADDRESS.toString(), ac.mAddress); } if (ac.mAvatarUrl != null) { activityItemValues.put(Field.CONTACT_AVATAR_URL.toString(), ac.mAvatarUrl); } } return activityItemValues; } /** * Fetches a list of status items from the given time stamp. * * @param timeStamp Time stamp in milliseconds * @param readableDb Readable SQLite database * @return A cursor (use one of the {@link #getQueryData} methods to read * the data) */ public static Cursor fetchStatusEventList(final long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchStatusEventList()"); return readableDb.rawQuery("SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + " & " + ActivityItem.STATUS_ITEM + ") AND " + Field.TIMESTAMP + " > " + timeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); } /** * Returns a list of activity IDs already synced, in reverse chronological * order Fetches from the given timestamp. * * @param actIdList An empty list which will be filled with the result * @param timeStamp The time stamp to start the fetch * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus fetchActivitiesIds(final List<Long> actIdList, final Long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchActivitiesIds()"); Cursor cursor = null; try { long queryTimeStamp; if (timeStamp != null) { queryTimeStamp = timeStamp; } else { queryTimeStamp = 0; } cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.TIMESTAMP + " >= " + queryTimeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); while (cursor.moveToNext()) { actIdList.add(cursor.getLong(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchActivitiesIds()" + "Unable to fetch group list", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Adds a list of activities to table. The activities added will be grouped * in the database, based on local contact Id, name or contact address (see * {@link #removeContactGroup(Long, String, Long, int, * TimelineNativeTypes[], SQLiteDatabase)} * for more information on how the grouping works. * * @param actList The list of activities * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus addActivities(final List<ActivityItem> actList, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addActivities()"); SQLiteStatement statement = ContactsTable.fetchLocalFromServerIdStatement(writableDb); - for (ActivityItem activity : actList) { + for (ActivityItem activity : actList) { + try { writableDb.beginTransaction(); if (activity.contactList != null) { int clistSize = activity.contactList.size(); for (int i = 0; i < clistSize; i++) { final ActivityContact activityContact = activity.contactList.get(i); activityContact.mLocalContactId = ContactsTable.fetchLocalFromServerId( activityContact.mContactId, statement); + if (activityContact.mLocalContactId == null) { + // Just skip activities for which we don't have a corresponding contact + // in the database anymore otherwise they will be shown as "Blank name". + // This is the same on the web but we could use the provided name instead. + continue; + } + int latestStatusVal = removeContactGroup( activityContact.mLocalContactId, activityContact.mName, activity.time, activity.activityFlags, null, writableDb); ContentValues cv = fillUpdateData(activity, i); cv.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); activity.localActivityId = writableDb.insertOrThrow(TABLE_NAME, null, cv); } } else { activity.localActivityId = writableDb.insertOrThrow( TABLE_NAME, null, fillUpdateData(activity, null)); } - if (activity.localActivityId < 0) { + if ((activity.localActivityId != null) && (activity.localActivityId < 0)) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } if(statement != null) { statement.close(); statement = null; } return ServiceStatus.SUCCESS; } /** * Deletes all activities from the table. * * @param flag Can be a bitmap of: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * <li>NULL - to delete all activities</li> * </ul> * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteActivities(final Integer flag, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteActivities()"); try { String whereClause = null; if (flag != null) { whereClause = Field.FLAG + "&" + flag; } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } public static ServiceStatus fetchNativeIdsFromLocalContactId(List<Integer > nativeItemIdList, final long localContactId, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNativeIdsFromLocalContactId()"); Cursor cursor = null; try { cursor = readableDb.rawQuery("SELECT " + Field.NATIVE_ITEM_ID + " FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + " = " + localContactId, null); while (cursor.moveToNext()) { nativeItemIdList.add(cursor.getInt(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchNativeIdsFromLocalContactId()" + "Unable to fetch list of NativeIds from localcontactId", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Deletes specified timeline activity from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivity(final Context context, final TimelineSummaryItem timelineItem, final SQLiteDatabase writableDb, final SQLiteDatabase readableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteTimelineActivity()"); try { List<Integer > nativeItemIdList = new ArrayList<Integer>() ; //Delete from Native Database if(timelineItem.mNativeThreadId != null) { //Sms Native Database final Uri smsUri = Uri.parse("content://sms"); context.getContentResolver().delete(smsUri , "thread_id=" + timelineItem.mNativeThreadId, null); //Mms Native Database final Uri mmsUri = Uri.parse("content://mms"); context.getContentResolver().delete(mmsUri, "thread_id=" + timelineItem.mNativeThreadId, null); } else { // For CallLogs if(timelineItem.mLocalContactId != null) { fetchNativeIdsFromLocalContactId(nativeItemIdList, timelineItem.mLocalContactId, readableDb); if(nativeItemIdList.size() > 0) { //CallLog Native Database for(Integer nativeItemId : nativeItemIdList) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + nativeItemId, null); } } } else { if(timelineItem.mContactAddress != null) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls.NUMBER + "=" + timelineItem.mContactAddress, null); } } } String whereClause = null; //Delete from People Client database if(timelineItem.mLocalContactId != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } else if(timelineItem.mContactAddress != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } /** * Deletes all the timeline activities for a particular contact from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivities(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.deleteTimelineActivities()"); Cursor cursor = null; try { TimelineNativeTypes[] typeList = null; //For CallLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); //For SmsLog/MmsLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); //For ChatLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }; deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * * Deletes one or more timeline items for a contact for the given types. * * @param context The app context to open the transaction in. * @param latestTimelineItem The latest item from the timeline to get the belonging contact from. * @param writableDb The database to write to. * @param readableDb The database to read from. * @param typeList The list of types to delete timeline events for. * * @return Returns a success if the transaction was successful, an error otherwise. * */ private static ServiceStatus deleteTimeLineActivitiesByType(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb, TimelineNativeTypes[] typeList) { Cursor cursor = null; TimelineSummaryItem timelineItem = null; try { cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { return deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * Fetches timeline events grouped by local contact ID, name or contact * address. Events returned will be in reverse-chronological order. If a * native type list is provided the result will be filtered by the list. * * @param minTimeStamp Only timeline events from this date will be returned * @param nativeTypes A list of native types to filter the result, or null * to return all. * @param readableDb Readable SQLite database * @return A cursor containing the result. The * {@link #getTimelineData(Cursor)} method should be used for * reading the cursor. */ public static Cursor fetchTimelineEventList(final Long minTimeStamp, final TimelineNativeTypes[] nativeTypes, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchTimelineEventList() " + "minTimeStamp[" + minTimeStamp + "]"); try { int andVal = 1; String typesQuery = " AND "; if (nativeTypes != null) { typesQuery += DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), nativeTypes, "OR"); typesQuery += " AND "; andVal = 2; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + Field.TIMESTAMP + " > " + minTimeStamp + " AND (" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") ORDER BY " + Field.TIMESTAMP + " DESC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchLastUpdateTime() " + "Unable to fetch timeline event list", e); return null; } } /** * Adds a list of timeline events to the database. Each event is grouped by * contact and grouped by contact + native type. * * @param itemList List of timeline events * @param isCallLog true to group all activities with call logs, false to * group with messaging * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error */ public static ServiceStatus addTimelineEvents( final ArrayList<TimelineSummaryItem> itemList, final boolean isCallLog, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addTimelineEvents()"); TimelineNativeTypes[] activityTypes; if (isCallLog) { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; } else { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; } for (TimelineSummaryItem item : itemList) { try { writableDb.beginTransaction(); if (findNativeActivity(item, writableDb)) { continue; } int latestStatusVal = 0; if (!TextUtils.isEmpty(item.mContactName) || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, activityTypes, writableDb); } else { // unknown contact latestStatusVal = 1; } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM); values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } item.mLocalActivityId = writableDb.insert(TABLE_NAME, null, values); if (item.mLocalActivityId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "ERROR_DATABASE_CORRUPT - Unable to add " + "timeline list to database"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /** * The method returns the ROW_ID i.e. the INTEGER PRIMARY KEY AUTOINCREMENT * field value for the inserted row, i.e. LOCAL_ID. * * @param item TimelineSummaryItem. * @param read - TRUE if the chat message is outgoing or gets into the * timeline history view for a contact with LocalContactId. * @param writableDb Writable SQLite database. * @return LocalContactID or -1 if the row was not inserted. */ public static long addChatTimelineEvent(final TimelineSummaryItem item, final boolean read, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addChatTimelineEvent()"); try { writableDb.beginTransaction(); int latestStatusVal = 0; if (item.mContactName != null || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }, writableDb); } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); /** Chat message body. **/ values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); if (read) { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); } else { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | 0); } values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); /** Conversation ID for chat message. **/ // values.put(Field.URI.toString(), item.conversationId); // 0 for incoming, 1 for outgoing if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } final long itemId = writableDb.insert(TABLE_NAME, null, values); if (itemId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() - " + "Unable to add timeline list to database, index<0:" + itemId); return -1; } writableDb.setTransactionSuccessful(); return itemId; } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return -1; } finally { writableDb.endTransaction(); } } /** * Clears the grouping of an activity in the database, if the given activity * is newer. This is so that only the latest activity is returned for a * particular group. Each activity is associated with two groups: * <ol> * <li>All group - Grouped by contact only</li> * <li>Native group - Grouped by contact and native type (call log or * messaging)</li> * </ol> * The group to be removed is determined by the activityTypes parameter. * Grouping must also work for timeline events that are not associated with * a contact. The following fields are used to do identify a contact for the * grouping (in order of priority): * <ol> * <li>localContactId - If it not null</li> * <li>name - If this is a valid telephone number, the match will be done to * ensure that the same phone number written in different ways will be * included in the group. See {@link #fetchNameWhereClause(Long, String)} * for more information.</li> * </ol> * * @param localContactId Local contact Id or NULL if the activity is not * associated with a contact. * @param name Name of contact or contact address (telephone number, email, * etc). * @param newUpdateTime The time that the given activity has occurred * @param flag Bitmap of types including: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * </ul> * @param activityTypes A list of native types to include in the grouping. * Currently, only two groups are supported (see above). If this * parameter is null the contact will be added to the * "all group", otherwise the contact is added to the native * group. * @param writableDb Writable SQLite database
360/360-Engine-for-Android
19157a9f823c653538fd2a93f271fd2f9e395df7
Fix broken build caused by previous PAND-1966 checkin
diff --git a/src/com/vodafone360/people/service/SyncAdapter.java b/src/com/vodafone360/people/service/SyncAdapter.java index 9464ed9..430e17b 100644 --- a/src/com/vodafone360/people/service/SyncAdapter.java +++ b/src/com/vodafone360/people/service/SyncAdapter.java @@ -1,257 +1,264 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import android.accounts.Account; import android.accounts.AccountManager; import android.content.AbstractThreadedSyncAdapter; import android.content.BroadcastReceiver; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SyncResult; import android.content.SyncStatusObserver; import android.os.Bundle; import android.os.Handler; import android.provider.ContactsContract; import com.vodafone360.people.MainApplication; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; import com.vodafone360.people.service.PersistSettings.InternetAvail; /** * SyncAdapter implementation which basically just ties in with * the old Contacts Sync Engine code for the moment and waits for the sync to be finished. * In the future we may want to improve this, particularly if the sync * is actually be done in this thread which would also enable disable sync altogether. */ public class SyncAdapter extends AbstractThreadedSyncAdapter implements IContactSyncObserver { // TODO: RE-ENABLE SYNC VIA SYSTEM // /** // * Direct access to Sync Engine stored for convenience // */ // private final ContactSyncEngine mSyncEngine = EngineManager.getInstance().getContactSyncEngine(); // // /** // * Boolean used to remember if we have requested a sync. // * Useful to ignore events // */ // private boolean mPerformSyncRequested = false; // /** - * Delay when checking our Sync Setting when we a global setting change. + * Delay when checking our Sync Setting when there is a authority auto-sync setting change. * This waiting time is necessary because in case it is our sync adapter authority setting * that changes we cannot query in the callback because the value is not yet changed! */ private static final int SYNC_SETTING_CHECK_DELAY = 500; + /** + * Same as ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS + * The reason we have this is just because the constant is not publicly defined before 2.2. + */ + private static final int SYNC_OBSERVER_TYPE_SETTINGS = 1; + /** * Application object instance */ private final MainApplication mApplication; /** * Broadcast receiver used to listen for changes in the Master Auto Sync setting * intent: com.android.sync.SYNC_CONN_STATUS_CHANGED */ private final BroadcastReceiver mAutoSyncChangeBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { setConnectionSettingForAutoSyncSetting(); } }; /** * Observer for the global sync status setting. - * There is no known way to only observer our sync adapter's setting. + * There is no known way to only observe our sync adapter's setting. */ private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() { @Override public void onStatusChanged(int which) { mHandler.postDelayed(mRunnable, SYNC_SETTING_CHECK_DELAY); } }; /** * Handler used to post to a runnable in order to wait * for a short time before checking the sync adapter * authority sync setting after a global change occurs. */ private final Handler mHandler = new Handler(); /** * Cached Account we use to query this Sync Adapter instance's Auto-sync setting. */ private Account mAccount; /** * Runnable used to post to a runnable in order to wait * for a short time before checking the sync adapter * authority sync setting after a global change occurs. * The reason we use this kind of mechanism is because: * a) There is an intent(com.android.sync.SYNC_CONN_STATUS_CHANGED) * we can listen to for the Master Auto-sync but, * b) The authority auto-sync observer pattern using ContentResolver * listens to EVERY sync adapter setting on the device AND * when the callback is received the value is not yet changed so querying for it is useless. */ private final Runnable mRunnable = new Runnable() { @Override public void run() { setConnectionSettingForAutoSyncSetting(); } }; public SyncAdapter(Context context, MainApplication application) { // No automatic initialization (false) super(context, false); mApplication = application; context.registerReceiver(mAutoSyncChangeBroadcastReceiver, new IntentFilter( "com.android.sync.SYNC_CONN_STATUS_CHANGED")); ContentResolver.addStatusChangeListener( - ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver); + SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver); // Register for sync event callbacks // TODO: RE-ENABLE SYNC VIA SYSTEM // mSyncEngine.addEventCallback(this); } /** * {@inheritDoc} */ @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { if(extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false)) { initializeSyncAdapter(account, authority); return; } setConnectionSettingForAutoSyncSetting(); // TODO: RE-ENABLE SYNC VIA SYSTEM // try { // synchronized(this) { // mPerformSyncRequested = true; // if(!mSyncEngine.isSyncing()) { // mSyncEngine.startFullSync(); // } // // while(mSyncEngine.isSyncing()) { // wait(POOLING_WAIT_INTERVAL); // } // mPerformSyncRequested = false; // } // } catch (InterruptedException e) { // e.printStackTrace(); // } } /** * @see IContactSyncObserver#onContactSyncStateChange(Mode, State, State) */ @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { // TODO: RE-ENABLE SYNC VIA SYSTEM // synchronized(this) { // /* // * This check is done so that we can also update the native UI // * when the client devices to sync on it own // */ // if(!mPerformSyncRequested && // mode != Mode.NONE) { // mPerformSyncRequested = true; // Account account = new Account( // LoginPreferences.getUsername(), // NativeContactsApi2.PEOPLE_ACCOUNT_TYPE); // ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); // } // } } /** * @see IContactSyncObserver#onProgressEvent(State, int) */ @Override public void onProgressEvent(State currentState, int percent) { // Nothing to do } /** * @see IContactSyncObserver#onSyncComplete(ServiceStatus) */ @Override public void onSyncComplete(ServiceStatus status) { // Nothing to do } /** * Initializes Sync settings for this Sync Adapter * @param account The account associated with the initialization * @param authority The authority of the content */ private void initializeSyncAdapter(Account account, String authority) { mAccount = account; // caching ContentResolver.setIsSyncable(account, authority, 1); ContentResolver.setSyncAutomatically(account, authority, true); } /** * Checks if this Sync Adapter is allowed to Sync Automatically * Basically just checking if the Master and its own Auto-sync are on. * The Master Auto-sync takes precedence over the authority Auto-sync. * @return true if the settings are enabled, false otherwise */ private boolean canSyncAutomatically() { if(!ContentResolver.getMasterSyncAutomatically()) { return false; } - return ContentResolver.getSyncAutomatically(mAccount, ContactsContract.AUTHORITY); + return mAccount != null && + ContentResolver.getSyncAutomatically(mAccount, ContactsContract.AUTHORITY); } /** * Sets the application data connection setting depending on the Auto-Sync Setting. * If Auto-sync is enabled then connection is to online ("always connect") * Otherwise connection is set to offline ("manual connect") */ private synchronized void setConnectionSettingForAutoSyncSetting() { if(canSyncAutomatically()) { // Enable data connection mApplication.setInternetAvail(InternetAvail.ALWAYS_CONNECT); } else { // Disable data connection mApplication.setInternetAvail(InternetAvail.MANUAL_CONNECT); } } }
360/360-Engine-for-Android
5fd2d20c83dbab10352f6734f3410ac79df7117c
Fix for PAND-1966: Implement the sync settings for our sync adapter / authenticator
diff --git a/src/com/vodafone360/people/MainApplication.java b/src/com/vodafone360/people/MainApplication.java index df9348c..4531aa5 100644 --- a/src/com/vodafone360/people/MainApplication.java +++ b/src/com/vodafone360/people/MainApplication.java @@ -1,211 +1,229 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import android.app.Application; +import android.content.ContentResolver; import android.os.Handler; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.engine.EngineManager; +import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.service.PersistSettings; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.interfaces.IPeopleService; import com.vodafone360.people.utils.LoginPreferences; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.WidgetUtils; /** * Application class used to create the connection to the service and cache * state between Activities. */ public class MainApplication extends Application { private IPeopleService mServiceInterface; private Handler mServiceLoadedHandler; private DatabaseHelper mDatabaseHelper; private final ApplicationCache mApplicationCache = new ApplicationCache(); /** * Called when the Application is created. */ @Override public void onCreate() { super.onCreate(); SettingsManager.loadProperties(this); mDatabaseHelper = new DatabaseHelper(this); mDatabaseHelper.start(); LoginPreferences.getCurrentLoginActivity(this); } /** * Called when the Application is exited. */ @Override public void onTerminate() { // FlurryAgent.onEndSession(this); if (mDatabaseHelper != null) { mDatabaseHelper.close(); } super.onTerminate(); } /** * Return handle to DatabaseHelper, currently provides main point of access * to People client's database tables. * * @return Handle to DatabaseHelper. */ public DatabaseHelper getDatabase() { return mDatabaseHelper; } /** * Return handle to ApplicationCache. * * @return handle to ApplicationCache. */ public ApplicationCache getCache() { return mApplicationCache; } /** * Remove all user data from People client, this includes all account * information (downloaded contacts, login credentials etc.) and all cached * settings. */ public synchronized void removeUserData() { EngineManager mEngineManager = EngineManager.getInstance(); if (mEngineManager != null) { // Resets all the engines, the call will block until every engines // have been reset. mEngineManager.resetAllEngines(); } mDatabaseHelper.removeUserData(); // Before clearing the Application cache, kick the widget update. Pref's // file contain the widget ID. WidgetUtils.kickWidgetUpdateNow(this); mApplicationCache.clearCachedData(this); } /** * Register a Handler to receive notification when the People service has * loaded. If mServiceInterface == NULL then this means that the UI is * starting before the service has loaded - in this case the UI registers to * be notified when the service is loaded using the serviceLoadedHandler. * TODO: consider any pitfalls in this situation. * * @param serviceLoadedHandler Handler that receives notification of service * being loaded. */ public synchronized void registerServiceLoadHandler(Handler serviceLoadedHandler) { if (mServiceInterface != null) { onServiceLoaded(); } else { mServiceLoadedHandler = serviceLoadedHandler; LogUtils.logI("MainApplication.registerServiceLoadHandler() mServiceInterface is NULL " + "- need to wait for service to be loaded"); } } /** * Un-register People service loading handler. */ public synchronized void unRegisterServiceLoadHandler() { mServiceLoadedHandler = null; } private void onServiceLoaded() { if (mServiceLoadedHandler != null) { mServiceLoadedHandler.sendEmptyMessage(0); } } /** * Set IPeopleService interface - this is the interface by which we * interface to People service. * * @param serviceInterface IPeopleService handle. */ public synchronized void setServiceInterface(IPeopleService serviceInterface) { if (serviceInterface == null) { LogUtils.logE("MainApplication.setServiceInterface() " + "New serviceInterface should not be NULL"); } mServiceInterface = serviceInterface; onServiceLoaded(); } /** * Return current IPeopleService interface. TODO: The case where * mServiceInterface = NULL needs to be considered. * * @return current IPeopleService interface (can be null). */ public synchronized IPeopleService getServiceInterface() { if (mServiceInterface == null) { LogUtils.logE("MainApplication.getServiceInterface() " + "mServiceInterface should not be NULL"); } return mServiceInterface; } /** * Set Internet availability - always makes Internet available, only * available in home network, allow manual connection only. This setting is * stored in People database. * * @param internetAvail Internet availability setting. * @return SerivceStatus indicating whether the Internet availability * setting has been successfully updated in the database. */ public ServiceStatus setInternetAvail(InternetAvail internetAvail) { + if(getInternetAvail() == internetAvail) { + // Nothing to do + return ServiceStatus.SUCCESS; + } + + if(internetAvail == InternetAvail.ALWAYS_CONNECT && + !NativeContactsApi.getInstance().getMasterSyncAutomatically()) { + // FIXME: Perhaps an abusive use of this error code for when + // Master Sync Automatically is OFF, should have a different + return ServiceStatus.ERROR_NO_AUTO_CONNECT; + } + PersistSettings mPersistSettings = new PersistSettings(); mPersistSettings.putInternetAvail(internetAvail); ServiceStatus ss = mDatabaseHelper.setOption(mPersistSettings); + // FIXME: This is a hack in order to set the system auto sync on/off depending on our data settings + NativeContactsApi.getInstance().setSyncAutomatically( + internetAvail == InternetAvail.ALWAYS_CONNECT); + synchronized (this) { if (mServiceInterface != null) { mServiceInterface.notifyDataSettingChanged(internetAvail); } else { LogUtils.logE("MainApplication.setInternetAvail() " + "mServiceInterface should not be NULL"); } } return ss; } /** * Retrieve Internet availability setting from People database. * * @return current Internet availability setting. */ public InternetAvail getInternetAvail() { return mDatabaseHelper.fetchOption(PersistSettings.Option.INTERNETAVAIL).getInternetAvail(); } } diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java index 84dfeab..e053a02 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java @@ -1,393 +1,408 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.security.InvalidParameterException; import android.content.ContentResolver; import android.content.Context; import android.text.TextUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * Class that provides an abstraction layer for accessing the Native Contacts API. * The underlying API to be used should be the most suitable for the SDK version of the device. */ public abstract class NativeContactsApi { /** * 360 client account type. */ protected static final int PEOPLE_ACCOUNT_TYPE = 1; /** * Google account type. */ protected static final int GOOGLE_ACCOUNT_TYPE = 2; /** * Vendor specific type. */ protected static final int PHONE_ACCOUNT_TYPE = 3; /** * Account type for 360 People in the Native Accounts. * MUST be a copy of type in 'res/xml/authenticator.xml' */ protected static final String PEOPLE_ACCOUNT_TYPE_STRING = "com.vodafone360.people.android.account"; /** * Google account, there can be more than one of these */ protected static final String GOOGLE_ACCOUNT_TYPE_STRING = "com.google"; /** * There are devices with custom contact applications. For them we need * special handling of contacts. */ protected static final String[] VENDOR_SPECIFIC_ACCOUNTS = { "com.htc.android.pcsc", "vnd.sec.contact.phone", "com.motorola.blur.service.bsutils.MOTHER_USER_CREDS_TYPE" }; /** * {@link NativeContactsApi} the singleton instance providing access to the correct Contacts API interface */ private static NativeContactsApi sInstance; /** * {@link Context} to be used by the Instance */ protected Context mContext; /** * {@link ContentResolver} be used by the Instance */ protected ContentResolver mCr; /** * Sadly have to have this so that only one organization may be read from a * NAB Contact */ protected boolean mHaveReadOrganization = false; /** * Sadly have to have this because Organization detail is split into two * details in CAB */ protected int mMarkedOrganizationIndex = -1; /** * Sadly have to have this because Organization detail is split into two * details in CAB */ protected int mMarkedTitleIndex = -1; /** * Create NativeContactsApi singleton instance for later usage. The instance * can retrieved by calling getInstance(). * The instance can be destroyed * by calling destroyInstance() * * @see NativeContactsApi#getInstance() * @see NativeContactsApi#destroyInstance() * @param context The context to be used by the singleton */ public static void createInstance(Context context) { LogUtils.logW("NativeContactsApi.createInstance()"); String className; if (VersionUtils.is2XPlatform()) { className = "NativeContactsApi2"; LogUtils.logD("Using 2.X Native Contacts API"); } else { className = "NativeContactsApi1"; LogUtils.logD("Using 1.X Native Contacts API"); } try { Class<? extends NativeContactsApi> clazz = Class.forName( NativeContactsApi.class.getPackage().getName() + "." + className).asSubclass( NativeContactsApi.class); sInstance = clazz.newInstance(); } catch (Exception e) { throw new IllegalStateException("NativeContactsApi.createInstance()" + "Error creating a subclass of NativeContactsApi", e); } sInstance.mContext = context; sInstance.mCr = context.getContentResolver(); // Initialize the instance now (got Context and Content Resolver) sInstance.initialize(); } /** * Destroy NativeContactsApi singleton instance if created. The instance can * be recreated by calling createInstance() * * @see NativeContactsApi#createInstance() */ public static void destroyInstance() { if (sInstance != null) { sInstance.mCr = null; sInstance.mContext = null; sInstance = null; } } /** * Retrieves singleton instance providing access to the native contacts api. * * @return {@link NativeContactsApi} appropriate subclass instantiation */ public static NativeContactsApi getInstance() { if (sInstance == null) { throw new InvalidParameterException("Please call " + "NativeContactsApi.createInstance() " + "before NativeContactsApi.getInstance()"); } return sInstance; } /** * This Account class represents an available account on the device where * the native synchronization can be performed. */ public static class Account { /** * The name of the account. */ private String mName; /** * The type of the account. */ private String mType; /** * The Constructor. * * @param name the account name * @param type the account type */ public Account(String name, String type) { mName = name; mType = type; } /** * Gets the name of the account. * * @return the account name */ public String getName() { return mName; } /** * Gets the type of the accounts. * * @return the account type */ public String getType() { return mType; } /** * Checks if this account is a People Account * * @return true if this account is a People Account, false if not */ public boolean isPeopleAccount() { return TextUtils.equals(mType, PEOPLE_ACCOUNT_TYPE_STRING); } /** * Returns a String representation of the account. */ public String toString() { return "Account: name=" + mName + ", type=" + mType; } } /** * The Observer interface to receive notifications about changes in the * native address book. */ public static interface ContactsObserver { /** * Call-back to notify that a change happened in the native address * book. */ void onChange(); } /** * Method meant to be called only just after createInstance() is invoked. * This method effectively acts as a replacement for the constructor because * of the use of reflection. */ protected abstract void initialize(); /** * Registers a content observer. Note: the method only supports one observer * at a time. * * @param observer ContactsObserver currently observing native address book * changes * @throws RuntimeException if a new observer is being registered without * having unregistered the previous one */ public abstract void registerObserver(ContactsObserver observer); /** * Unregister the previously registered content observer. */ public abstract void unregisterObserver(); /** * Fetches all the existing Accounts on the device. Only supported on 2.X. * The 1.X implementation always returns null. * * @return An array containing all the Accounts on the device, or null if * none exist */ public abstract Account[] getAccounts(); /** * Fetches all the existing Accounts on the device corresponding to the * provided Type Only supported on 2.X. The 1.X implementation always * returns null. * * @param type The Type of Account to fetch * @return An array containing all the Accounts of the provided Type, or * null if none exist */ public abstract Account[] getAccountsByType(int type); /** * Adds the currently logged in user account to the NAB accounts. Only * supported on 2.X. The 1.X implementation does nothing. * * @return true if successful, false if not */ public abstract boolean addPeopleAccount(String username); /** * Checks if there is a People Account in the NAB Accounts. Only supported * on 2.X The 1.X implementation does nothing. * * @return true if an account exists, false if not. */ public abstract boolean isPeopleAccountCreated(); /** * Removes the (first found) People Account from the NAB accounts. Only * supported on 2.X. The 1.X implementation does nothing. */ public abstract void removePeopleAccount(); /** * Retrieves a list of contact IDs for a specific account. In 1.X devices * only the null account is supported, i.e., a non null account always uses * null as a return value. * * @param account The account to get contact IDs from (may be null) * @return List of contact IDs from the native address book */ public abstract long[] getContactIds(Account account); /** * Gets data for one Contact. * * @param nabContactId Native ID for the contact * @return A {@link ContactChange} array with contact's data or null */ public abstract ContactChange[] getContact(long nabContactId); /** * Adds a contact. Note that the returned ID data will be the same size of * ccList plus one change containing the NAB Contact ID (at the first * position). The remaining IDs correspond to the details in the original * change list. Null IDs among these remaining IDs are possible when these * correspond to unsupported details. On 1.X Devices only a null account * parameter is expected. * * @param account Account to be associated with the added contact (may be * null). * @param ccList The Contact data as a {@link ContactChange} array * @return A {@link ContactChange} array with contact's new ID data or null * in case of failure. */ public abstract ContactChange[] addContact(Account account, ContactChange[] ccList); /** * Updates an existing contact. The returned ID data will be the same size * of the ccList. However, if a null or empty ccList is passed as an * argument then null is returned. Null IDs among the ID data are also * possible when these correspond to unsupported details. * * @param ccList The Contact update data as a {@link ContactChange} array * @return A {@link ContactChange} array with the contact's new ID data or * null */ public abstract ContactChange[] updateContact(ContactChange[] ccList); /** * Removes a contact * * @param nabContactId Native ID of the contact to remove */ public abstract void removeContact(long nabContactId); + + /** + * Used to retrieve the master Auto-sync setting for the system. + * Method only exists to get around platform fragmentation. + * Note that this method always returns true for 1.X devices! + * @return true if the Master Auto-sync is enabled, false otherwise + */ + public abstract boolean getMasterSyncAutomatically(); + + /** + * Used to forcefully set the underlying Sync adapter to be Automatically Syncable or not. + * This is really only useful for 2.X devices and for System UE. + * @param syncAutomatically if true Sync is Automatic, false otherwise + */ + public abstract void setSyncAutomatically(boolean syncAutomatically); /** * Checks whether or not a {@link ContactChange} key is supported. Results * may vary in 1.X and 2.X * * @param key Key to check for support * @return true if supported, false if not */ public abstract boolean isKeySupported(int key); /** * Checks if this account is a vendor specific one. All vendor specific * accounts are held in the VENDOR_SPECIFIC_ACCOUNTS array. * * @param type to checks for * @return true if vendor specific account, false otherwise */ public boolean isVendorSpecificAccount(String type) { for (String vendorSpecificType : VENDOR_SPECIFIC_ACCOUNTS) { if (vendorSpecificType.equals(type)) { return true; } } return false; } } diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java index 78c843d..39862b9 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java @@ -1,918 +1,935 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.List; import android.content.ContentUris; import android.content.ContentValues; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.provider.Contacts; import android.provider.Contacts.ContactMethods; import android.provider.Contacts.Organizations; import android.provider.Contacts.People; import android.provider.Contacts.Phones; import android.text.TextUtils; import android.util.SparseIntArray; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.VCardHelper.Name; import com.vodafone360.people.datatypes.VCardHelper.Organisation; import com.vodafone360.people.datatypes.VCardHelper.PostalAddress; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.LogUtils; /** * The implementation of the NativeContactsApi for the Android 1.X platform. */ @SuppressWarnings("deprecation") // Needed to hide warnings because we are using deprecated 1.X native apis // APIs public class NativeContactsApi1 extends NativeContactsApi { /** * Convenience Contact ID Projection. */ private final static String[] CONTACTID_PROJECTION = { People._ID }; /** * Convenience Projection for the NATE and NOTES from the People table */ private final static String[] PEOPLE_PROJECTION = { People.NAME, People.NOTES }; /** * Contact methods table kind value for email. */ private static final int CONTACT_METHODS_KIND_EMAIL = 1; /** * Contact methods table kind value for postal address. */ private static final int CONTACT_METHODS_KIND_ADDRESS = 2; /** * Mapping of supported {@link ContactChange} Keys. */ private static final SparseIntArray sSupportedKeys; static { sSupportedKeys = new SparseIntArray(7); sSupportedKeys.append(ContactChange.KEY_VCARD_NAME, 0); sSupportedKeys.append(ContactChange.KEY_VCARD_PHONE, 0); sSupportedKeys.append(ContactChange.KEY_VCARD_EMAIL, 0); sSupportedKeys.append(ContactChange.KEY_VCARD_ADDRESS, 0); sSupportedKeys.append(ContactChange.KEY_VCARD_ORG, 0); sSupportedKeys.append(ContactChange.KEY_VCARD_TITLE, 0); sSupportedKeys.append(ContactChange.KEY_VCARD_NOTE, 0); } /** * Values used for writing to NAB */ private final ContentValues mValues = new ContentValues(); /** * The registered ContactsObserver. * * @see #registerObserver(ContactsObserver) */ private ContactsObserver mContactsObserver; /** * The observer for the native contacts. */ private ContentObserver mNativeObserver; /** * @see NativeContactsApi#initialize() */ @Override protected void initialize() { // Nothing to do } /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { if (mContactsObserver != null) { throw new RuntimeException( "NativeContactsApi1.registerObserver(): current implementation only supports one observer" + " at a time... Please unregister first."); } mContactsObserver = observer; mNativeObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { mContactsObserver.onChange(); } }; mCr.registerContentObserver(Contacts.CONTENT_URI, true, mNativeObserver); } /** * @see NativeContactsApi#unregisterObserver() */ @Override public void unregisterObserver() { if (mContactsObserver != null) { mContactsObserver = null; mCr.unregisterContentObserver(mNativeObserver); mNativeObserver = null; } } /** * @see NativeContactsApi#getAccounts() */ @Override public Account[] getAccounts() { // No accounts on 1.X NAB return null; } /** * @see NativeContactsApi#getAccountsByType(String) */ @Override public Account[] getAccountsByType(int type) { // No accounts on 1.X NAB return null; } /** * @see NativeContactsApi#addPeopleAccount(String) */ @Override public boolean addPeopleAccount(String username) { // No People Accounts on 1.X NAB return false; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { // No People Accounts on 1.X NAB return false; } /** * @see NativeContactsApi#removePeopleAccount() */ @Override public void removePeopleAccount() { // No People Accounts on 1.X NAB } /** * @see NativeContactsApi#getContactIds(Account) */ @Override public long[] getContactIds(Account account) { if (account != null) { // Accounts not supported in 1.X, just return null LogUtils.logE("NativeContactsApi1.getContactIds() Unexpected non-null Account(\"" + account.toString() + "\""); return null; } long[] ids = null; final Cursor cursor = mCr.query(People.CONTENT_URI, CONTACTID_PROJECTION, null, null, People._ID); try { final int idCount = cursor.getCount(); if (idCount > 0) { ids = new long[idCount]; int index = 0; while (cursor.moveToNext()) { ids[index] = cursor.getLong(0); index++; } } } finally { CursorUtils.closeCursor(cursor); } return ids; } /** * @see NativeContactsApi#getContact(long) */ @Override public ContactChange[] getContact(long nabContactId) { final List<ContactChange> ccList = new ArrayList<ContactChange>(); final Cursor cursor = mCr.query(ContentUris .withAppendedId(People.CONTENT_URI, nabContactId), PEOPLE_PROJECTION, null, null, null); try { if (cursor.moveToNext()) { final String displayName = CursorUtils.getString(cursor, People.NAME); if (!TextUtils.isEmpty(displayName)) { // TODO: Remove if really not necessary // final Name name = parseRawName(displayName); final Name name = new Name(); name.firstname = displayName; final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NAME, VCardHelper.makeName(name), ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); ccList.add(cc); } // Note final String note = CursorUtils.getString(cursor, People.NOTES); if (!TextUtils.isEmpty(note)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NOTE, note, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); ccList.add(cc); } // Remaining contact details readContactPhoneNumbers(ccList, nabContactId); readContactMethods(ccList, nabContactId); readContactOrganizations(ccList, nabContactId); } } finally { CursorUtils.closeCursor(cursor); } return ccList.toArray(new ContactChange[ccList.size()]); } /** * @see NativeContactsApi#addContact(Account, ContactChange[]) */ @Override public ContactChange[] addContact(Account account, ContactChange[] ccList) { if (account != null) { // Accounts not supported in 1.X, just return null return null; } /* * These details need special treatment: Name and Note (written to * people table); Organization/Title (written as one detail in NAB). */ mMarkedOrganizationIndex = mMarkedTitleIndex = -1; preprocessContactToAdd(ccList); Uri uri = mCr.insert(People.CONTENT_URI, mValues); if (uri != null) { // Change List to hold resulting changes for the add contact // (including +1 for contact id) final ContactChange[] idChangeList = new ContactChange[ccList.length + 1]; final long nabContactId = ContentUris.parseId(uri); idChangeList[0] = ContactChange.createIdsChange(ccList[0], ContactChange.TYPE_UPDATE_NAB_CONTACT_ID); idChangeList[0].setNabContactId(nabContactId); writeDetails(ccList, idChangeList, nabContactId); processOrganization(ccList, idChangeList, nabContactId); return idChangeList; } return null; } /** * @see NativeContactsApi#updateContact(ContactChange[]) */ @Override public ContactChange[] updateContact(ContactChange[] ccList) { if (ccList == null || ccList.length == 0) { LogUtils.logW("NativeContactsApi1.updateContact() nothing to update - empty ccList!"); return null; } mMarkedOrganizationIndex = mMarkedTitleIndex = -1; final long nabContactId = ccList[0].getNabContactId(); final int ccListSize = ccList.length; final ContactChange[] idCcList = new ContactChange[ccListSize]; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc.getKey() == ContactChange.KEY_VCARD_ORG) { if (mMarkedOrganizationIndex < 0) { mMarkedOrganizationIndex = i; } continue; } if (cc.getKey() == ContactChange.KEY_VCARD_TITLE) { if (mMarkedTitleIndex < 0) { mMarkedTitleIndex = i; } continue; } switch (cc.getType()) { case ContactChange.TYPE_ADD_DETAIL: final int key = cc.getKey(); if (key != ContactChange.KEY_VCARD_NAME && key != ContactChange.KEY_VCARD_NOTE) { final long nabDetailId = insertDetail(cc, nabContactId); if (nabDetailId != ContactChange.INVALID_ID) { idCcList[i] = ContactChange.createIdsChange(cc, ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idCcList[i].setNabDetailId(nabDetailId); } } else { // Name and Note are not inserted but updated because // they are always there! updateDetail(cc); } break; case ContactChange.TYPE_UPDATE_DETAIL: updateDetail(cc); break; case ContactChange.TYPE_DELETE_DETAIL: deleteDetail(cc.getKey(), nabContactId, cc.getNabDetailId()); break; default: break; } } final long orgDetailId = updateOrganization(ccList, nabContactId); if (orgDetailId != ContactChange.INVALID_ID) { if (mMarkedOrganizationIndex >= 0 && ccList[mMarkedOrganizationIndex].getType() == ContactChange.TYPE_ADD_DETAIL) { idCcList[mMarkedOrganizationIndex] = ContactChange.createIdsChange( ccList[mMarkedOrganizationIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idCcList[mMarkedOrganizationIndex].setNabDetailId(orgDetailId); } if (mMarkedTitleIndex >= 0 && ccList[mMarkedTitleIndex].getType() == ContactChange.TYPE_ADD_DETAIL) { idCcList[mMarkedTitleIndex] = ContactChange.createIdsChange( ccList[mMarkedTitleIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idCcList[mMarkedTitleIndex].setNabDetailId(orgDetailId); } } return idCcList; } /** * @see NativeContactsApi#removeContact(long) */ @Override public void removeContact(long nabContactId) { Uri rawContactUri = ContentUris.withAppendedId(People.CONTENT_URI, nabContactId); mCr.delete(rawContactUri, null, null); } + + /** + * @see NativeContactsApi#getMasterSyncAutomatically + */ + @Override + public boolean getMasterSyncAutomatically() { + // Always true in 1.X + return true; + } + + /** + * @see NativeContactsApi#setSyncAutomatically(boolean) + */ + @Override + public void setSyncAutomatically(boolean syncAutomatically) { + // Nothing to do + } /** * @see NativeContactsApi#isKeySupported(int) */ @Override public boolean isKeySupported(int key) { return sSupportedKeys.indexOfKey(key) >= 0; } /** * Reads Phone Number details from a Contact into the provided * {@link ContactChange} List * * @param ccList {@link ContactChange} list to add details into * @param nabContactId ID of the NAB Contact */ private void readContactPhoneNumbers(List<ContactChange> ccList, long nabContactId) { final Uri contactUri = ContentUris.withAppendedId(People.CONTENT_URI, nabContactId); final Uri phoneUri = Uri.withAppendedPath(contactUri, People.Phones.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(phoneUri, null, null, null, null); if (cursor == null) { return; } try { while (cursor.moveToNext()) { final ContactChange cc = readContactPhoneNumber(cursor); if (cc != null) { cc.setNabContactId(nabContactId); ccList.add(cc); } } } finally { CursorUtils.closeCursor(cursor); } } /** * Reads one Phone Number Detail from the supplied cursor into a * {@link ContactChange} * * @param cursor Cursor to read from * @return Read Phone Number Detail or null */ private ContactChange readContactPhoneNumber(Cursor cursor) { ContactChange cc = null; final String phoneNumber = CursorUtils.getString(cursor, Phones.NUMBER); if (!TextUtils.isEmpty(phoneNumber)) { final long nabDetailId = CursorUtils.getLong(cursor, Phones._ID); final boolean isPrimary = CursorUtils.getInt(cursor, Phones.ISPRIMARY) != 0; final int rawType = CursorUtils.getInt(cursor, Phones.TYPE); int flags = mapFromNabPhoneType(rawType); if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } cc = new ContactChange(ContactChange.KEY_VCARD_PHONE, phoneNumber, flags); cc.setNabDetailId(nabDetailId); } return cc; } /** * Reads Contact Method details from a Contact into the provided * {@link ContactChange} List * * @param ccList {@link ContactChange} list to add details into * @param nabContactId ID of the NAB Contact */ private void readContactMethods(List<ContactChange> ccList, long nabContactId) { Uri contactUri = ContentUris.withAppendedId(People.CONTENT_URI, nabContactId); Uri contactMethodUri = Uri.withAppendedPath(contactUri, People.ContactMethods.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(contactMethodUri, null, null, null, null); if (cursor == null) { return; } try { while (cursor.moveToNext()) { final ContactChange cc = readContactMethod(cursor); if (cc != null) { cc.setNabContactId(nabContactId); ccList.add(cc); } } } finally { CursorUtils.closeCursor(cursor); } } /** * Reads one Contact Method Detail from the supplied cursor into a * {@link ContactChange} * * @param cursor Cursor to read from * @return Read Contact Method Detail or null */ private ContactChange readContactMethod(Cursor cursor) { ContactChange cc = null; final String value = CursorUtils.getString(cursor, ContactMethods.DATA); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, ContactMethods._ID); final boolean isPrimary = CursorUtils.getInt(cursor, ContactMethods.ISPRIMARY) != 0; final int kind = CursorUtils.getInt(cursor, ContactMethods.KIND); final int type = CursorUtils.getInt(cursor, ContactMethods.TYPE); int flags = mapFromNabContactMethodType(type); if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } if (kind == CONTACT_METHODS_KIND_EMAIL) { cc = new ContactChange(ContactChange.KEY_VCARD_EMAIL, value, flags); cc.setNabDetailId(nabDetailId); } else if (kind == CONTACT_METHODS_KIND_ADDRESS) { if (!TextUtils.isEmpty(value)) { cc = new ContactChange(ContactChange.KEY_VCARD_ADDRESS, VCardHelper .makePostalAddress(parseRawAddress(value)), flags); cc.setNabDetailId(nabDetailId); } } } return cc; } /** * Reads Organization details from a Contact into the provided * {@link ContactChange} List * * @param ccList {@link ContactChange} list to add details into * @param nabContactId ID of the NAB Contact */ private void readContactOrganizations(List<ContactChange> ccList, long nabContactId) { final Uri contactUri = ContentUris.withAppendedId(People.CONTENT_URI, nabContactId); final Uri contactOrganizationsUri = Uri.withAppendedPath(contactUri, Contacts.Organizations.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(contactOrganizationsUri, null, null, null, Organizations._ID); if (cursor == null) { return; } try { // Only loops while there is not Organization read (CAB limitation!) while (!mHaveReadOrganization && cursor.moveToNext()) { readContactOrganization(cursor, ccList, nabContactId); } } finally { CursorUtils.closeCursor(cursor); } // Reset the boolean flag mHaveReadOrganization = false; } /** * Reads one Organization Detail from the supplied cursor into a * {@link ContactChange} Note that this method may actually read up to 2 * into Contact Changes. However, Organization and Title may only be read if * a boolean flag is not set * * @param cursor Cursor to read from * @param ccList {@link ContactChange} list to add details to * @param nabContactId ID of the NAB Contact * @return Read Contact Method Detail or null */ private void readContactOrganization(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final long nabDetailId = CursorUtils.getLong(cursor, Organizations._ID); final boolean isPrimary = CursorUtils.getInt(cursor, Organizations.ISPRIMARY) != 0; final int type = CursorUtils.getInt(cursor, Organizations.TYPE); int flags = mapFromNabOrganizationType(type); if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } if (!mHaveReadOrganization) { // Company final String company = CursorUtils.getString(cursor, Organizations.COMPANY); if (!TextUtils.isEmpty(company)) { // Escaping the value (no need to involve the VCardHelper just // for the company) final String escapedCompany = company.replace(";", "\\;"); final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_ORG, escapedCompany, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } // Title final String title = CursorUtils.getString(cursor, Organizations.TITLE); if (!TextUtils.isEmpty(title)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_TITLE, title, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } } } /** * "Pre-processing" of {@link ContactChange} list before it can be added to * NAB. This needs to be done because of issues on the 1.X NAB and our CAB * In 1.X NAB: Name and Note which are stored differently from other details * In our CAB: Organization and Title are separate details contrary to the * NAB * * @param ccList {@link ContactChange} list for the add operation */ private void preprocessContactToAdd(ContactChange[] ccList) { final int ccListSize = ccList.length; boolean nameFound = false, noteFound = false; mValues.clear(); for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc != null) { if (!nameFound && cc.getKey() == ContactChange.KEY_VCARD_NAME) { final Name name = VCardHelper.getName(cc.getValue()); mValues.put(People.NAME, name.toString()); nameFound = true; } if (!noteFound && cc.getKey() == ContactChange.KEY_VCARD_NOTE) { mValues.put(People.NOTES, cc.getValue()); noteFound = true; } if (mMarkedOrganizationIndex < 0 && cc.getKey() == ContactChange.KEY_VCARD_ORG) { mMarkedOrganizationIndex = i; } if (mMarkedTitleIndex < 0 && cc.getKey() == ContactChange.KEY_VCARD_TITLE) { mMarkedTitleIndex = i; } } } } /** * Writes new details from a provided {@link ContactChange} list into the * NAB. The resulting detail IDs are put in another provided * {@link ContactChange} list. * * @param ccList {@link ContactChange} list to write from * @param idChangeList {@link ContatChange} list where IDs for the written * details are put * @param nabContactId ID of the NAB Contact */ private void writeDetails(ContactChange[] ccList, ContactChange[] idChangeList, long nabContactId) { final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc != null) { long nabDetailId = insertDetail(cc, nabContactId); if (nabDetailId != ContactChange.INVALID_ID) { // The +1 assumes prior addition of the contact id at // position 0 idChangeList[i + 1] = ContactChange.createIdsChange(cc, ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChangeList[i + 1].setNabDetailId(nabDetailId); } } } } /** * Inserts a new detail to NAB * * @param cc {@link ContactChange} to read data from * @param nabContactId ID of the NAB Contact * @return The created detail's ID */ private long insertDetail(ContactChange cc, long nabContactId) { mValues.clear(); Uri contentUri = null; switch (cc.getKey()) { case ContactChange.KEY_VCARD_PHONE: putPhoneValues(cc, nabContactId); contentUri = Phones.CONTENT_URI; break; case ContactChange.KEY_VCARD_EMAIL: putContactMethodValues(cc, CONTACT_METHODS_KIND_EMAIL, nabContactId); contentUri = ContactMethods.CONTENT_URI; break; case ContactChange.KEY_VCARD_ADDRESS: putContactMethodValues(cc, CONTACT_METHODS_KIND_ADDRESS, nabContactId); contentUri = ContactMethods.CONTENT_URI; break; } if (contentUri != null) { Uri uri = mCr.insert(contentUri, mValues); if (uri != null) { return ContentUris.parseId(uri); } } return ContactChange.INVALID_ID; } /** * Updates a detail. * * @param cc {@link ContactChange} to read data from * @param nabContactId ID of the NAB Contact * @return true if the detail was updated, false if not */ private boolean updateDetail(ContactChange cc) { mValues.clear(); Uri contentUri = null; long nabDetailId = cc.getNabDetailId(); final long nabContactId = cc.getNabContactId(); switch (cc.getKey()) { case ContactChange.KEY_VCARD_PHONE: putPhoneValues(cc, nabContactId); contentUri = Phones.CONTENT_URI; break; case ContactChange.KEY_VCARD_EMAIL: putContactMethodValues(cc, CONTACT_METHODS_KIND_EMAIL, nabContactId); contentUri = ContactMethods.CONTENT_URI; break; case ContactChange.KEY_VCARD_ADDRESS: putContactMethodValues(cc, CONTACT_METHODS_KIND_ADDRESS, nabContactId); contentUri = ContactMethods.CONTENT_URI; break; case ContactChange.KEY_VCARD_NAME: final Name name = VCardHelper.getName(cc.getValue()); mValues.put(People.NAME, name.toString()); contentUri = People.CONTENT_URI; nabDetailId = nabContactId; break; case ContactChange.KEY_VCARD_NOTE: mValues.put(People.NOTES, cc.getValue()); contentUri = People.CONTENT_URI; nabDetailId = nabContactId; break; } if (contentUri != null) { Uri uri = ContentUris.withAppendedId(contentUri, nabDetailId); return mCr.update(uri, mValues, null, null) > 0; } return false; } /** * Deletes a detail from NAB * * @param key The detail key * @param nabContactId ID of the NAB Contact * @param nabDetailId ID of the NAB Detail * @return true if the detail was deleted, false if not */ private boolean deleteDetail(int key, long nabContactId, long nabDetailId) { mValues.clear(); Uri contentUri = null; switch (key) { case ContactChange.KEY_VCARD_PHONE: contentUri = Phones.CONTENT_URI; break; case ContactChange.KEY_VCARD_EMAIL: case ContactChange.KEY_VCARD_ADDRESS: contentUri = ContactMethods.CONTENT_URI; break; case ContactChange.KEY_VCARD_NAME: mValues.putNull(People.NAME); contentUri = People.CONTENT_URI; nabDetailId = nabContactId; break; case ContactChange.KEY_VCARD_NOTE: mValues.putNull(People.NOTES); contentUri = People.CONTENT_URI; nabDetailId = nabContactId; break; } if (contentUri != null) { final Uri uri = ContentUris.withAppendedId(contentUri, nabDetailId); if (mValues.size() > 0) { return mCr.update(uri, mValues, null, null) > 0; } else { return mCr.delete(uri, null, null) > 0; } } return false; } /** * Put Phone detail into the values * * @param cc * @param nabContactId ID of the NAB Contact */ private void putPhoneValues(ContactChange cc, long nabContactId) { mValues.put(Phones.PERSON_ID, nabContactId); mValues.put(Phones.NUMBER, cc.getValue()); int flags = cc.getFlags(); mValues.put(Phones.TYPE, mapToNabPhoneType(flags)); mValues.put(Phones.ISPRIMARY, flags & ContactChange.FLAG_PREFERRED); /* * Forcing the label field to be null because we don't support custom * labels and in case we replace from a custom label to home or private * type without setting label to null, mCr.update() will throw a SQL * constraint exception. */ mValues.put(Phones.LABEL, (String)null); } /** * Put Contact Methods detail into the values * * @param cc {@link ContactChange} to read values from * @param kind The kind of contact method (email or address) * @param nabContactId ID of the NAB Contact */ private void putContactMethodValues(ContactChange cc, int kind, long nabContactId) { mValues.put(ContactMethods.PERSON_ID, nabContactId); if (kind == CONTACT_METHODS_KIND_EMAIL) { mValues.put(ContactMethods.DATA, cc.getValue()); } else { // Must be Address, once again need to use VCardHelper to extract // address PostalAddress address = VCardHelper.getPostalAddress(cc.getValue()); mValues.put(ContactMethods.DATA, address.toString()); } mValues.put(ContactMethods.KIND, kind); int flags = cc.getFlags(); mValues.put(ContactMethods.TYPE, mapToNabContactMethodType(flags)); mValues.put(ContactMethods.ISPRIMARY, flags & ContactChange.FLAG_PREFERRED); } /** * Ugly method to process organization for writing to NAB * * @param ccList {@link ContactChange} list to fetch organization from * @param idChangeList {@link ContatChange} list where IDs for the written * organization are put * @param nabContactId ID of the NAB Contact */ private void processOrganization(ContactChange[] ccList, ContactChange[] idChangeList, long nabContactId) { final long organizationId = writeOrganization(ccList, nabContactId); if (organizationId != ContactChange.INVALID_ID) { if (mMarkedOrganizationIndex >= 0) { idChangeList[mMarkedOrganizationIndex + 1] = ContactChange.createIdsChange( ccList[mMarkedOrganizationIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChangeList[mMarkedOrganizationIndex + 1].setNabDetailId(organizationId); } if (mMarkedTitleIndex >= 0) { idChangeList[mMarkedTitleIndex + 1] = ContactChange.createIdsChange( ccList[mMarkedTitleIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); idChangeList[mMarkedTitleIndex + 1].setNabDetailId(organizationId); } } } /** * Write Organization detail to NAB * * @param ccList {@link ContactChange} list where Organization and Title are * found * @param nabContactId ID of the NAB Contact * @return ID of the NAB Contact */ private long writeOrganization(ContactChange[] ccList, long nabContactId) { mValues.clear(); int flags = ContactChange.FLAG_NONE; if (mMarkedOrganizationIndex >= 0) { final ContactChange cc = ccList[mMarkedOrganizationIndex]; final Organisation organization = VCardHelper.getOrg(cc.getValue()); if (!TextUtils.isEmpty(organization.name)) { mValues.put(Organizations.COMPANY, organization.name); flags |= cc.getFlags(); } } if (mMarkedTitleIndex >= 0) { final ContactChange cc = ccList[mMarkedTitleIndex]; // No need to check for empty values as there is only one flags |= cc.getFlags(); mValues.put(Organizations.TITLE, cc.getValue()); } if (mValues.size() > 0) { mValues.put(Organizations.PERSON_ID, nabContactId); mValues.put(Organizations.TYPE, mapToNabOrganizationType(flags)); final Uri uri = mCr.insert(Organizations.CONTENT_URI, mValues); if (uri != null) { return ContentUris.parseId(uri); } diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index 1bdb149..9fe0e9d 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,1274 +1,1299 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.accounts.AccountManager; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.OperationApplicationException; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; +import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.provider.ContactsContract; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.Settings; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Event; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.Website; import android.text.TextUtils; import android.util.SparseArray; import com.vodafone360.people.R; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.VCardHelper.Name; import com.vodafone360.people.datatypes.VCardHelper.Organisation; import com.vodafone360.people.datatypes.VCardHelper.PostalAddress; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * The implementation of the NativeContactsApi for the Android 2.X platform. */ public class NativeContactsApi2 extends NativeContactsApi { /** * Convenience Projection to fetch only a Raw Contact's ID and Native * Account Type */ private static final String[] CONTACTID_PROJECTION = new String[] { RawContacts._ID, RawContacts.ACCOUNT_TYPE }; /** * Raw ID Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_RAW_ID = 0; /** * Account Type Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_ACCOUNT_TYPE = 1; /** * Group ID Projection */ private static final String[] GROUPID_PROJECTION = new String[] { Groups._ID }; /** * Vendor specific account. Only used in 2.x API. */ private static Account sPhoneAccount = null; /** * Regular expression for a date that can be handled by the People Client at * present. Matches the following cases: N-n-n n-n-N Where: - 'n' * corresponds to one or two digits - 'N' corresponds to two or 4 digits */ private static final String COMPLETE_DATE_REGEX = "(?:^\\d{2,4}-\\d{1,2}-\\d{1,2}$|^\\d{1,2}-\\d{1,2}-\\d{2,4}$)"; /** * 'My Contacts' System group where clause */ private static final String MY_CONTACTS_GROUP_WHERE_CLAUSE = Groups.SYSTEM_ID + "=\"Contacts\""; /** * 'My Contacts' System Group Membership where in clause (Multiple 'My * Contacts' IDs) */ private static final String MY_CONTACTS_MULTI_GROUP_MEMBERSHIP = Data.MIMETYPE + "=\"" + GroupMembership.CONTENT_ITEM_TYPE + "\" AND " + Data.DATA1 + " IN ("; /** * Selection where clause for a NULL Account */ private static final String NULL_ACCOUNT_WHERE_CLAUSE = RawContacts.ACCOUNT_NAME + " IS NULL AND " + RawContacts.ACCOUNT_TYPE + " IS NULL"; /** * Selection where clause for an Organization detail. */ private static final String ORGANIZATION_DETAIL_WHERE_CLAUSE = RawContacts.Data.MIMETYPE + "=\"" + Organization.CONTENT_ITEM_TYPE + "\""; /** * The list of Uri that need to be listened to for contacts changes on * native side. */ private static final Uri[] sUri = { ContactsContract.RawContacts.CONTENT_URI, ContactsContract.Data.CONTENT_URI }; /** * Holds mapping from a NAB type (MIME) to a VCard Key */ private static final HashMap<String, Integer> sFromNabContentTypeToKeyMap; /** * Holds mapping from a VCard Key to a NAB type (MIME) */ private static final SparseArray<String> sFromKeyToNabContentTypeArray; static { sFromNabContentTypeToKeyMap = new HashMap<String, Integer>(9, 1); sFromNabContentTypeToKeyMap.put(StructuredName.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NAME); sFromNabContentTypeToKeyMap.put(Nickname.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NICKNAME); sFromNabContentTypeToKeyMap.put(Phone.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_PHONE); sFromNabContentTypeToKeyMap.put(Email.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_EMAIL); sFromNabContentTypeToKeyMap.put(StructuredPostal.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ADDRESS); sFromNabContentTypeToKeyMap .put(Organization.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ORG); sFromNabContentTypeToKeyMap.put(Website.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_URL); sFromNabContentTypeToKeyMap.put(Note.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NOTE); sFromNabContentTypeToKeyMap.put(Event.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_DATE); // sFromNabContentTypeToKeyMap.put( // Photo.CONTENT_ITEM_TYPE, ContactChange.KEY_PHOTO); sFromKeyToNabContentTypeArray = new SparseArray<String>(10); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NAME, StructuredName.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NICKNAME, Nickname.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_PHONE, Phone.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_EMAIL, Email.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ADDRESS, StructuredPostal.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ORG, Organization.CONTENT_ITEM_TYPE); // Special case: VCARD_TITLE maps to the same NAB type as sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_TITLE, Organization.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_URL, Website.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NOTE, Note.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_DATE, Event.CONTENT_ITEM_TYPE); // sFromKeyToNabContentTypeArray.append( // ContactChange.KEY_PHOTO, Photo.CONTENT_ITEM_TYPE); } /** * The observer registered by the upper layer. */ private ContactsObserver mAbstractedObserver; /** * Content values used for writing to NAB. */ private final ContentValues mValues = new ContentValues(); /** * The content observers that listens for native contacts changes. */ private final ContentObserver[] mContentObservers = new ContentObserver[sUri.length]; /** * Array of row ID in the groups table to the "My Contacts" System Group. * The reason for this being an array is because there may be multiple * "My Contacts" groups (Platform Bug!?). */ private long[] mMyContactsGroupRowIds = null; /** * Arguably another example where Organization and Title force us into extra * effort. We use this value to pass the correct detail ID when an 'add * detail' is done for one the two although the other is already present. * Make sure to reset this value for every UpdateContact operation */ private long mExistingOrganizationId = ContactChange.INVALID_ID; /** * Flag to check if we have already read a Birthday detail */ private boolean mHaveReadBirthday = false; /** * Yield value for our ContentProviderOperations. */ private boolean mYield = true; /** * Batch used for Contact Writing operations. */ private BatchOperation mBatch = new BatchOperation(); /** * Inner class for applying batches. TODO: Move to own class if batches * become supported in other areas */ private class BatchOperation { // List for storing the batch mOperations ArrayList<ContentProviderOperation> mOperations; /** * Default constructor */ public BatchOperation() { mOperations = new ArrayList<ContentProviderOperation>(); } /** * Current size of the batch * * @return Size of the batch */ public int size() { return mOperations.size(); } /** * Adds a new operation to the batch * * @param cpo The */ public void add(ContentProviderOperation cpo) { mOperations.add(cpo); } /** * Clears all operations in the batch Effectively resets the batch. */ public void clear() { mOperations.clear(); } public ContentProviderResult[] execute() { ContentProviderResult[] resultArray = null; if (mOperations.size() > 0) { // Apply the mOperations to the content provider try { resultArray = mCr.applyBatch(ContactsContract.AUTHORITY, mOperations); } catch (final OperationApplicationException e1) { LogUtils.logE("storing contact data failed", e1); } catch (final RemoteException e2) { LogUtils.logE("storing contact data failed", e2); } mOperations.clear(); } return resultArray; } } /** * Convenience interface to map the generic DATA column names to the People * profile detail column names. */ private interface PeopleProfileColumns { /** * 360 People profile MIME Type */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/com.vodafone360.people.profile"; /** * 360 People Contact's profile ID (Corresponds to Contact's Internal * Contact ID) */ public static final String DATA_PID = Data.DATA1; /** * 360 People Contact profile Summary */ public static final String DATA_SUMMARY = Data.DATA2; /** * 360 People Contact profile detail */ public static final String DATA_DETAIL = Data.DATA3; } /** * This class holds a native content observer that will be notified in case * of changes on the registered URI. */ private class NativeContentObserver extends ContentObserver { public NativeContentObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { LogUtils.logI("NativeContactsApi2.NativeContentObserver.onChange(" + selfChange + ")"); mAbstractedObserver.onChange(); } } /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { LogUtils.logI("NativeContactsApi2.registerObserver()"); if (mAbstractedObserver != null) { throw new RuntimeException( "Only one observer at a time supported... Please unregister first."); } mAbstractedObserver = observer; final ContentResolver cr = mContext.getContentResolver(); for (int i = 0; i < mContentObservers.length; i++) { mContentObservers[i] = new NativeContentObserver(); cr.registerContentObserver(sUri[i], true, mContentObservers[i]); } } /** * @see NativeContactsApi#unregisterObserver(ContactsObserver) */ @Override public void unregisterObserver() { LogUtils.logI("NativeContactsApi2.unregisterObserver()"); if (mCr != null) { mAbstractedObserver = null; for (int i = 0; i < mContentObservers.length; i++) { if (mContentObservers[i] != null) { mCr.unregisterContentObserver(mContentObservers[i]); mContentObservers[i] = null; } } } } /** * @see NativeContactsApi#initialize() */ @Override protected void initialize() { // perform here any one time initialization sPhoneAccount = getVendorSpecificAccount(); } /** * @see NativeContactsApi#getAccounts() */ @Override public Account[] getAccounts() { AccountManager accountManager = AccountManager.get(mContext); final android.accounts.Account[] accounts2xApi = accountManager.getAccounts(); Account[] accounts = null; if (accounts2xApi.length > 0) { accounts = new Account[accounts2xApi.length]; for (int i = 0; i < accounts2xApi.length; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } } return accounts; } /** * Reads vendor specific accounts from settings and through accountmanager. * Some phones with custom ui like sense have additional account that we * have to take care of. This method tryes to read them * * @return Account object if vendor specific account is found, null * otherwise */ public Account getVendorSpecificAccount() { // first read the settings String[] PROJECTION = { Settings.ACCOUNT_NAME, Settings.ACCOUNT_TYPE, Settings.UNGROUPED_VISIBLE }; // Get a cursor with all people Cursor cursor = mCr.query(Settings.CONTENT_URI, PROJECTION, null, null, null); // Got no cursor? Return with null! if (null == cursor) { return null; } try { String[] values = new String[cursor.getCount()]; for (int i = 0; i < values.length; i++) { cursor.moveToNext(); if (isVendorSpecificAccount(cursor.getString(1))) { return new Account(cursor.getString(0), cursor.getString(1)); } } } catch (Exception exc) { return null; } CursorUtils.closeCursor(cursor); // nothing found in the settings? try accountmanager Account[] accounts = getAccounts(); if (accounts == null) { return null; } for (Account account : accounts) { if (isVendorSpecificAccount(account.getType())) { return account; } } return null; } /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override public Account[] getAccountsByType(int type) { switch (type) { // people and google type lead to the same block the difference is // then handled inside in two if statements. // Otherwise we would have a lot of redundant code, case PEOPLE_ACCOUNT_TYPE: case GOOGLE_ACCOUNT_TYPE: { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts2xApi = null; // For people account set the people account type string... if (PEOPLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); } // .. and for google the same only with google string. if (GOOGLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(GOOGLE_ACCOUNT_TYPE_STRING); } final int numAccounts = accounts2xApi.length; if (numAccounts > 0) { Account[] accounts = new Account[numAccounts]; for (int i = 0; i < numAccounts; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } return accounts; } else { return null; } } case PHONE_ACCOUNT_TYPE: { if (sPhoneAccount == null) { return null; } return new Account[] { sPhoneAccount }; } default: return null; } } /** * @see NativeContactsApi#addPeopleAccount(String) */ @Override public boolean addPeopleAccount(String username) { boolean isAdded = false; try { android.accounts.Account account = new android.accounts.Account(username, PEOPLE_ACCOUNT_TYPE_STRING); AccountManager accountMan = AccountManager.get(mContext); isAdded = accountMan.addAccountExplicitly(account, null, null); if (isAdded) { if (VersionUtils.isHtcSenseDevice(mContext)) { createSettingsEntryForAccount(username); - } - // TODO: RE-ENABLE SYNC VIA SYSTEM - ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0); - // ContentResolver.setSyncAutomatically(account, - // ContactsContract.AUTHORITY, true); + } } } catch (Exception ex) { LogUtils.logE("People Account creation failed because of exception:\n", ex); } if (isAdded) { // Updating MyContacts Group IDs here for now because it needs to be // done one time just before first time sync. // In the future, this code may change if we modify // the way we retrieve contact IDs. fetchMyContactsGroupRowIds(); } return isAdded; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); return accounts != null && accounts.length > 0; } /** * @see NativeContactsApi#removePeopleAccount() */ @Override public void removePeopleAccount() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); if (accounts != null && accounts.length > 0) { accountMan.removeAccount(accounts[0], null, null); } } /** * @see NativeContactsApi#getContactIds(Account) */ @Override public long[] getContactIds(Account account) { // Need to construct a where clause if (account != null) { final StringBuffer clauseBuffer = new StringBuffer(); clauseBuffer.append(RawContacts.ACCOUNT_NAME); clauseBuffer.append("=\""); clauseBuffer.append(account.getName()); clauseBuffer.append("\" AND "); clauseBuffer.append(RawContacts.ACCOUNT_TYPE); clauseBuffer.append("=\""); clauseBuffer.append(account.getType()); clauseBuffer.append('\"'); return getContactIds(clauseBuffer.toString()); } else { return getContactIds(NULL_ACCOUNT_WHERE_CLAUSE); } } /** * @see NativeContactsApi#getContact(long) */ @Override public ContactChange[] getContact(long nabContactId) { // Reset the boolean flags mHaveReadOrganization = false; mHaveReadBirthday = false; final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, nabContactId); final Uri dataUri = Uri.withAppendedPath(rawContactUri, RawContacts.Data.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(dataUri, null, null, null, null); try { if (cursor != null && cursor.getCount() > 0) { final List<ContactChange> ccList = new ArrayList<ContactChange>(); while (cursor.moveToNext()) { readDetail(cursor, ccList, nabContactId); } return ccList.toArray(new ContactChange[ccList.size()]); } } finally { CursorUtils.closeCursor(cursor); } return null; } /** * @see NativeContactsApi#addContact(Account, ContactChange[]) */ @Override public ContactChange[] addContact(Account account, ContactChange[] ccList) { // Make sure to reset all the member variables we need mYield = true; mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mValues.clear(); mBatch.clear(); mValues.put(RawContacts.ACCOUNT_TYPE, account.getType()); mValues.put(RawContacts.ACCOUNT_NAME, account.getName()); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI)).withYieldAllowed(mYield) .withValues(mValues); mBatch.add(builder.build()); // according to the calling method ccList here has at least 1 element, ccList[0] is not null final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc != null) { final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } putDetail(cc); addValuesToBatch(ContactChange.INVALID_ID); } } // Special case for the organization/title if it was flagged in the // putDetail call putOrganization(ccList); addValuesToBatch(ContactChange.INVALID_ID); // Add 360 profile detail addProfileAction(ccList[0].getInternalContactId()); // Execute the batch and Generate ID changes from it return executeNewContactBatch(ccList); } /** * @see NativeContactsApi#updateContact(ContactChange[]) */ @Override public ContactChange[] updateContact(ContactChange[] ccList) { if (ccList == null || ccList.length == 0) { LogUtils.logW("NativeContactsApi2.updateContact() nothing to update - empty ccList!"); return null; } // Make sure to reset all the member variables we need mYield = true; mBatch.clear(); mValues.clear(); mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mExistingOrganizationId = ContactChange.INVALID_ID; final long nabContactId = ccList[0].getNabContactId(); if (nabContactId == ContactChange.INVALID_ID) { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update request because of invalid NAB Contact ID. Internal Contact ID is " + ccList[0].getInternalContactId()); return null; } final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } switch (cc.getType()) { case ContactChange.TYPE_ADD_DETAIL: putDetail(cc); addValuesToBatch(nabContactId); // not a new contact break; case ContactChange.TYPE_UPDATE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { putDetail(cc); addUpdateValuesToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update to detail for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; case ContactChange.TYPE_DELETE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { addDeleteDetailToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring detail deletion for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; default: break; } } updateOrganization(ccList, nabContactId); // Execute the batch and Generate ID changes from it return executeUpdateContactBatch(ccList); } /** * @see NativeContactsApi#removeContact(long) */ @Override public void removeContact(long nabContactId) { mCr.delete(addCallerIsSyncAdapterParameter(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId)), null, null); } + + /** + * @see NativeContactsApi#getMasterSyncAutomatically + */ + @Override + public boolean getMasterSyncAutomatically() { + // Always true in 1.X + return ContentResolver.getMasterSyncAutomatically(); + } + + /** + * @see NativeContactsApi#setSyncAutomatically(boolean) + */ + @Override + public void setSyncAutomatically(boolean syncAutomatically) { + android.accounts.Account[] accounts = + AccountManager.get(mContext).getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); + if(accounts != null && accounts.length > 0) { + ContentResolver.setSyncAutomatically(accounts[0], ContactsContract.AUTHORITY, syncAutomatically); + if(syncAutomatically) { + // Kick start sync + ContentResolver.requestSync(accounts[0], ContactsContract.AUTHORITY, new Bundle()); + } else { + // Cancel ongoing just in case + ContentResolver.cancelSync(accounts[0], ContactsContract.AUTHORITY); + } + } + } /** * @see NativeContactsApi#isKeySupported(int) */ @Override public boolean isKeySupported(int key) { // Only supported if in the SparseArray return sFromKeyToNabContentTypeArray.indexOfKey(key) >= 0; } /** * Inner (private) method for getting contact ids. Allows a cleaner * separation the public API method. * * @param selection The where clause for the operation * @return An array containing the Contact IDs that have been found */ private long[] getContactIds(final String selection) { // Store ids in a temporary array because of possible null values long[] tempIds = null; int idCount = 0; final Cursor cursor = mCr.query(RawContacts.CONTENT_URI, CONTACTID_PROJECTION, selection, null, null); if (cursor == null) { return null; } try { final int cursorCount = cursor.getCount(); if (cursorCount > 0) { tempIds = new long[cursorCount]; while (cursor.moveToNext()) { final long id = cursor.getLong(CONTACTID_PROJECTION_RAW_ID); final String accountType = cursor.getString(CONTACTID_PROJECTION_ACCOUNT_TYPE); // TODO: Remove hardcoding (if statement) if (TextUtils.isEmpty(accountType) || accountType.equals(NativeContactsApi.PEOPLE_ACCOUNT_TYPE_STRING) || isVendorSpecificAccount(accountType) || isContactInMyContactsGroup(id)) { tempIds[idCount] = id; idCount++; } } } } finally { CursorUtils.closeCursor(cursor); } if (idCount > 0) { // Here we copy the array to strip any eventual nulls at the end of // the tempIds array final long[] ids = new long[idCount]; System.arraycopy(tempIds, 0, ids, 0, idCount); return ids; } return null; } /** * Fetches the IDs corresponding to the "My Contacts" System Group The * reason why we return an array is because there may be multiple * "My Contacts" groups. * * @return Array containing all IDs of the "My Contacts" group or null if * none exist */ private void fetchMyContactsGroupRowIds() { final Cursor cursor = mCr.query(Groups.CONTENT_URI, GROUPID_PROJECTION, MY_CONTACTS_GROUP_WHERE_CLAUSE, null, null); if (cursor == null) { return; } try { final int count = cursor.getCount(); if (count > 0) { mMyContactsGroupRowIds = new long[count]; for (int i = 0; i < count; i++) { cursor.moveToNext(); mMyContactsGroupRowIds[i] = cursor.getLong(0); } } } finally { CursorUtils.closeCursor(cursor); } } /** * Checks if a Contact is in the "My Contacts" System Group * * @param nabContactId ID of the Contact to check * @return true if the Contact is in the Group, false if not */ private boolean isContactInMyContactsGroup(long nabContactId) { boolean belongs = false; if (mMyContactsGroupRowIds != null) { final Uri dataUri = Uri.withAppendedPath(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId), RawContacts.Data.CONTENT_DIRECTORY); // build query containing row ID values final StringBuilder sb = new StringBuilder(); sb.append(MY_CONTACTS_MULTI_GROUP_MEMBERSHIP); final int rowIdCount = mMyContactsGroupRowIds.length; for (int i = 0; i < rowIdCount; i++) { sb.append(mMyContactsGroupRowIds[i]); if (i < rowIdCount - 1) { sb.append(','); } } sb.append(')'); final Cursor cursor = mCr.query(dataUri, null, sb.toString(), null, null); try { belongs = cursor != null && cursor.getCount() > 0; } finally { CursorUtils.closeCursor(cursor); } } return belongs; } /** * Reads a Contact Detail from a Cursor into the supplied Contact Change * List. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to read Detail into * @param nabContactId NAB ID of the Contact */ private void readDetail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String mimetype = CursorUtils.getString(cursor, Data.MIMETYPE); final Integer key = sFromNabContentTypeToKeyMap.get(mimetype); if (key != null) { switch (key.intValue()) { case ContactChange.KEY_VCARD_NAME: readName(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_NICKNAME: readNickname(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_PHONE: readPhone(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_EMAIL: readEmail(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ADDRESS: readAddress(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ORG: // Only one Organization can be read (CAB limitation!) if (!mHaveReadOrganization) { readOrganization(cursor, ccList, nabContactId); } break; case ContactChange.KEY_VCARD_URL: readWebsite(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_DATE: if (!mHaveReadBirthday) { readBirthday(cursor, ccList, nabContactId); } break; default: // The default case is also a valid key final String value = CursorUtils.getString(cursor, Data.DATA1); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Data._ID); final ContactChange cc = new ContactChange(key, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } break; } } } /** * Reads an name detail as a {@link ContactChange} from the provided cursor. * For this type of detail we need to use a VCARD (semicolon separated) * value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readName(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using display name only to check if there is a valid name to read final String displayName = CursorUtils.getString(cursor, StructuredName.DISPLAY_NAME); if (!TextUtils.isEmpty(displayName)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredName._ID); // VCard Helper data type (CAB) final Name name = new Name(); // NAB: Given name -> CAB: First name name.firstname = CursorUtils.getString(cursor, StructuredName.GIVEN_NAME); // NAB: Family name -> CAB: Surname name.surname = CursorUtils.getString(cursor, StructuredName.FAMILY_NAME); // NAB: Prefix -> CAB: Title name.title = CursorUtils.getString(cursor, StructuredName.PREFIX); // NAB: Middle name -> CAB: Middle name name.midname = CursorUtils.getString(cursor, StructuredName.MIDDLE_NAME); // NAB: Suffix -> CAB: Suffixes name.suffixes = CursorUtils.getString(cursor, StructuredName.SUFFIX); // NOTE: Ignoring Phonetics (DATA7, DATA8 and DATA9)! // TODO: Need to get middle name and concatenate into value final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NAME, VCardHelper .makeName(name), ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an nickname detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readNickname(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Nickname.NAME); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Nickname._ID); /* * TODO: Decide what to do with nickname: Can only have one in VF360 * but NAB Allows more than one! */ final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NICKNAME, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an phone detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readPhone(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Phone.NUMBER); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Phone._ID); final int type = CursorUtils.getInt(cursor, Phone.TYPE); int flags = mapFromNabPhoneType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Phone.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // assuming raw value is good enough for us final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_PHONE, value, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an email detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readEmail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Email.DATA); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Email._ID); final int type = CursorUtils.getInt(cursor, Email.TYPE); int flags = mapFromNabEmailType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Email.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // assuming raw value is good enough for us final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_EMAIL, value, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an address detail as a {@link ContactChange} from the provided * cursor. For this type of detail we need to use a VCARD (semicolon * separated) value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readAddress(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using formatted address only to check if there is a valid address to // read final String formattedAddress = CursorUtils.getString(cursor, StructuredPostal.FORMATTED_ADDRESS); if (!TextUtils.isEmpty(formattedAddress)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredPostal._ID); final int type = CursorUtils.getInt(cursor, StructuredPostal.TYPE); int flags = mapFromNabAddressType(type); final boolean isPrimary = CursorUtils.getInt(cursor, StructuredPostal.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // VCard Helper data type (CAB) final PostalAddress address = new PostalAddress(); // NAB: Street -> CAB: AddressLine1 address.addressLine1 = CursorUtils.getString(cursor, StructuredPostal.STREET); // NAB: PO Box -> CAB: postOfficeBox address.postOfficeBox = CursorUtils.getString(cursor, StructuredPostal.POBOX); // NAB: Neighborhood -> CAB: AddressLine2 address.addressLine2 = CursorUtils.getString(cursor, StructuredPostal.NEIGHBORHOOD); // NAB: City -> CAB: City address.city = CursorUtils.getString(cursor, StructuredPostal.CITY); // NAB: Region -> CAB: County address.county = CursorUtils.getString(cursor, StructuredPostal.REGION); // NAB: Post code -> CAB: Post code address.postCode = CursorUtils.getString(cursor, StructuredPostal.POSTCODE); // NAB: Country -> CAB: Country address.country = CursorUtils.getString(cursor, StructuredPostal.COUNTRY); final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_ADDRESS, VCardHelper .makePostalAddress(address), flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an organization detail as a {@link ContactChange} from the provided * cursor. For this type of detail we need to use a VCARD (semicolon * separated) value. In reality two different changes may be read if a title * is also present. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readOrganization(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final int type = CursorUtils.getInt(cursor, Organization.TYPE); int flags = mapFromNabOrganizationType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Organization.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } final long nabDetailId = CursorUtils.getLong(cursor, Organization._ID); if (!mHaveReadOrganization) { // VCard Helper data type (CAB) final Organisation organization = new Organisation(); // Company organization.name = CursorUtils.getString(cursor, Organization.COMPANY); // Department final String department = CursorUtils.getString(cursor, Organization.DEPARTMENT); if (!TextUtils.isEmpty(department)) { organization.unitNames.add(department); } if ((organization.unitNames != null && organization.unitNames.size() > 0) || !TextUtils.isEmpty(organization.name)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_ORG, VCardHelper .makeOrg(organization), flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } // Title final String title = CursorUtils.getString(cursor, Organization.TITLE); if (!TextUtils.isEmpty(title)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_TITLE, title, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } } } /** * Reads an Website detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readWebsite(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String url = CursorUtils.getString(cursor, Website.URL); if (!TextUtils.isEmpty(url)) { final long nabDetailId = CursorUtils.getLong(cursor, Website._ID); final int type = CursorUtils.getInt(cursor, Website.TYPE); int flags = mapFromNabWebsiteType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Website.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_URL, url, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an Birthday detail as a {@link ContactChange} from the provided * cursor. Note that since the Android Type is the Generic "Event", it may * be the case that nothing is read if this is not actually a Birthday * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ public void readBirthday(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final int type = CursorUtils.getInt(cursor, Event.TYPE); if (type == Event.TYPE_BIRTHDAY) { final String date = CursorUtils.getString(cursor, Event.START_DATE); // Ignoring birthdays without year, day and month! // FIXME: Remove this check when/if the backend becomes able to // handle incomplete birthdays if (date != null && date.matches(COMPLETE_DATE_REGEX)) { final long nabDetailId = CursorUtils.getLong(cursor, Event._ID); final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_DATE, date, ContactChange.FLAG_BIRTHDAY); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadBirthday = true; } } } /** * Adds current values to the batch. * * @param nabContactId The existing NAB Contact ID if it is an update or an * invalid id if a new contact */ private void addValuesToBatch(long nabContactId) { // Add to batch if (mValues.size() > 0) { final boolean isNewContact = nabContactId == ContactChange.INVALID_ID; if (!isNewContact) { // Updating a Contact, need to add the ID to the Values mValues.put(Data.RAW_CONTACT_ID, nabContactId); } ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( addCallerIsSyncAdapterParameter(Data.CONTENT_URI)).withYieldAllowed(mYield) .withValues(mValues); if (isNewContact) { // New Contact needs Back Reference builder.withValueBackReference(Data.RAW_CONTACT_ID, 0); } mYield = false; mBatch.add(builder.build()); } } /** * Adds current update values to the batch. * * @param nabDetailId The NAB ID of the detail to update */ private void addUpdateValuesToBatch(long nabDetailId) { if (mValues.size() > 0) { final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, nabDetailId); ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate( addCallerIsSyncAdapterParameter(uri)).withYieldAllowed(mYield).withValues( mValues); mYield = false; mBatch.add(builder.build()); } } /** * Adds a delete detail operation to the batch. diff --git a/src/com/vodafone360/people/service/NativeAccountObjectsHolder.java b/src/com/vodafone360/people/service/NativeAccountObjectsHolder.java index c4a9578..088f6ce 100644 --- a/src/com/vodafone360/people/service/NativeAccountObjectsHolder.java +++ b/src/com/vodafone360/people/service/NativeAccountObjectsHolder.java @@ -1,70 +1,70 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import android.content.Context; import android.os.IBinder; import com.vodafone360.people.MainApplication; /** * Small class created solely for holding * the Authenticator and Sync Adapter objects required * for the ability to have a 360 People Account on Native side. * We hold the objects this way to make it so that the code also loads on 1.X devices. */ public class NativeAccountObjectsHolder { /** * "Hidden" Authenticator object */ private static Object sAuthenticator; /** * "Hidden" Sync Adapter object */ private static Object sSyncAdapter; public NativeAccountObjectsHolder(MainApplication application) { Context context = application.getApplicationContext(); sAuthenticator = new Authenticator(context, application); - sSyncAdapter = new SyncAdapter(context, true); + sSyncAdapter = new SyncAdapter(context, application); } /** * Shortcut method to get the Binder Interface from the Authenticator object. * @return IBinder object for the Authenticator */ public IBinder getAuthenticatorBinder() { return ((Authenticator) sAuthenticator).getIBinder(); } /** * Shortcut method to get the Binder Interface from the Sync Adapter object. * @return IBinder object for the Sync Adapter */ public IBinder getSyncAdapterBinder() { return ((SyncAdapter)sSyncAdapter).getSyncAdapterBinder(); } } diff --git a/src/com/vodafone360/people/service/SyncAdapter.java b/src/com/vodafone360/people/service/SyncAdapter.java index 03924e9..9464ed9 100644 --- a/src/com/vodafone360/people/service/SyncAdapter.java +++ b/src/com/vodafone360/people/service/SyncAdapter.java @@ -1,133 +1,257 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service; import android.accounts.Account; +import android.accounts.AccountManager; import android.content.AbstractThreadedSyncAdapter; +import android.content.BroadcastReceiver; import android.content.ContentProviderClient; +import android.content.ContentResolver; import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; import android.content.SyncResult; +import android.content.SyncStatusObserver; import android.os.Bundle; +import android.os.Handler; +import android.provider.ContactsContract; +import com.vodafone360.people.MainApplication; +import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; +import com.vodafone360.people.service.PersistSettings.InternetAvail; /** * SyncAdapter implementation which basically just ties in with * the old Contacts Sync Engine code for the moment and waits for the sync to be finished. * In the future we may want to improve this, particularly if the sync * is actually be done in this thread which would also enable disable sync altogether. */ public class SyncAdapter extends AbstractThreadedSyncAdapter implements IContactSyncObserver { // TODO: RE-ENABLE SYNC VIA SYSTEM // /** // * Direct access to Sync Engine stored for convenience // */ // private final ContactSyncEngine mSyncEngine = EngineManager.getInstance().getContactSyncEngine(); // // /** // * Boolean used to remember if we have requested a sync. // * Useful to ignore events // */ // private boolean mPerformSyncRequested = false; // -// /** -// * Time to suspend the thread between pools to the Sync Engine. -// */ -// -// private final int POOLING_WAIT_INTERVAL = 1000; - public SyncAdapter(Context context, boolean autoInitialize) { - super(context, autoInitialize); + /** + * Delay when checking our Sync Setting when we a global setting change. + * This waiting time is necessary because in case it is our sync adapter authority setting + * that changes we cannot query in the callback because the value is not yet changed! + */ + private static final int SYNC_SETTING_CHECK_DELAY = 500; + + /** + * Application object instance + */ + private final MainApplication mApplication; + + /** + * Broadcast receiver used to listen for changes in the Master Auto Sync setting + * intent: com.android.sync.SYNC_CONN_STATUS_CHANGED + */ + private final BroadcastReceiver mAutoSyncChangeBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + setConnectionSettingForAutoSyncSetting(); + } + }; + + /** + * Observer for the global sync status setting. + * There is no known way to only observer our sync adapter's setting. + */ + private final SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() { + @Override + public void onStatusChanged(int which) { + mHandler.postDelayed(mRunnable, SYNC_SETTING_CHECK_DELAY); + } + }; + + /** + * Handler used to post to a runnable in order to wait + * for a short time before checking the sync adapter + * authority sync setting after a global change occurs. + */ + private final Handler mHandler = new Handler(); + + /** + * Cached Account we use to query this Sync Adapter instance's Auto-sync setting. + */ + private Account mAccount; + + /** + * Runnable used to post to a runnable in order to wait + * for a short time before checking the sync adapter + * authority sync setting after a global change occurs. + * The reason we use this kind of mechanism is because: + * a) There is an intent(com.android.sync.SYNC_CONN_STATUS_CHANGED) + * we can listen to for the Master Auto-sync but, + * b) The authority auto-sync observer pattern using ContentResolver + * listens to EVERY sync adapter setting on the device AND + * when the callback is received the value is not yet changed so querying for it is useless. + */ + private final Runnable mRunnable = new Runnable() { + @Override + public void run() { + setConnectionSettingForAutoSyncSetting(); + } + }; + + public SyncAdapter(Context context, MainApplication application) { + // No automatic initialization (false) + super(context, false); + mApplication = application; + context.registerReceiver(mAutoSyncChangeBroadcastReceiver, new IntentFilter( + "com.android.sync.SYNC_CONN_STATUS_CHANGED")); + ContentResolver.addStatusChangeListener( + ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver); // Register for sync event callbacks - // TODO: RE-ENABLE SYNC VIA SYSTEM -// mSyncEngine.addEventCallback(this); + // TODO: RE-ENABLE SYNC VIA SYSTEM + // mSyncEngine.addEventCallback(this); } /** * {@inheritDoc} */ @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { + if(extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false)) { + initializeSyncAdapter(account, authority); + return; + } + + setConnectionSettingForAutoSyncSetting(); + // TODO: RE-ENABLE SYNC VIA SYSTEM // try { // synchronized(this) { // mPerformSyncRequested = true; // if(!mSyncEngine.isSyncing()) { // mSyncEngine.startFullSync(); // } // // while(mSyncEngine.isSyncing()) { // wait(POOLING_WAIT_INTERVAL); // } // mPerformSyncRequested = false; // } // } catch (InterruptedException e) { // e.printStackTrace(); // } } + + /** * @see IContactSyncObserver#onContactSyncStateChange(Mode, State, State) */ @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { // TODO: RE-ENABLE SYNC VIA SYSTEM // synchronized(this) { // /* // * This check is done so that we can also update the native UI // * when the client devices to sync on it own // */ // if(!mPerformSyncRequested && // mode != Mode.NONE) { // mPerformSyncRequested = true; // Account account = new Account( // LoginPreferences.getUsername(), // NativeContactsApi2.PEOPLE_ACCOUNT_TYPE); // ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); // } // } } /** * @see IContactSyncObserver#onProgressEvent(State, int) */ @Override public void onProgressEvent(State currentState, int percent) { // Nothing to do } /** * @see IContactSyncObserver#onSyncComplete(ServiceStatus) */ @Override public void onSyncComplete(ServiceStatus status) { // Nothing to do } + + /** + * Initializes Sync settings for this Sync Adapter + * @param account The account associated with the initialization + * @param authority The authority of the content + */ + private void initializeSyncAdapter(Account account, String authority) { + mAccount = account; // caching + ContentResolver.setIsSyncable(account, authority, 1); + ContentResolver.setSyncAutomatically(account, authority, true); + } + + /** + * Checks if this Sync Adapter is allowed to Sync Automatically + * Basically just checking if the Master and its own Auto-sync are on. + * The Master Auto-sync takes precedence over the authority Auto-sync. + * @return true if the settings are enabled, false otherwise + */ + private boolean canSyncAutomatically() { + if(!ContentResolver.getMasterSyncAutomatically()) { + return false; + } + return ContentResolver.getSyncAutomatically(mAccount, ContactsContract.AUTHORITY); + } + + /** + * Sets the application data connection setting depending on the Auto-Sync Setting. + * If Auto-sync is enabled then connection is to online ("always connect") + * Otherwise connection is set to offline ("manual connect") + */ + private synchronized void setConnectionSettingForAutoSyncSetting() { + if(canSyncAutomatically()) { + // Enable data connection + mApplication.setInternetAvail(InternetAvail.ALWAYS_CONNECT); + } else { + // Disable data connection + mApplication.setInternetAvail(InternetAvail.MANUAL_CONNECT); + } + } }
360/360-Engine-for-Android
c4933a89e4a2eaf251a4918fbd6dc52951d93b17
PAND-1681 initial commit for evaluation
diff --git a/src/com/vodafone360/people/ApplicationCache.java b/src/com/vodafone360/people/ApplicationCache.java index 8685f9a..f956a51 100644 --- a/src/com/vodafone360/people/ApplicationCache.java +++ b/src/com/vodafone360/people/ApplicationCache.java @@ -1,666 +1,683 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import java.security.InvalidParameterException; import java.util.ArrayList; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import com.vodafone360.people.R; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.engine.contactsync.SyncStatus; import com.vodafone360.people.service.ServiceStatus; +import com.vodafone360.people.ui.contacts.MyProfileCache; import com.vodafone360.people.utils.ThirdPartyAccount; import com.vodafone360.people.utils.LoginPreferences; import com.vodafone360.people.utils.LogUtils; /** * Caches information about the current state of the application. Stores most * recent activity and caches other information such as login details, so that * the application is returned to its most recent state when brought back to the * foreground or re-entered. The cached details can be cleared if required (as * part of 'Remove user data' for example). */ public class ApplicationCache { /** Text key for Terms of Service content. **/ private final static String TERMS_OF_SERVICE = "TERMS_OF_SERVICE"; /** Text key for Terms of Service last updated time. **/ private final static String TERMS_OF_SERVICE_TIME = "TERMS_OF_SERVICE_TIME"; /** Text key for Privacy content. **/ private final static String PRIVACY = "PRIVACY"; /** Text key for Privacy last updated time. **/ private final static String PRIVACY_TIME = "PRIVACY_TIME"; /** * Refresh any cached terms of service or privacy content after 10 minutes. */ private final static long REFRESH_TIME = 10 * 60 * 1000; private static final String TRUE = "true"; private static final String FALSE = "false"; /** * Login details are stored in the preferences file so that they can be used * to pre-populate the edit fields if the user is interrupted in the middle * of login/signup */ public static final String PREFS_FILE = "NOW_PLUS"; public static final String CONTACT_DATA = "ContactData"; public static final String CONTACT_SUMMARY = "ContactSummary"; public static final String CONTACT_ID = "CONTACTID"; public static final String CONTACT_NAME = "CONTACTNAME"; public static final String CONTACT_NUMBER = "CONTACTNUMBER"; public static final String CONTACT_NETWORK = "CONTACTNETWORK"; public static final String CONTACT_MODIFIED = "ContactModified"; public static final String STARTUP_LAUNCH_PATH_KEY = "LAUNCHED_FROM"; public static final int RESULT_DELETE = -100; public static final int CONTACT_PROFILE_VIEW = 0; public static final int CONTACT_PROFILE_EDIT = 1; public static final int CONTACT_PROFILE_ADD = 2; public static final int CONTACT_PROFILE_VIEW_ME = 3; public static final String THIRD_PARTY_ACCOUNT_NAME_KEY = "ThirdPartyAccountName"; public static final String THIRD_PARTY_ACCOUNT_NETWORK_KEY = "ThirdPartyNetworkName"; public static final String THIRD_PARTY_ACCOUNT_USERNAME_KEY = "ThirdPartyAccountUsername"; public static final String THIRD_PARTY_ACCOUNT_PASSWORD_KEY = "ThirdPartyAccountPassword"; public static final String THIRD_PARTY_ACCOUNT_CAPABILITIES = "ThirdPartyAccountCapabilities"; public static final String THIRD_PARTY_ACCOUNT_ERROR_CODE = "ThirdPartyAccountErrorCode"; private final static String FACEBOOK_SUBSCRIBED = "FacebookSubscribed"; private final static String HYVES_SUBSCRIBED = "HyvesSubscribed"; public final static String PREFS_NAME = "NowPlus_Prefs"; // Check settings public final static String PREFS_CHECK_FREQUENCY = "checkFrequency"; // Upgrade version - these values are deleted when the latest version is not // new public final static String PREFS_LAST_DIALOG_DATE = "lastDialogDate"; public final static String PREFS_LAST_CHECKED_DATE = "lastCheckedDate"; public final static String PREFS_UPGRADE_LATEST_VERSION = "upgradeLatestVersion"; public final static String PREFS_UPGRADE_URL = "upgradeUrl"; public final static String PREFS_UPGRADE_TEXT = "upgradeText"; public static String sWidgetProviderClassName = null; public static String sIsNewMessage = "isNewMessage"; // Frequency setting descriptions and defaults public final static long[] FREQUENCY_SETTING_LONG = { -1, // Off 7 * 24 * 60 * 60 * 1000, // Weekly 24 * 60 * 60 * 1000, // Daily 6 * 60 * 60 * 1000, // Every 6 hours 1 * 60 * 60 * 1000, // Hourly 10 * 60 * 1000 // Every 10 minutes }; /** In memory cache of the current contacts sync status. **/ private SyncStatus mSyncStatus = null; // Cached login flags private boolean mFirstTimeLogin = true; private boolean mScanThirdPartyAccounts = true; private boolean mAcceptedTermsAndConditions = false; private int mIdentityBeingProcessed = -1; private ArrayList<ThirdPartyAccount> mThirdPartyAccountsCache; private ContactSummary mMeProfileSummary; private Contact mCurrentContact; private ContactSummary mCurrentContactSummary; private ServiceStatus mServiceStatus = ServiceStatus.ERROR_UNKNOWN; private TimelineSummaryItem mCurrentTimelineSummary; private long mCurrentContactFilter; /** Cached whether ThirdPartyAccountsActivity is opened. */ private boolean mIsAddAccountActivityOpened; + + /** + * The My profile checkboxes states cache. + */ + private static MyProfileCache sMyProfileCache; /*** * GETTER Whether "add Account" activity is opened * * @return True if "add Account" activity is opened */ public boolean addAccountActivityOpened() { return mIsAddAccountActivityOpened; } /*** * SETTER Whether "add Account" activity is opened. * * @param flag if "add Account" activity is opened */ public void setAddAccountActivityOpened(final boolean flag) { mIsAddAccountActivityOpened = flag; } /** * Whether this is a first time login (on this device) for current account. * * @return True if this is the first login for current account. */ public boolean firstTimeLogin() { return mFirstTimeLogin; } /** * Set whether this is a first time login (on this device) for current * account. If we have not logged in on this device (or after 'Remove user * data') we will need to perform the first time 'full' time contact sync. * * @param aState True if this is our 1st time sync. */ public void setFirstTimeLogin(boolean state) { mFirstTimeLogin = state; } /** * Set whether application should re-scan 3rd party accounts. * * @param state true if application should re-scan 3rd party accounts. */ public void setScanThirdPartyAccounts(boolean state) { mScanThirdPartyAccounts = state; } /** * Return whether application should re-scan 3rd party accounts. * * @return true if application should re-scan 3rd party accounts. */ public boolean getScanThirdPartyAccounts() { return mScanThirdPartyAccounts; } /** * Set index of Identity currently being processed. * * @param index Index of Identity currently being processed. */ public void setIdentityBeingProcessed(int index) { mIdentityBeingProcessed = index; } /** * Return index of the Identity currently being processed. * * @return index of the Identity currently being processed. */ public int getIdentityBeingProcessed() { return mIdentityBeingProcessed; } /** * Set whether user has accepted the Terms and Conditions on sign-up. * * @param state true if user has accepted terms and conditions. */ public void setAcceptedTermsAndConditions(boolean state) { mAcceptedTermsAndConditions = state; } /** * Return whether user has accepted the Terms and Conditions on sign-up. * * @return true if user has accepted terms and conditions. */ public boolean getAcceptedTermsAndConditions() { return mAcceptedTermsAndConditions; } /** * Clear all cached data currently stored in People application. */ protected void clearCachedData(Context context) { LoginPreferences.clearPreferencesFile(context); LoginPreferences.clearCachedLoginDetails(); mFirstTimeLogin = true; mScanThirdPartyAccounts = true; mIdentityBeingProcessed = -1; mAcceptedTermsAndConditions = false; mMeProfileSummary = null; mCurrentContact = null; mCurrentContactSummary = null; mServiceStatus = ServiceStatus.ERROR_UNKNOWN; mThirdPartyAccountsCache = null; mSyncStatus = null; mIsAddAccountActivityOpened = false; } /** * Gets the ME profile object. * * @return The ME profile object. */ public ContactSummary getMeProfile() { return mMeProfileSummary; } /** * Sets the ME profile object. * * @param summary ContyactSummary for Me profile. */ public void setMeProfile(ContactSummary summary) { mMeProfileSummary = summary; } /** * Gets the contact currently being viewed in the UI. * * @return The currently view contact. */ public Contact getCurrentContact() { return mCurrentContact; } /** * Sets the contact currently being viewed in the UI. * * @param contact The currently viewed contact. */ public void setCurrentContact(Contact contact) { mCurrentContact = contact; } /** * Gets the summary information of the contact currently being viewed in the * UI. * * @return Contact summary information. */ public ContactSummary getCurrentContactSummary() { return mCurrentContactSummary; } /** * Sets the summary information of the contact currently being viewed in the * UI. * * @param contactSummary Contact summary information. */ public void setCurrentContactSummary(ContactSummary contactSummary) { mCurrentContactSummary = contactSummary; } /** * Return status of request issued to People service. * * @return status of request issued to People service. */ public ServiceStatus getServiceStatus() { return mServiceStatus; } /** * Set status of request issued to People service. * * @param status of request issued to People service. */ public void setServiceStatus(ServiceStatus status) { mServiceStatus = status; } /** * Cache list of 3rd party accounts (Identities) associated with current * login. * * @param list List of ThirdPartyAccount items retrieved from current login. */ public void storeThirdPartyAccounts(Context context, ArrayList<ThirdPartyAccount> list) { setValue(context, FACEBOOK_SUBSCRIBED, isFacebookInThirdPartyAccountList(list) + ""); setValue(context, HYVES_SUBSCRIBED, isHyvesInThirdPartyAccountList(list) + ""); mThirdPartyAccountsCache = list; } /** * Return cached list of 3rd party accounts (Identities) associated with * current login. * * @return List of ThirdPartyAccount items retrieved from current login. */ public ArrayList<ThirdPartyAccount> getThirdPartyAccounts() { return mThirdPartyAccountsCache; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Facebook account. */ private static boolean isFacebookInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("facebook")) { if (thirdPartyAccount.isChecked()) { LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook is checked"); return true; } else { LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook is unchecked"); return false; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given ThirdPartyAccount contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Hyves account. */ private static boolean isHyvesInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("hyves")) { if (thirdPartyAccount.isChecked()) { LogUtils .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is checked"); return true; } else { LogUtils .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is unchecked"); return false; } } } } LogUtils.logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves not found in list"); return false; } /** * Get list of IDs of Home-screen widgets. * * @param context Current context. * @return list of IDs of Home-screen widgets. */ public int[] getWidgetIdList(Context context) { if(sWidgetProviderClassName != null) { return AppWidgetManager.getInstance(context).getAppWidgetIds( new ComponentName(context, sWidgetProviderClassName)); } return null; } /*** * Set a value in the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param value Preference value. */ private static void setValue(Context context, String key, String value) { SharedPreferences.Editor editor = context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(key, value); if (!editor.commit()) { throw new NullPointerException("MainApplication.setValue() Failed to set key[" + key + "] with value[" + value + "]"); } LogUtils.logV("ApplicationCache.setValue() key [" + key + "] value [" + value + "] saved to properties file"); } /*** * Gets the current sync state, or NULL if the state has not been set in * this JVM instance. * * @return SyncStatus or NULL. */ public SyncStatus getSyncStatus() { return mSyncStatus; } /*** * Sets the current sync status. * * @param syncStatus New sync status. */ public void setSyncStatus(SyncStatus syncStatus) { mSyncStatus = syncStatus; } /*** * Get a value from the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param defaultValue Preference value. * @return */ private static String getValue(Context context, String key, String defaultValue) { return context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).getString(key, defaultValue); } /*** * Return the resource ID for the SNS Subscribed warning (e.g. * facebook/hyves/etc posting), or -1 if no warning is necessary. * * @param context Android context. * @return Resource ID for textView or -1 is warning is not required. * @throws InvalidParameterException when context is NULL. */ public static int getSnsSubscribedWarningId(Context context) { if (context == null) { throw new InvalidParameterException("ApplicationCache.getSnsSubscribedWarningId() " + "context cannot be NULL"); } boolean facebook = getValue(context, FACEBOOK_SUBSCRIBED, "").equals("true"); boolean hyves = getValue(context, HYVES_SUBSCRIBED, "").equals("true"); if (facebook && hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves_and_facebook; } else if (facebook) { return R.string.ContactStatusListActivity_update_status_on_facebook; } else if (hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves; } else { return -1; } } public static boolean isBooleanValue(Context context, String key) { return TRUE.equals(getValue(context, key, FALSE)); } public static void setBooleanValue(Context context, String key, boolean value) { setValue(context, key, value ? TRUE : FALSE); } /** * Gets the summary information of the Timeline currently being viewed in the * UI. * * @return Timeline summary information. */ public TimelineSummaryItem getCurrentTimelineSummary() { return mCurrentTimelineSummary; } /** * Sets the summary information of the Timeline Item currently being viewed in the * UI. * * @param timelineSummary Timeline summary information. */ public void setCurrentTimelineSummary(TimelineSummaryItem timelineSummary) { mCurrentTimelineSummary = timelineSummary; } /*** * Set the Terms of Service content into the cache. * * @param value Terms of Service content. * @param context Android context. */ public static void setTermsOfService(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(TERMS_OF_SERVICE, value); editor.putLong(TERMS_OF_SERVICE_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setTermsOfService() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Set the Privacy content into the cache. * * @param value Privacy content. * @param context Android context. */ public static void setPrivacyStatemet(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(PRIVACY, value); editor.putLong(PRIVACY_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setPrivacyStatemet() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Get the Terms of Service content from the cache. Will return NULL if * there is no content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Terms of Service content */ public static String getTermsOfService(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(TERMS_OF_SERVICE_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME) { return null; } else { return sharedPreferences.getString(TERMS_OF_SERVICE, null); } } /*** * Get the Privacy content from the cache. Will return NULL if there is no * content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Privacy content */ public static String getPrivacyStatement(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(PRIVACY_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME) { return null; } else { return sharedPreferences.getString(PRIVACY, null); } } private static ServiceStatus sStatus = ServiceStatus.SUCCESS; public static void setTermsStatus(final ServiceStatus status) { sStatus = status; } public static ServiceStatus getTermsStatus() { return sStatus; } /** * @param currentContactFilter the mCurrentContactFilter to set */ public final void setCurrentContactFilter(final long currentContactFilter) { mCurrentContactFilter = currentContactFilter; } /** * @return the mCurrentContactFilter */ public final long getCurrentContactFilter() { return mCurrentContactFilter; } + + public static MyProfileCache getMyProfileUiCache() { + if (sMyProfileCache == null) { + sMyProfileCache = new MyProfileCache(); + } + return sMyProfileCache; + } + + public static void setMyProfileUiCache(MyProfileCache cache) { + sMyProfileCache = cache; + } } diff --git a/src/com/vodafone360/people/Settings.java b/src/com/vodafone360/people/Settings.java index ecd66d0..c33a9ce 100644 --- a/src/com/vodafone360/people/Settings.java +++ b/src/com/vodafone360/people/Settings.java @@ -1,296 +1,296 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; /** * All application settings. */ public final class Settings { /* * LogCat. */ /** LogCat TAG prefix. **/ public static final String LOG_TAG = "People_"; /* * Transport. */ /** Milliseconds until HTTP connection will time out. */ public static final int HTTP_CONNECTION_TIMEOUT = 30000; /** Maximum number of HTTP connection attempts. */ public static final int HTTP_MAX_RETRY_COUNT = 3; /** HTTP header content type. */ public static final String HTTP_HEADER_CONTENT_TYPE = "application/binary"; /** Number of empty RPG poll responses before stopping RPG poll. */ public static final int BLANK_RPG_HEADER_COUNT = 4; /** TCP Heartbeat interval (10 seconds). */ public static final long TCP_VF_HEARTBEAT_INTERVAL = 10 * 60 * 1000; /** TCP retry interval if we have lost the connection (30 seconds). */ public static final long TCP_RETRY_BROKEN_CONNECTION_INTERVAL = 30 * 60 * 1000; /** TCP socket read time out for the read-operation. */ public static final int TCP_SOCKET_READ_TIMEOUT = 10 * 60 * 1000; /* * Notifications. */ /** LED colour. */ public static final int NOTIFICATION_LED_COLOR = 0xff00ff00; // Green /** LED on time. */ public static final int NOTIFICATION_LED_OFF_TIME = 300; /** LED on time. */ public static final int NOTIFICATION_LED_ON_TIME = 1000; /* * Upgrade Engine */ /** * See UpdateSettingsActivity.FREQUENCY_SETTING_LONG array for meaning (i.e. * Every 6 hours) */ public static final int PREFS_CHECK_FREQUENCY_DEFAULT = 3; /** Show the upgrade dialog box every 10 minutes. */ public static final int DIALOG_CHECK_FREQUENCY_MILLIS = 10 * 60 * 1000; /** * Component trace flags (always checked in as false, not part of build * script). */ /** Trace output for engine components. **/ public static final boolean ENABLED_ENGINE_TRACE = false; /** Trace output for database components. **/ public static final boolean ENABLED_DATABASE_TRACE = false; /** Trace output for transport (i.e. network IO) components. **/ - public static final boolean ENABLED_TRANSPORT_TRACE = false; + public static final boolean ENABLED_TRANSPORT_TRACE = true; /** Trace output for contact synchronisation components. **/ public static final boolean ENABLED_CONTACTS_SYNC_TRACE = false; /** Log engine runtime information to file for profiling. **/ public static final boolean ENABLED_PROFILE_ENGINES = false; /** * This is a list of strings containing the names of engines to be * deactivated in the build. A de-activated engine is constructed but will * never be run (nor will onCreate or onDestroy be called). Any UI requests * will be automatically completed by the framework with a * ServiceStatus.ERROR_NOT_IMPLEMENTED error. */ public static final String DEACTIVATE_ENGINE_LIST_KEY = "deactivated-engines-list"; /* * Hard coded settings */ /** Enable dialler cheat code. **/ public static final boolean DIALER_CHEATCODES_ENABLED = true; /** Enable SMS account activation. **/ public static final boolean ENABLE_ACTIVATION = false; /** * Enable SIM inserted check. Always set to TRUE. Makes the application * unusable if there is no valid SIM card inserted into the device. */ public static final boolean ENABLE_SIM_CHECK = true; /** Enable fetching native contacts. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS = true; /** Enable fetching native contacts on change. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS_ON_CHANGE = true; /** Enable ME profile synchronisation. **/ public static final boolean ENABLE_ME_PROFILE_SYNC = true; /** Enable server contact synchronisation. **/ public static final boolean ENABLE_SERVER_CONTACT_SYNC = true; /** Enable server thumbnail synchronisation. **/ public static final boolean ENABLE_THUMBNAIL_SYNC = true; /** Enable update native contacts synchronisation. **/ public static final boolean ENABLE_UPDATE_NATIVE_CONTACTS = true; /** Enable hiding of connected friends group. **/ public static final boolean HIDE_CONNECTED_FRIENDS_GROUP = true; /** Disable the native sync after the first time import for Android 1.X devices only **/ public static final boolean DISABLE_NATIVE_SYNC_AFTER_IMPORT_ON_ANDROID_1X = true; /* * Keys for properties that can be changed at build time. */ /** Key for application ID setting. **/ public static final String APP_KEY_ID = "app-key-id"; /** Key for application secret key setting. **/ public static final String APP_SECRET_KEY = "app-secret-key"; /** Key for enable logging setting. **/ protected static final String ENABLE_LOGCAT_KEY = "enable-logcat"; /** Key for enable RPG setting. **/ public static final String ENABLE_RPG_KEY = "use-rpg"; /** Key for enable SNS resource icon setting. **/ public static final String ENABLE_SNS_RESOURCE_ICON_KEY = "enable-sns-resource-icon"; /** Key for RPG server URL setting. **/ public static final String RPG_SERVER_KEY = "rpg-url"; /** Key for Hessian URL setting. **/ public static final String SERVER_URL_HESSIAN_KEY = "hessian-url"; /* * Keys without defaults. */ /** Key for TCP server URL setting. **/ public static final String TCP_RPG_URL_KEY = "rpg-tcp-url"; /** Key for TCP port setting. **/ public static final String TCP_RPG_PORT_KEY = "rpg-tcp-port"; /** Key for upgrade check URL setting. **/ public static final String UPGRADE_CHECK_URL_KEY = "upgrade-url"; /* * Default for properties that can be changed at build time. */ /** Default for logging enabled setting. **/ protected static final String DEFAULT_ENABLE_LOGCAT = "true"; /** Default for RPG enabled setting. **/ protected static final String DEFAULT_ENABLE_RPG = "true"; /** Default for SNS resource icon setting. **/ protected static final String DEFAULT_ENABLE_SNS_RESOURCE_ICON = "true"; /** Default for RPG server URL setting. **/ protected static final String DEFAULT_RPG_SERVER = "http://rpg.vodafone360.com/rpg/mcomet/"; /** Default for Hessian URL setting. **/ protected static final String DEFAULT_SERVER_URL_HESSIAN = "http://api.vodafone360.com/services/hessian/"; /* * Request timeouts for all engines and requests, except for fire and * forget calls to RPG: SET_AVAILABILITY and SEND_CHAT_MSG. */ /** Do not handle timeouts for this API. **/ private static final long DONT_HANDLE_TIMEOUTS = -1; /** Generic timeout for requests. **/ private static final long ALL_ENGINES_REQUESTS_TIMEOUT = 60000; /** Timeout for all presence API requests. **/ private static final long PRESENCE_ENGINE_REQUESTS_TIMEOUT = 120000; /** Number of milliseconds in a week. **/ public static final long HISTORY_IS_WEEK_LONG = 7 * 24 * 60 * 60 * 1000; /** Timeout for request waiting in queue. **/ public static final long REMOVE_REQUEST_FROM_QUEUE_MILLIS = 15 * 60 * 1000; /* * The timeouts in milliseconds for the different APIs. */ /** Timeout for activities API. **/ public static final long API_REQUESTS_TIMEOUT_ACTIVITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for authentication API. **/ public static final long API_REQUESTS_TIMEOUT_AUTH = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat create conversation API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_CREATE_CONV = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat send message API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_SEND_MESSAGE = DONT_HANDLE_TIMEOUTS; /** Timeout for contacts API. **/ public static final long API_REQUESTS_TIMEOUT_CONTACTS = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for group privacy API. **/ public static final long API_REQUESTS_TIMEOUT_GROUP_PRIVACY = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for identities API. **/ public static final long API_REQUESTS_TIMEOUT_IDENTITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for presence list API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_LIST = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Timeout for presence set availability API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Enable Facebook chat. **/ public static boolean sEnableFacebookChat = true; /** * Danger! Only set to true if you know what you are doing! This logs each * response no matter if gzipped or not to the SD card under the given * request ID. */ public static boolean sEnableSuperExpensiveResponseFileLogging = false; /** * Private constructor to prevent instantiation. */ private Settings() { } } \ No newline at end of file diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 482f385..9a915ba 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,806 +1,839 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; -import android.text.TextUtils; - import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.ChatMessage; import com.vodafone360.people.datatypes.Conversation; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.PresenceList; import com.vodafone360.people.datatypes.PushAvailabilityEvent; import com.vodafone360.people.datatypes.PushChatMessageEvent; import com.vodafone360.people.datatypes.PushClosedConversationEvent; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.datatypes.SystemNotification.Tags; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Chat; import com.vodafone360.people.service.io.api.Presence; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.HardcodedUtils; import com.vodafone360.people.utils.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, ITcpConnectionListener { /** Check every 24 hours **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private final List<TimelineSummaryItem> mFailedMessagesList; // (to, network) /** The list of Users still to be processed. **/ private List<User> mUsers = null; /** * This state indicates there are no more pending presence payload * information to be processed. **/ private static final int IDLE = 0; /** * This state indicates there are some pending presence payload information * to be processed. **/ private static final int UPDATE_PROCESSING_GOING_ON = 1; /** Timeout between each presence update processing. **/ private static final long UPDATE_PRESENCE_TIMEOUT_MILLS = 0; /** The page size i.e the number of presence updates processed at a time. **/ private static final int UPDATE_PRESENCE_PAGE_SIZE = 10; /** The number of pages after which the HandlerAgent is notified. **/ private static final int NOTIFY_AGENT_PAGE_INTERVAL = 5; /** The state of the presence Engine. **/ private int mState = IDLE; /** * Number of pages of presence Updates done. This is used to control when a * notification is sent to the UI. **/ private int mIterations = 0; /** * True if the engine runs for the 1st time. */ private boolean firstRun = true; /** * * @param eventCallback * @param databaseHelper */ public PresenceEngine(IEngineEventCallback eventCallback, DatabaseHelper databaseHelper) { super(eventCallback); mEngineId = EngineId.PRESENCE_ENGINE; mDbHelper = databaseHelper; mSendMessagesHash = new Hashtable<String, ChatMessage>(); mFailedMessagesList = new ArrayList<TimelineSummaryItem>(); } @Override public void onCreate() { } @Override public void onDestroy() { if (mDbHelper != null && SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper) != null) { PresenceDbUtils.resetPresenceStatesAcceptForMe(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), mDbHelper); } EngineManager.getInstance().getLoginEngine().removeListener(this); } /** * Checks if the SyncMe and ContactSync Engines have both completed first time sync. * * @return true if both engines have completed first time sync */ private boolean isFirstTimeSyncComplete() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!isFirstTimeSyncComplete()) { LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"); return -1; } /** * need isUiRequestOutstanding() because currently the worker thread is * running and finishing before PresenceEngine.setNextRuntime is called */ if (isCommsResponseOutstanding() || isUiRequestOutstanding()) { LogUtils.logV("PresenceEngine getNextRunTime() comms response outstanding"); return 0; } if (firstRun) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); firstRun = false; } return getCurrentTimeout(); } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + getCurrentTimeout() + "]"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logV("PresenceEngine.run() handled processCommsInQueue()"); return; } if (processTimeout()) { LogUtils.logV("PresenceEngine.run() handled processTimeout()"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logV("PresenceEngine.run(): AgentState.DISCONNECTED"); setPresenceOffline(); } /** * and the getNextRunTime must check the uiRequestReady() function and * return 0 if it is true */ if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { return isUiRequestOutstanding(); } private User getMyAvailabilityStatusFromDatabase() { return PresenceDbUtils.getMeProfilePresenceStatus(mDbHelper); } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setTimeout(CHECK_FREQUENCY); } } else { firstRun = true; mFailedMessagesList.clear(); mSendMessagesHash.clear(); setPresenceOffline(); } } /*** * Set the Global presence status to offline. */ private synchronized void setPresenceOffline() { PresenceDbUtils.setPresenceOfflineInDatabase(mDbHelper); // We clear the mUsers of any pending presence updates because this // Offline presence update request should take the highest priority. mUsers = null; mState = IDLE; mEventCallback.getUiAgent().updatePresence(UiAgent.ALL_USERS); } @Override protected void onRequestComplete() { LogUtils.logI("PresenceEngine.onRequestComplete()"); } @Override protected void onTimeoutEvent() { LogUtils.logI("PresenceEngine.onTimeoutEvent()"); switch (mState) { case UPDATE_PROCESSING_GOING_ON: updatePresenceDatabaseNextPage(); break; case IDLE: default: if (mLoggedIn) { if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setTimeout(CHECK_FREQUENCY); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); setTimeout(CHECK_FREQUENCY / 20); } } } } @Override protected void processCommsResponse(DecodedResponse resp) { handleServerResponse(resp.mDataTypes); } private void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg) { UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribedWithChat()) { uiAgent.sendUnsolicitedUiEvent(errorEvent, null); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users List of users that require updating. */ private synchronized void updatePresenceDatabase(List<User> users) { if (users == null || users.size() == 0) { LogUtils.logW("PresenceEngine.updatePresenceDatabase() users is NULL or zero size"); } else { if (mUsers == null) { mUsers = users; } else { // Doing an add one by one is not an efficient way but then // there is an issue in the addAll API. It crashes sometimes. // And the java code for the AddAll API seems to be erroneous. // More investigation is needed on this. for (User user : users) { mUsers.add(user); } } } mState = UPDATE_PROCESSING_GOING_ON; updatePresenceDatabaseNextPage(); } /** * This API makes the presence updates in pages of 10 with a timeout * after each page. The HandlerAgent is notified after every 10 pages. */ private synchronized void updatePresenceDatabaseNextPage(){ UiAgent uiAgent = mEventCallback.getUiAgent(); if(mUsers == null){ mState = IDLE; return; } int listSize = mUsers.size(); int start = 0; int end = UPDATE_PRESENCE_PAGE_SIZE; if(listSize == 0){ mState = IDLE; mUsers = null; return; } else if(listSize < end) { end = listSize; } List<User> userSubset = mUsers.subList(start, end); if ((userSubset != null)) { long idListeningTo = UiAgent.ALL_USERS; if (uiAgent != null) { idListeningTo = uiAgent.getLocalContactId(); } boolean updateUI = PresenceDbUtils.updateDatabase(userSubset, idListeningTo, mDbHelper); userSubset.clear(); // Send the update notification to UI for every UPDATE_PRESENCE_PAGE_SIZE*NOTIFY_AGENT_PAGE_INTERVAL updates. if (updateUI) { if (mUsers.size() == 0 || NOTIFY_AGENT_PAGE_INTERVAL == mIterations) { if (uiAgent != null) { uiAgent.updatePresence(idListeningTo); } mIterations = 0; } else { mIterations++; } } this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: + LogUtils.logE(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SET_MY_AVAILABILITY:"+ data); Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); LogUtils.logW("PresenceEngine processUiRequest() SEND_CHAT_MESSAGE :" + msg); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } // Get presences // TODO: Fill up hashtable with identities and online statuses Hashtable<String, String> presenceList = HardcodedUtils.createMyAvailabilityHashtable(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } - + /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * - * @param presence Network-presence to set + * @param status Availability to set for all identities we have. */ - public void setMyAvailability(NetworkPresence presence) { - if (presence == null) { + public void setMyAvailability(Hashtable<String, String> presenceList) { + if (presenceList == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } - LogUtils.logV("PresenceEngine setMyAvailability() called with network presence:"+presence.toString()); + LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+ presenceList.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } - ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); - presenceList.add(presence); + // Get presences + // TODO: Fill up hashtable with identities and online statuses + User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), - null); - me.setPayload(presenceList); + presenceList); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } + + /** + * Changes the user's availability and therefore the state of the engine. + * Also displays the login notification if necessary. + * + * @param presence Network-presence to set + */ + public void setMyAvailability(SocialNetwork network, OnlineStatus status) { + + LogUtils.logV("PresenceEngine setMyAvailability() called with network presence: "+network + "=" + status); + if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { + LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); + return; + } + + ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); + + String userId = String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)); + + presenceList.add(new NetworkPresence(userId, network.ordinal(), status.ordinal())); + + User me = new User(userId, null); + + me.setPayload(presenceList); + + // set the DB values for myself + me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); + updateMyPresenceInDatabase(me); + + // set the engine to run now + Hashtable<String, String> presence = new Hashtable<String, String>(); + presence.put(network.toString(), status.toString()); + addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presence); + } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { LogUtils.logW("PresenceEngine.sendMessage() to:" + toLocalContactId + ", body:" + body + ", at:" + networkId); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } @Override public void onConnectionStateChanged(int state) { if (mLoggedIn && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * This method gets the availability information for Me Profile from the Presence * table and updates the same to the server. */ public final void setMyAvailability() { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if(identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); for(Identity identity : identities) { presences.put(identity.mNetwork, statusString); } return presences; } @Override public void onReset() { // reset the engine as if it was just created super.onReset(); firstRun = true; mLoggedIn = false; mIterations = 0; mState = IDLE; mUsers = null; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } diff --git a/src/com/vodafone360/people/engine/presence/User.java b/src/com/vodafone360/people/engine/presence/User.java index babc209..5ad72f9 100644 --- a/src/com/vodafone360/people/engine/presence/User.java +++ b/src/com/vodafone360/people/engine/presence/User.java @@ -1,273 +1,277 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; +import com.vodafone360.people.utils.LogUtils; /** * User is a class encapsulating the information about a user's presence state. */ public class User { private static final String COLUMNS = "::"; private long mLocalContactId; // the database id of the contact, which // corresponds to, e.g. "[email protected]" private int mOverallOnline; // the overall presence state displayed in the // common contact list private ArrayList<NetworkPresence> mPayload; // communities presence status // {google:online, pc:online, // mobile:online} /** * Default Constructor. */ public User() { } /** * Constructor. * * @param userId - user id in the contact list, e.g. * "google::[email protected]" or "882339" * @param payload - communities presence status {google:online, pc:online, * mobile:online} */ public User(String userId, Hashtable<String, String> payload) { - mOverallOnline = isOverallOnline(payload); - mPayload = createPayload(userId, payload); + LogUtils.logE("user id " + userId + ": "+ payload); + if (payload != null) { + mOverallOnline = isOverallOnline(payload); + mPayload = createPayload(userId, payload); + } } /** * This method returns the localContactId for this contact in DB across the * application . * * @return the localContactId for this contact in DB */ public long getLocalContactId() { return mLocalContactId; } public void setLocalContactId(long mLocalContactId) { this.mLocalContactId = mLocalContactId; } /** * Returns communities presence status * * @return communities presence status, e.g. {google:online, pc:online, * mobile:online} */ public ArrayList<NetworkPresence> getPayload() { return mPayload; } public OnlineStatus getStatusForNetwork(SocialNetwork network) { if (network == null) { return null; } OnlineStatus os = OnlineStatus.OFFLINE; if (mPayload != null) { if (network == SocialNetwork.VODAFONE) { int aggregated = 0; // aggregated state for "mobile" and "pc" for (NetworkPresence np : mPayload) { if (np.getNetworkId() == SocialNetwork.MOBILE.ordinal() || (np.getNetworkId() == SocialNetwork.PC.ordinal())) { if (aggregated < np.getOnlineStatusId()) { aggregated += np.getOnlineStatusId(); } } } os = OnlineStatus.getValue(aggregated); } else { for (NetworkPresence np : mPayload) { if (np.getNetworkId() == network.ordinal()) { os = OnlineStatus.getValue(np.getOnlineStatusId()); break; } } } } return os; } /** * Returns communities presence status * * @return communities presence status, e.g. {google:online, pc:online, * mobile:online} */ public void setPayload(ArrayList<NetworkPresence> payload) { mPayload = payload; } /** * Returns the overall user presence status * * @return true if user is online at least at one community, e.g. true if * {google:offline, pc:offline, mobile:online} */ private int isOverallOnline(Hashtable<String, String> payload) { if (payload != null) { if (payload.values().contains(ContactSummary.OnlineStatus.ONLINE.toString())) return ContactSummary.OnlineStatus.ONLINE.ordinal(); if (payload.values().contains(ContactSummary.OnlineStatus.INVISIBLE.toString())) return ContactSummary.OnlineStatus.INVISIBLE.ordinal(); if (payload.values().contains(ContactSummary.OnlineStatus.IDLE.toString())) return ContactSummary.OnlineStatus.IDLE.ordinal(); } return ContactSummary.OnlineStatus.OFFLINE.ordinal(); } /** * Returns the overall user presence status: in fact the one from the below * status states first encountered for all known user accounts next: * INVISIBLE, ONLINE, IDLE, OFFLINE * * @return presence state */ public int isOnline() { return mOverallOnline; } /** * @param payload * @return */ private ArrayList<NetworkPresence> createPayload(String userId, Hashtable<String, String> payload) { ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(payload.size()); String parsedUserId = parseUserName(userId); String key = null; SocialNetwork network = null; String value = null; OnlineStatus status = null; for (Enumeration<String> en = payload.keys(); en.hasMoreElements();) { key = en.nextElement(); network = SocialNetwork.getValue(key); if (network != null) { int keyIdx = network.ordinal(); value = payload.get(key); if (value != null) { status = OnlineStatus.getValue(value); if (status != null) { int valueIdx = status.ordinal(); presenceList.add(new NetworkPresence(parsedUserId, keyIdx, valueIdx)); } } } } return presenceList; } /** * @param user * @return */ private static String parseUserName(String userId) { if (userId != null) { int columnsIndex = userId.indexOf(COLUMNS); if (columnsIndex > -1) { return userId.substring(columnsIndex + COLUMNS.length()); } else { return userId; } } return null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mOverallOnline; result = prime * result + ((mPayload == null) ? 0 : mPayload.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User)obj; if (mOverallOnline != other.mOverallOnline) return false; if (mPayload == null) { if (other.mPayload != null) return false; } else if (!mPayload.equals(other.mPayload)) return false; return true; } @Override public String toString() { final StringBuffer sb = new StringBuffer("User [mLocalContactId="); sb.append(mLocalContactId); sb.append(", mOverallOnline="); sb.append(mOverallOnline); sb.append(", mPayload="); sb.append(mPayload); sb.append("]"); return sb.toString(); } /** * This method sets the overall user presence status, * @parameter the online status id - the ordinal, see @OnlineStatus */ public void setOverallOnline(int overallOnline) { this.mOverallOnline = overallOnline; } /** * This method removes the network presence information with the given presence id from the User. * @param ordinal - the network id, ordinal in @see SocialNetworks */ public void removeNetwork(int ordinal) { Iterator<NetworkPresence> itr = mPayload.iterator(); NetworkPresence presence = null; while (itr.hasNext()) { presence = itr.next(); if (presence.getNetworkId() == ordinal) { itr.remove(); break; } } } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index f7a1129..e7759cd 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,361 +1,368 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.interfaces; import java.util.ArrayList; +import java.util.Hashtable; import android.os.Bundle; import android.os.Handler; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; -import com.vodafone360.people.engine.presence.NetworkPresence; +import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.agent.NetworkAgentState; /*** * Interface to expose service functionality to the UI classes. */ public interface IPeopleService { /*** * Allows the Activity to register a Handler, so that it can receive new * call back events from the Service layer. * * @param Handler to listen for call back events. */ void addEventCallback(Handler uiHandler); /*** * Allows the Activity to unregister a Handler, so it will no longer receive * call back events from the Service layer. Usually called on an Activity's * onDestroy() method. * * @param Handler to listen for call back events. */ void removeEventCallback(Handler uiHandler); /*** * Called by the UI to determine if the Service is currently logged into the * Vodafone 360 back end. Called by the StartActivity and other key classes, * so the work flow can be diverted back to the Landing page if the user has * been signed out for any reason. * * @return TRUE Service is logged into the back end system, FALSE user must * log in before they can use the Application. */ boolean getLoginRequired(); /*** * Sets a preference that disables the showing of further roaming * notifications. * * @param TRUE show further roaming notifications, FALSE stop showing */ void setShowRoamingNotificationAgain(boolean showAgain); /*** * Gets the type of roaming notification to show to the user * * @return ROAMING_DIALOG_GLOBAL_ON Data roaming is on, * ROAMING_DIALOG_GLOBAL_OFF Data roaming is off */ int getRoamingNotificationType(); /*** * Gets the current IS_ROAMING_ALLOWED value for the device, which is set by * the user in the * "Menu > Settings > Wireless Controls > Mobile network settings > Data roaming" * check box. * * @return TRUE when roaming is permitted, FALSE when roaming is not * permitted. */ boolean getRoamingDeviceSetting(); /*** * Sets the current Data connectivity preference (i.e. connect, connect when * not roaming, or never connect), although this value is ignored during * initial sign up. * * @see com.vodafone360.people.service.PersistSettings.InternetAvail * @param InternetAvail New data Settings changes */ void notifyDataSettingChanged(InternetAvail internetAvail); /*** * Fetched the current Terms of Service information from the Vodafone 360 * back end system. The result is sent to the registered Handler some time * later after the download process has finished. */ void fetchTermsOfService(); /*** * Fetched the current Privacy Statement information from the Vodafone 360 * back end system. The result is sent to the registered Handler some time * later after the download process has finished. */ void fetchPrivacyStatement(); /*** * Log into the Vodafone 360 back end system using the given credentials. * * @param LoginDetails object containing user name, password, etc. */ void logon(LoginDetails loginDetails); /*** * Asks the back end server to check the validity of the given user name. * * @param String User name to check. */ void fetchUsernameState(String username); /*** * Signs up a new user to the Vodafone 360 back end using the given * Registration details. * * @param RegistrationDetails Registration details */ void register(RegistrationDetails details); /*** * Begins the process of synchronising contacts with the Vodafone 360 back * end. This is designed to run in the foreground and be shown to the user * during the initial sign up process. */ void startContactSync(); /*** * Begins the process of synchronising contacts with the Vodafone 360 back * end. This is designed to run in the background and is called every time * the ContactListActivity is shown to the user. * * @param delay the delay in milliseconds from now when the sync should * start */ void startBackgroundContactSync(long delay); /** * Pings the service about user activity. */ void pingUserActivity(); /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities(); /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities(); /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities(); /*** * Begins the process of retrieving all Third party Accounts from the * Vodafone 360 back end. The response is sent to any currently registered * Activity handlers. * * @param Bundle filter the kind of identities to return. */ //void fetchAvailableIdentities(Bundle data); /*** * Calls the set identity capability status API * * @param network Social Network Name * @param identityId Social Network Identifier * @param identityCapabilityStatus Social Network capability status Bundle */ void setIdentityStatus(String network, String identityId, boolean identityStatus); /*** * Validate the given Social Network identity * * @param dryRun Set to true to validate credentials without actually * signing the server up. * @param network Social Network Name * @param username Login user name * @param password Login password * @param identityCapabilityStatus Social Network capability status Bundle */ void validateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus); /*** * Push the UpdateEngine to immediately check for an updated version of the * client. */ void checkForUpdates(); /*** * Push the UpdateEngine to check if a new update frequency has been set and * to act accordingly. */ void setNewUpdateFrequency(); /*** * Push the ActivitiesEngine Engine to begin synchronising Activities */ void startStatusesSync(); /*** * Returns the current state of the Network Agent. Used for testing only. */ NetworkAgentState getNetworkAgentState(); /*** * Overrides the current state of the Network Agent. Used for testing only. * * @param state A new overriding state. */ void setNetworkAgentState(NetworkAgentState state); /*** * Request a refresh of the currently known Presence information (used for * testing only) * * @param contactId Provide a contactId to receive detailed presence * information for the given contact only * @param contactId Set this to -1 to receive less detailed presence * information but for every contact */ void getPresenceList(long contactId); /** * Change current global (all identities) availability state. * @param status Availability to set for all identities we have. */ void setAvailability(OnlineStatus status); + /** + * Change current global (all identities) availability state. + * @param status Availability to set for all identities we have. + */ + void setAvailability(Hashtable<String, String> status); + /** * Change current availability state for a single network. * @param presence Network-presence to set */ - void setAvailability(NetworkPresence presence); + void setAvailability(SocialNetwork network, OnlineStatus status); /*** * Allows an Activity to indicate to the Service that it is ready and able * to handle incoming unsolicited UI events. This should be called in an * Activities onResume() method, to indicate that the activity is currently * on screen. * * @param handler to accept incoming unsolicited UI events from the Service. * @param contactId Provide a contactId to receive updates for the given * contact only. Set this to -1 to receive updates for every * contact. Set this to NULL not to receive contact updates. * @param chat - TRUE if the Handler expects chat messages. */ void subscribe(Handler handler, Long contactId, boolean chat); /*** * Allows the Activity to indicate that it is no longer in the foreground * and will not handle incoming UI events correctly. This should be called * in an Activities onPause() method, to indicate that the Activity is not * on screen. * * @param handler that should no longer receive incoming unsolicited UI * events from the Service */ void unsubscribe(Handler handler); /** * This method should be used to send a message to a contact * * @param to LocalContactIds of ContactSummary/TimelineSummary items the * message is intended for. Current protocol version only * supports a single recipient. * @param body Message text */ void sendMessage(long toLocalContactId, String body, int socialNetworkId); /** * This method should be called to retrieve status updates in * StatusListActivity, @see ActivitiesEngine. */ void getStatuses(); /** * This method should be called to retrieve older timelines in * TimelineListActivity, @see ActivitiesEngine. */ void getMoreTimelines(); /** * This method should be called to retrieve older statuses in * StatusListActivity, @see ActivitiesEngine. */ void getOlderStatuses(); /** * This method triggers the Me Profile upload */ void uploadMeProfile(); /** * This method triggers the Me Profile status text upload * * @param statusText String - new Me Profile status text */ void uploadMyStatus(String statusText); /** * This method triggers the Me Profile download, is currently called by UI */ void downloadMeProfileFirstTime(); /** * This method should be called to update the Chat Notifications. */ void updateChatNotification(long localContactId); } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java index 5ecea59..895ddbe 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,433 +1,440 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.interfaces; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import android.os.Bundle; import android.os.Handler; import android.os.Message; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.MainApplication; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback; import com.vodafone360.people.engine.presence.NetworkPresence; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.agent.NetworkAgentState; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.utils.LogUtils; /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback * @see com.vodafone360.people.service.interfaces.IPeopleService */ public class IPeopleServiceImpl implements IPeopleService, IEngineEventCallback { private final List<Handler> mUiEventCallbackList = new ArrayList<Handler>(); private IWorkerThreadControl mWorkerThreadControl; private RemoteService mService; private NetworkAgent mNetworkAgent; private UiAgent mHandlerAgent; private ApplicationCache mApplicationCache; /** * Initialises the object, creating the UiAgent. * * @param workerThreadControl Provides access to worker thread control * functions. * @param service Provides access to remote service functions (mainly used * to retrieve context). */ public IPeopleServiceImpl(IWorkerThreadControl workerThreadControl, RemoteService service) { mWorkerThreadControl = workerThreadControl; mService = service; mHandlerAgent = new UiAgent((MainApplication)service.getApplication(), service); mApplicationCache = ((MainApplication)service.getApplication()).getCache(); } /*** * Sets the ServiceAgent, as this needs to be called after the constructor. * * @param agent Handle to ServiceAgent. */ public void setNetworkAgent(NetworkAgent agent) { mNetworkAgent = agent; } /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#onUiEvent(UiEvent, * int, int, Object) */ @Override public void onUiEvent(ServiceUiRequest event, int arg1, int arg2, Object data) { synchronized (mUiEventCallbackList) { for (Handler handler : mUiEventCallbackList) { Message msg = handler.obtainMessage(event.ordinal(), data); msg.arg1 = arg1; msg.arg2 = arg2; if (!handler.sendMessage(msg)) { LogUtils.logE("IPeopleServiceImpl.onUiEvent() Sending msg FAILED"); } } } } /*** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#kickWorkerThread() */ @Override public void kickWorkerThread() { mWorkerThreadControl.kickWorkerThread(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#addEventCallback(Handler) */ @Override public void addEventCallback(Handler uiHandler) { synchronized (mUiEventCallbackList) { if (!mUiEventCallbackList.contains(uiHandler)) { mUiEventCallbackList.add(uiHandler); } } } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#removeEventCallback(Handler) */ @Override public void removeEventCallback(Handler uiHandler) { synchronized (mUiEventCallbackList) { mUiEventCallbackList.remove(uiHandler); } } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#checkForUpdates() */ @Override public void checkForUpdates() { EngineManager.getInstance().getUpgradeEngine().checkForUpdates(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMyThirdPartyIdentities() */ public ArrayList<Identity> getMyThirdPartyIdentities() { return EngineManager.getInstance().getIdentityEngine().getMyThirdPartyIdentities(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyIdentities() */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { return EngineManager.getInstance().getIdentityEngine().getAvailableThirdPartyIdentities(); } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyChattableIdentities() */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { return EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchPrivacyStatement() */ @Override public void fetchPrivacyStatement() { EngineManager.getInstance().getLoginEngine().addUiFetchPrivacyStatementRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchTermsOfService() */ @Override public void fetchTermsOfService() { EngineManager.getInstance().getLoginEngine().addUiFetchTermsOfServiceRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchUsernameState(String) */ @Override public void fetchUsernameState(String userName) { EngineManager.getInstance().getLoginEngine().addUiGetUsernameStateRequest(userName); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getLoginRequired() */ @Override public boolean getLoginRequired() { EngineManager manager = EngineManager.getInstance(); return manager.getLoginEngine().getLoginRequired(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getRoamingNotificationType() */ @Override public int getRoamingNotificationType() { return mService.getNetworkAgent().getRoamingNotificationType(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getRoamingDeviceSetting() */ @Override public boolean getRoamingDeviceSetting() { return mService.getNetworkAgent().getRoamingDeviceSetting(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#notifyDataSettingChanged(InternetAvail) */ @Override public void notifyDataSettingChanged(InternetAvail val) { mService.getNetworkAgent().notifyDataSettingChanged(val); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#logon(LoginDetails) */ @Override public void logon(LoginDetails loginDetails) { EngineManager manager = EngineManager.getInstance(); manager.getLoginEngine().addUiLoginRequest(loginDetails); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#register(RegistrationDetails) */ @Override public void register(RegistrationDetails details) { EngineManager.getInstance().getLoginEngine().addUiRegistrationRequest(details); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setNewUpdateFrequency() */ @Override public void setNewUpdateFrequency() { EngineManager.getInstance().getUpgradeEngine().setNewUpdateFrequency(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setShowRoamingNotificationAgain(boolean) */ @Override public void setShowRoamingNotificationAgain(boolean showAgain) { mService.getNetworkAgent().setShowRoamingNotificationAgain(showAgain); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startContactSync() */ @Override public void startContactSync() { EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); EngineManager.getInstance().getContactSyncEngine().addUiStartFullSync(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startBackgroundContactSync(long) */ @Override public void startBackgroundContactSync(long delay) { EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); EngineManager.getInstance().getContactSyncEngine().addUiStartServerSync(delay); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#pingUserActivity() */ @Override public void pingUserActivity() { EngineManager.getInstance().getContactSyncEngine().pingUserActivity(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#validateIdentityCredentials(boolean, * String, String, String, Bundle) */ @Override public void validateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { EngineManager.getInstance().getIdentityEngine().addUiValidateIdentityCredentials(dryRun, network, username, password, identityCapabilityStatus); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#startStatusesSync() */ @Override public void startStatusesSync() { EngineManager.getInstance().getActivitiesEngine().addStatusesSyncRequest(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getNetworkAgentState() */ @Override public NetworkAgentState getNetworkAgentState() { return mNetworkAgent.getNetworkAgentState(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setNetowrkAgentState(NetworkAgentState) */ @Override public void setNetworkAgentState(NetworkAgentState state) { mNetworkAgent.setNetworkAgentState(state); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#getPresenceList(long) */ @Override public void getPresenceList(long contactId) { EngineManager.getInstance().getPresenceEngine().getPresenceList(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(OnlineStatus) */ @Override public void setAvailability(OnlineStatus status) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(NetworkPresence) */ @Override - public void setAvailability(NetworkPresence presence) { - EngineManager.getInstance().getPresenceEngine().setMyAvailability(presence); + public void setAvailability(SocialNetwork network, OnlineStatus status) { + EngineManager.getInstance().getPresenceEngine().setMyAvailability(network, status); + } + + /*** + * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(Hashtable<String, String> status) + */ + @Override + public void setAvailability(Hashtable<String, String> status) { + EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } - /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#subscribe(Handler, * long, boolean) */ @Override public void subscribe(Handler handler, Long contactId, boolean chat) { mHandlerAgent.subscribe(handler, contactId, chat); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#unsubscribe(Handler) */ @Override public void unsubscribe(Handler handler) { mHandlerAgent.unsubscribe(handler); } /** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#getUiAgent() */ @Override public UiAgent getUiAgent() { return mHandlerAgent; } /** * @see com.vodafone360.people.engine.BaseEngine.IEngineEventCallback#getApplicationCache() */ @Override public ApplicationCache getApplicationCache() { return mApplicationCache; } /** * @see com.vodafone360.people.service.interfaces.IPeopleService#sendMessage(long, * String, int) */ @Override public void sendMessage(long localContactId, String body, int networkId) { EngineManager.getInstance().getPresenceEngine() .sendMessage(localContactId, body, networkId); } @Override public void setIdentityStatus(String network, String identityId, boolean identityStatus) { EngineManager.getInstance().getIdentityEngine().addUiSetIdentityStatus(network, identityId, identityStatus); } @Override public void getStatuses() { EngineManager.getInstance().getActivitiesEngine().addStatusesSyncRequest(); } @Override public void getMoreTimelines() { EngineManager.getInstance().getActivitiesEngine().addOlderTimelinesRequest(); } @Override public void getOlderStatuses() { EngineManager.getInstance().getActivitiesEngine().addGetOlderStatusesRequest(); } @Override public void uploadMeProfile() { EngineManager.getInstance().getSyncMeEngine().addUpdateMeProfileContactRequest(); } @Override public void uploadMyStatus(String statusText) { EngineManager.getInstance().getSyncMeEngine().addUpdateMyStatusRequest(statusText); } @Override public void downloadMeProfileFirstTime() { EngineManager.getInstance().getSyncMeEngine().addGetMeProfileContactFirstTimeRequest(); } @Override public void updateChatNotification(long localContactId) { mHandlerAgent.updateChat(localContactId, false); } } \ No newline at end of file
360/360-Engine-for-Android
42c152a7cf470ea0cb95ff132d12679315ab0ac9
Code review fixes
diff --git a/src/com/vodafone360/people/database/tables/ActivitiesTable.java b/src/com/vodafone360/people/database/tables/ActivitiesTable.java index 3554dbc..943c4bc 100644 --- a/src/com/vodafone360/people/database/tables/ActivitiesTable.java +++ b/src/com/vodafone360/people/database/tables/ActivitiesTable.java @@ -1,1772 +1,1783 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.database.tables; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import android.net.Uri; import android.provider.CallLog.Calls; import android.telephony.PhoneNumberUtils; +import android.text.TextUtils; import com.vodafone360.people.Settings; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.SQLKeys; import com.vodafone360.people.database.utils.SqlUtils; import com.vodafone360.people.datatypes.ActivityContact; import com.vodafone360.people.datatypes.ActivityItem; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.CloseUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.StringBufferPool; /** * Contains all the functionality related to the activities database table. This * class is never instantiated hence all methods must be static. * * @version %I%, %G% */ public abstract class ActivitiesTable { /*** * The name of the table as it appears in the database. */ private static final String TABLE_NAME = "Activities"; private static final String TABLE_INDEX_NAME = "ActivitiesIndex"; /** Database cleanup will delete any activity older than X days. **/ private static final int CLEANUP_MAX_AGE_DAYS = 20; /** Database cleanup will delete older activities after the first X. **/ private static final int CLEANUP_MAX_QUANTITY = 400; /*** * An enumeration of all the field names in the database. */ public static enum Field { /** Local timeline id. **/ LOCAL_ACTIVITY_ID("LocalId"), /** Activity ID. **/ ACTIVITY_ID("activityid"), /** Timestamp. */ TIMESTAMP("time"), /** Type of the event. **/ TYPE("type"), /** URI. */ URI("uri"), /** Title for timelines . **/ TITLE("title"), /** Contents of timelines/statuses. **/ DESCRIPTION("description"), /** Preview URL. **/ PREVIEW_URL("previewurl"), /** Store. **/ STORE("store"), /** Type of the event: status, chat messages, phone call or SMS/MMS. **/ FLAG("flag"), /** Parent Activity. **/ PARENT_ACTIVITY("parentactivity"), /** Has children. **/ HAS_CHILDREN("haschildren"), /** Visibility. **/ VISIBILITY("visibility"), /** More info. **/ MORE_INFO("moreinfo"), /** Contact ID. **/ CONTACT_ID("contactid"), /** User ID. **/ USER_ID("userid"), /** Contact name or the alternative. **/ CONTACT_NAME("contactname"), /** Other contact's localContactId. **/ LOCAL_CONTACT_ID("contactlocalid"), /** @see SocialNetwork. **/ CONTACT_NETWORK("contactnetwork"), /** Contact address. **/ CONTACT_ADDRESS("contactaddress"), /** Contact avatar URL. **/ CONTACT_AVATAR_URL("contactavatarurl"), /** Native item type. **/ NATIVE_ITEM_TYPE("nativeitemtype"), /** Native item ID. **/ NATIVE_ITEM_ID("nativeitemid"), /** Latest contact status. **/ LATEST_CONTACT_STATUS("latestcontactstatus"), /** Native thread ID. **/ NATIVE_THREAD_ID("nativethreadid"), /** For chat messages: if this message is incoming. **/ INCOMING("incoming"); /** Name of the field as it appears in the database. **/ private final String mField; /** * Constructor. * * @param field - The name of the field (see list above) */ private Field(final String field) { mField = field; } /** * @return the name of the field as it appears in the database. */ public String toString() { return mField; } } /** * An enumeration of supported timeline types. */ public static enum TimelineNativeTypes { /** Call log type. **/ CallLog, /** SMS log type. **/ SmsLog, /** MMS log type. **/ MmsLog, /** Chat log type. **/ ChatLog } /** * This class encapsulates a timeline activity item. */ public static class TimelineSummaryItem { /*** * Enum of Timeline types. */ public enum Type { /** Incoming type. **/ INCOMING, /** Outgoing type. **/ OUTGOING, /** Unsent type. **/ UNSENT, /** Unknown type (do not use). **/ UNKNOWN } /*** * Get the Type from a given Integer value. * @param input Integer.ordinal value of the Type * @return Relevant Type or UNKNOWN if the Integer is not known. */ public static Type getType(final int input) { if (input < 0 || input > Type.UNKNOWN.ordinal()) { return Type.UNKNOWN; } else { return Type.values()[input]; } } /** Maps to the local activity ID (primary key). **/ private Long mLocalActivityId; /** Maps to the activity timestamp in the table. **/ public Long mTimestamp; /** Maps to the contact name in the table. **/ public String mContactName; /** Set to true if there is an avatar URL stored in the table. **/ private boolean mHasAvatar; /** Maps to type in the table. **/ public ActivityItem.Type mType; /** Maps to local contact id in the table. **/ public Long mLocalContactId; /** Maps to contact network stored in the table. **/ public String mContactNetwork; /** Maps to title stored in the table. **/ public String mTitle; /** Maps to description stored in the table. **/ public String mDescription; /** * Maps to native item type in the table Can be an ordinal from the * {@link ActivitiesTable#TimelineNativeTypes}. */ public Integer mNativeItemType; /** * Key linking to the call-log or message-log item in the native * database. */ public Integer mNativeItemId; /** Server contact ID. **/ public Long mContactId; /** User ID from the server. **/ public Long mUserId; /** Thread ID from the native database (for messages). **/ public Integer mNativeThreadId; /** Contact address (phone number or email address). **/ public String mContactAddress; /** Messages can be incoming and outgoing. **/ public Type mIncoming; /** * Returns a string describing the timeline summary item. * * @return String describing the timeline summary item. */ @Override public final String toString() { final StringBuilder sb = new StringBuilder("TimeLineSummaryItem [mLocalActivityId["); sb.append(mLocalActivityId); sb.append("], mTimestamp["); sb.append(mTimestamp); sb.append("], mContactName["); sb.append(mContactName); sb.append("], mHasAvatar["); sb.append(mHasAvatar); sb.append("], mType["); sb.append(mType); sb.append("], mLocalContactId["); sb.append(mLocalContactId); sb.append("], mContactNetwork["); sb.append(mContactNetwork); sb.append("], mTitle["); sb.append(mTitle); sb.append("], mDescription["); sb.append(mDescription); sb.append("], mNativeItemType["); sb.append(mNativeItemType); sb.append("], mNativeItemId["); sb.append(mNativeItemId); sb.append("], mContactId["); sb.append(mContactId); sb.append("], mUserId["); sb.append(mUserId); sb.append("], mNativeThreadId["); sb.append(mNativeThreadId); sb.append("], mContactAddress["); sb.append(mContactAddress); sb.append("], mIncoming["); sb.append(mIncoming); sb.append("]]");; return sb.toString(); } @Override public final boolean equals(final Object object) { if (TimelineSummaryItem.class != object.getClass()) { return false; } TimelineSummaryItem item = (TimelineSummaryItem) object; return mLocalActivityId.equals(item.mLocalActivityId) && mTimestamp.equals(item.mTimestamp) && mContactName.equals(item.mContactName) && mHasAvatar == item.mHasAvatar && mType.equals(item.mType) && mLocalContactId.equals(item.mLocalContactId) && mContactNetwork.equals(item.mContactNetwork) && mTitle.equals(item.mTitle) && mDescription.equals(item.mDescription) && mNativeItemType.equals(item.mNativeItemType) && mNativeItemId.equals(item.mNativeItemId) && mContactId.equals(item.mContactId) && mUserId.equals(item.mUserId) && mNativeThreadId.equals(item.mNativeThreadId) && mContactAddress.equals(item.mContactAddress) && mIncoming.equals(item.mIncoming); } }; /** Number of milliseconds in a day. **/ private static final int NUMBER_OF_MS_IN_A_DAY = 24 * 60 * 60 * 1000; /** Number of milliseconds in a second. **/ private static final int NUMBER_OF_MS_IN_A_SECOND = 1000; /*** * Private constructor to prevent instantiation. */ private ActivitiesTable() { // Do nothing. } /** * Create Activities Table. * * @param writeableDb A writable SQLite database. */ public static void create(final SQLiteDatabase writeableDb) { DatabaseHelper.trace(true, "DatabaseHelper.create()"); writeableDb.execSQL("CREATE TABLE " + TABLE_NAME + " (" + Field.LOCAL_ACTIVITY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.ACTIVITY_ID + " LONG, " + Field.TIMESTAMP + " LONG, " + Field.TYPE + " TEXT, " + Field.URI + " TEXT, " + Field.TITLE + " TEXT, " + Field.DESCRIPTION + " TEXT, " + Field.PREVIEW_URL + " TEXT, " + Field.STORE + " TEXT, " + Field.FLAG + " INTEGER, " + Field.PARENT_ACTIVITY + " LONG, " + Field.HAS_CHILDREN + " INTEGER, " + Field.VISIBILITY + " INTEGER, " + Field.MORE_INFO + " TEXT, " + Field.CONTACT_ID + " LONG, " + Field.USER_ID + " LONG, " + Field.CONTACT_NAME + " TEXT, " + Field.LOCAL_CONTACT_ID + " LONG, " + Field.CONTACT_NETWORK + " TEXT, " + Field.CONTACT_ADDRESS + " TEXT, " + Field.CONTACT_AVATAR_URL + " TEXT, " + Field.LATEST_CONTACT_STATUS + " INTEGER, " + Field.NATIVE_ITEM_TYPE + " INTEGER, " + Field.NATIVE_ITEM_ID + " INTEGER, " + Field.NATIVE_THREAD_ID + " INTEGER, " + Field.INCOMING + " INTEGER);"); writeableDb.execSQL("CREATE INDEX " + TABLE_INDEX_NAME + " ON " + TABLE_NAME + " ( " + Field.TIMESTAMP + " )"); } /** * Fetches a comma separated list of table fields which can be used in an * SQL SELECT statement as the query projection. One of the * {@link #getQueryData} methods can used to fetch data from the cursor. * * @return SQL string */ private static String getFullQueryList() { DatabaseHelper.trace(false, "DatabaseHelper.getFullQueryList()"); final StringBuffer fullQuery = StringBufferPool.getStringBuffer(); fullQuery.append(Field.LOCAL_ACTIVITY_ID).append(SqlUtils.COMMA). append(Field.ACTIVITY_ID).append(SqlUtils.COMMA). append(Field.TIMESTAMP).append(SqlUtils.COMMA). append(Field.TYPE).append(SqlUtils.COMMA). append(Field.URI).append(SqlUtils.COMMA). append(Field.TITLE).append(SqlUtils.COMMA). append(Field.DESCRIPTION).append(SqlUtils.COMMA). append(Field.PREVIEW_URL).append(SqlUtils.COMMA). append(Field.STORE).append(SqlUtils.COMMA). append(Field.FLAG).append(SqlUtils.COMMA). append(Field.PARENT_ACTIVITY).append(SqlUtils.COMMA). append(Field.HAS_CHILDREN).append(SqlUtils.COMMA). append(Field.VISIBILITY).append(SqlUtils.COMMA). append(Field.MORE_INFO).append(SqlUtils.COMMA). append(Field.CONTACT_ID).append(SqlUtils.COMMA). append(Field.USER_ID).append(SqlUtils.COMMA). append(Field.CONTACT_NAME).append(SqlUtils.COMMA). append(Field.LOCAL_CONTACT_ID).append(SqlUtils.COMMA). append(Field.CONTACT_NETWORK).append(SqlUtils.COMMA). append(Field.CONTACT_ADDRESS).append(SqlUtils.COMMA). append(Field.CONTACT_AVATAR_URL).append(SqlUtils.COMMA). append(Field.INCOMING); return StringBufferPool.toStringThenRelease(fullQuery); } /** * Fetches activities information from a cursor at the current position. The * {@link #getFullQueryList()} method should be used to make the query. * * @param cursor The cursor returned by the query * @param activityItem An empty activity object that will be filled with the * result * @param activityContact An empty activity contact object that will be * filled */ public static void getQueryData(final Cursor cursor, final ActivityItem activityItem, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityItem. **/ activityItem.localActivityId = SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); activityItem.activityId = SqlUtils.setLong(cursor, Field.ACTIVITY_ID.toString(), null); activityItem.time = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); activityItem.type = SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); activityItem.uri = SqlUtils.setString(cursor, Field.URI.toString()); activityItem.title = SqlUtils.setString(cursor, Field.TITLE.toString()); activityItem.description = SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); activityItem.previewUrl = SqlUtils.setString(cursor, Field.PREVIEW_URL.toString()); activityItem.store = SqlUtils.setString(cursor, Field.STORE.toString()); activityItem.activityFlags = SqlUtils.setInt(cursor, Field.FLAG.toString(), null); activityItem.parentActivity = SqlUtils.setLong(cursor, Field.PARENT_ACTIVITY.toString(), null); activityItem.hasChildren = SqlUtils.setBoolean(cursor, Field.HAS_CHILDREN.toString(), activityItem.hasChildren); activityItem.visibilityFlags = SqlUtils.setInt(cursor, Field.VISIBILITY.toString(), null); // TODO: Field MORE_INFO is not used, consider deleting. /** Populate ActivityContact. **/ getQueryData(cursor, activityContact); } /** * Fetches activities information from a cursor at the current position. The * {@link #getFullQueryList()} method should be used to make the query. * * @param cursor The cursor returned by the query. * @param activityContact An empty activity contact object that will be * filled */ public static void getQueryData(final Cursor cursor, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityContact. **/ activityContact.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); activityContact.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); activityContact.mName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); activityContact.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); activityContact.mNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); activityContact.mAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); activityContact.mAvatarUrl = SqlUtils.setString(cursor, Field.CONTACT_AVATAR_URL.toString()); } /*** * Provides a ContentValues object that can be used to update the table. * * @param item The source activity item * @param contactIdx The index of the contact to use for the update, or null * to exclude contact specific information. * @return ContentValues for use in an SQL update or insert. * @note Items that are NULL will be not modified in the database. */ private static ContentValues fillUpdateData(final ActivityItem item, final Integer contactIdx) { DatabaseHelper.trace(false, "DatabaseHelper.fillUpdateData()"); ContentValues activityItemValues = new ContentValues(); ActivityContact ac = null; if (contactIdx != null) { ac = item.contactList.get(contactIdx); } activityItemValues.put(Field.ACTIVITY_ID.toString(), item.activityId); activityItemValues.put(Field.TIMESTAMP.toString(), item.time); if (item.type != null) { activityItemValues.put(Field.TYPE.toString(), item.type.getTypeCode()); } if (item.uri != null) { activityItemValues.put(Field.URI.toString(), item.uri); } /** TODO: Not sure if we need this. **/ // activityItemValues.put(Field.INCOMING.toString(), false); activityItemValues.put(Field.TITLE.toString(), item.title); activityItemValues.put(Field.DESCRIPTION.toString(), item.description); if (item.previewUrl != null) { activityItemValues.put(Field.PREVIEW_URL.toString(), item.previewUrl); } if (item.store != null) { activityItemValues.put(Field.STORE.toString(), item.store); } if (item.activityFlags != null) { activityItemValues.put(Field.FLAG.toString(), item.activityFlags); } if (item.parentActivity != null) { activityItemValues.put(Field.PARENT_ACTIVITY.toString(), item.parentActivity); } if (item.hasChildren != null) { activityItemValues.put(Field.HAS_CHILDREN.toString(), item.hasChildren); } if (item.visibilityFlags != null) { activityItemValues.put(Field.VISIBILITY.toString(), item.visibilityFlags); } if (ac != null) { activityItemValues.put(Field.CONTACT_ID.toString(), ac.mContactId); activityItemValues.put(Field.USER_ID.toString(), ac.mUserId); activityItemValues.put(Field.CONTACT_NAME.toString(), ac.mName); activityItemValues.put(Field.LOCAL_CONTACT_ID.toString(), ac.mLocalContactId); if (ac.mNetwork != null) { activityItemValues.put(Field.CONTACT_NETWORK.toString(), ac.mNetwork); } if (ac.mAddress != null) { activityItemValues.put(Field.CONTACT_ADDRESS.toString(), ac.mAddress); } if (ac.mAvatarUrl != null) { activityItemValues.put(Field.CONTACT_AVATAR_URL.toString(), ac.mAvatarUrl); } } return activityItemValues; } /** * Fetches a list of status items from the given time stamp. * * @param timeStamp Time stamp in milliseconds * @param readableDb Readable SQLite database * @return A cursor (use one of the {@link #getQueryData} methods to read * the data) */ public static Cursor fetchStatusEventList(final long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchStatusEventList()"); return readableDb.rawQuery("SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + " & " + ActivityItem.STATUS_ITEM + ") AND " + Field.TIMESTAMP + " > " + timeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); } /** * Returns a list of activity IDs already synced, in reverse chronological * order Fetches from the given timestamp. * * @param actIdList An empty list which will be filled with the result * @param timeStamp The time stamp to start the fetch * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus fetchActivitiesIds(final List<Long> actIdList, final Long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchActivitiesIds()"); Cursor cursor = null; try { long queryTimeStamp; if (timeStamp != null) { queryTimeStamp = timeStamp; } else { queryTimeStamp = 0; } cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.TIMESTAMP + " >= " + queryTimeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); while (cursor.moveToNext()) { actIdList.add(cursor.getLong(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchActivitiesIds()" + "Unable to fetch group list", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Adds a list of activities to table. The activities added will be grouped * in the database, based on local contact Id, name or contact address (see * {@link #removeContactGroup(Long, String, Long, int, * TimelineNativeTypes[], SQLiteDatabase)} * for more information on how the grouping works. * * @param actList The list of activities * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus addActivities(final List<ActivityItem> actList, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addActivities()"); SQLiteStatement statement = ContactsTable.fetchLocalFromServerIdStatement(writableDb); for (ActivityItem activity : actList) { try { writableDb.beginTransaction(); if (activity.contactList != null) { int clistSize = activity.contactList.size(); for (int i = 0; i < clistSize; i++) { final ActivityContact activityContact = activity.contactList.get(i); activityContact.mLocalContactId = ContactsTable.fetchLocalFromServerId( activityContact.mContactId, statement); int latestStatusVal = removeContactGroup( activityContact.mLocalContactId, activityContact.mName, activity.time, activity.activityFlags, null, writableDb); ContentValues cv = fillUpdateData(activity, i); cv.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); activity.localActivityId = writableDb.insertOrThrow(TABLE_NAME, null, cv); } } else { activity.localActivityId = writableDb.insertOrThrow( TABLE_NAME, null, fillUpdateData(activity, null)); } if (activity.localActivityId < 0) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } if(statement != null) { statement.close(); statement = null; } return ServiceStatus.SUCCESS; } /** * Deletes all activities from the table. * * @param flag Can be a bitmap of: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * <li>NULL - to delete all activities</li> * </ul> * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteActivities(final Integer flag, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteActivities()"); try { String whereClause = null; if (flag != null) { whereClause = Field.FLAG + "&" + flag; } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } public static ServiceStatus fetchNativeIdsFromLocalContactId(List<Integer > nativeItemIdList, final long localContactId, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNativeIdsFromLocalContactId()"); Cursor cursor = null; try { cursor = readableDb.rawQuery("SELECT " + Field.NATIVE_ITEM_ID + " FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + " = " + localContactId, null); while (cursor.moveToNext()) { nativeItemIdList.add(cursor.getInt(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchNativeIdsFromLocalContactId()" + "Unable to fetch list of NativeIds from localcontactId", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Deletes specified timeline activity from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivity(final Context context, final TimelineSummaryItem timelineItem, final SQLiteDatabase writableDb, final SQLiteDatabase readableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteTimelineActivity()"); try { List<Integer > nativeItemIdList = new ArrayList<Integer>() ; //Delete from Native Database if(timelineItem.mNativeThreadId != null) { //Sms Native Database final Uri smsUri = Uri.parse("content://sms"); context.getContentResolver().delete(smsUri , "thread_id=" + timelineItem.mNativeThreadId, null); //Mms Native Database final Uri mmsUri = Uri.parse("content://mms"); context.getContentResolver().delete(mmsUri, "thread_id=" + timelineItem.mNativeThreadId, null); } else { // For CallLogs if(timelineItem.mLocalContactId != null) { fetchNativeIdsFromLocalContactId(nativeItemIdList, timelineItem.mLocalContactId, readableDb); if(nativeItemIdList.size() > 0) { //CallLog Native Database for(Integer nativeItemId : nativeItemIdList) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + nativeItemId, null); } } } else { if(timelineItem.mContactAddress != null) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls.NUMBER + "=" + timelineItem.mContactAddress, null); } } } String whereClause = null; //Delete from People Client database if(timelineItem.mLocalContactId != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } else if(timelineItem.mContactAddress != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } /** * Deletes all the timeline activities for a particular contact from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivities(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.deleteTimelineActivities()"); Cursor cursor = null; try { TimelineNativeTypes[] typeList = null; - TimelineSummaryItem timelineItem = null; //For CallLog Timeline - typeList = new TimelineNativeTypes[] { - TimelineNativeTypes.CallLog - }; - cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, - latestTimelineItem.mContactName, typeList, null, readableDb); - - if(cursor != null && cursor.getCount() > 0) { - cursor.moveToFirst(); - timelineItem = getTimelineData(cursor); - if(timelineItem != null) { - deleteTimelineActivity(context, timelineItem, writableDb, readableDb); - } - } + typeList = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; + deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); //For SmsLog/MmsLog Timeline - typeList = new TimelineNativeTypes[] { - TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog - }; - cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, - latestTimelineItem.mContactName, typeList, null, readableDb); - - if(cursor != null && cursor.getCount() > 0) { - cursor.moveToFirst(); - timelineItem = getTimelineData(cursor); - if(timelineItem != null) { - deleteTimelineActivity(context, timelineItem, writableDb, readableDb); - } - } - + typeList = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; + deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); + //For ChatLog Timeline - typeList = new TimelineNativeTypes[] { - TimelineNativeTypes.ChatLog - }; - cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, - latestTimelineItem.mContactName, typeList, null, readableDb); - - if(cursor != null && cursor.getCount() > 0) { - cursor.moveToFirst(); - timelineItem = getTimelineData(cursor); - if(timelineItem != null) { - deleteTimelineActivity(context, timelineItem, writableDb, readableDb); - } - } + typeList = new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }; + deleteTimeLineActivitiesByType(context, latestTimelineItem, writableDb, readableDb, typeList); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } + /** + * + * Deletes one or more timeline items for a contact for the given types. + * + * @param context The app context to open the transaction in. + * @param latestTimelineItem The latest item from the timeline to get the belonging contact from. + * @param writableDb The database to write to. + * @param readableDb The database to read from. + * @param typeList The list of types to delete timeline events for. + * + * @return Returns a success if the transaction was successful, an error otherwise. + * + */ + private static ServiceStatus deleteTimeLineActivitiesByType(Context context, TimelineSummaryItem latestTimelineItem, + SQLiteDatabase writableDb, SQLiteDatabase readableDb, + TimelineNativeTypes[] typeList) { + Cursor cursor = null; + TimelineSummaryItem timelineItem = null; + + try { + cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, + latestTimelineItem.mContactName, typeList, null, readableDb); + + if(cursor != null && cursor.getCount() > 0) { + cursor.moveToFirst(); + timelineItem = getTimelineData(cursor); + if(timelineItem != null) { + return deleteTimelineActivity(context, timelineItem, writableDb, readableDb); + } + } + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + + "Unable to delete timeline activities", e); + return ServiceStatus.ERROR_DATABASE_CORRUPT; + } finally { + if(cursor != null) { + CloseUtils.close(cursor); + } + } + + return ServiceStatus.SUCCESS; + } + + /** * Fetches timeline events grouped by local contact ID, name or contact * address. Events returned will be in reverse-chronological order. If a * native type list is provided the result will be filtered by the list. * * @param minTimeStamp Only timeline events from this date will be returned * @param nativeTypes A list of native types to filter the result, or null * to return all. * @param readableDb Readable SQLite database * @return A cursor containing the result. The * {@link #getTimelineData(Cursor)} method should be used for * reading the cursor. */ public static Cursor fetchTimelineEventList(final Long minTimeStamp, final TimelineNativeTypes[] nativeTypes, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchTimelineEventList() " + "minTimeStamp[" + minTimeStamp + "]"); try { int andVal = 1; String typesQuery = " AND "; if (nativeTypes != null) { typesQuery += DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), nativeTypes, "OR"); typesQuery += " AND "; andVal = 2; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + Field.TIMESTAMP + " > " + minTimeStamp + " AND (" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") ORDER BY " + Field.TIMESTAMP + " DESC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchLastUpdateTime() " + "Unable to fetch timeline event list", e); return null; } } /** * Adds a list of timeline events to the database. Each event is grouped by * contact and grouped by contact + native type. * * @param itemList List of timeline events * @param isCallLog true to group all activities with call logs, false to * group with messaging * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error */ public static ServiceStatus addTimelineEvents( final ArrayList<TimelineSummaryItem> itemList, final boolean isCallLog, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addTimelineEvents()"); TimelineNativeTypes[] activityTypes; if (isCallLog) { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; } else { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; } for (TimelineSummaryItem item : itemList) { try { writableDb.beginTransaction(); if (findNativeActivity(item, writableDb)) { continue; } int latestStatusVal = 0; - if (item.mContactName != null || item.mLocalContactId != null) { + if (!TextUtils.isEmpty(item.mContactName) || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, activityTypes, writableDb); - } else if ((item.mContactAddress == null) && (item.mLocalContactId == null)) { // unknown contact + } else { // unknown contact latestStatusVal = 1; } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM); values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } item.mLocalActivityId = writableDb.insert(TABLE_NAME, null, values); if (item.mLocalActivityId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "ERROR_DATABASE_CORRUPT - Unable to add " + "timeline list to database"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /** * The method returns the ROW_ID i.e. the INTEGER PRIMARY KEY AUTOINCREMENT * field value for the inserted row, i.e. LOCAL_ID. * * @param item TimelineSummaryItem. * @param read - TRUE if the chat message is outgoing or gets into the * timeline history view for a contact with LocalContactId. * @param writableDb Writable SQLite database. * @return LocalContactID or -1 if the row was not inserted. */ public static long addChatTimelineEvent(final TimelineSummaryItem item, final boolean read, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addChatTimelineEvent()"); try { writableDb.beginTransaction(); int latestStatusVal = 0; if (item.mContactName != null || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }, writableDb); } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); /** Chat message body. **/ values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); if (read) { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); } else { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | 0); } values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); /** Conversation ID for chat message. **/ // values.put(Field.URI.toString(), item.conversationId); // 0 for incoming, 1 for outgoing if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } final long itemId = writableDb.insert(TABLE_NAME, null, values); if (itemId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() - " + "Unable to add timeline list to database, index<0:" + itemId); return -1; } writableDb.setTransactionSuccessful(); return itemId; } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return -1; } finally { writableDb.endTransaction(); } } /** * Clears the grouping of an activity in the database, if the given activity * is newer. This is so that only the latest activity is returned for a * particular group. Each activity is associated with two groups: * <ol> * <li>All group - Grouped by contact only</li> * <li>Native group - Grouped by contact and native type (call log or * messaging)</li> * </ol> * The group to be removed is determined by the activityTypes parameter. * Grouping must also work for timeline events that are not associated with * a contact. The following fields are used to do identify a contact for the * grouping (in order of priority): * <ol> * <li>localContactId - If it not null</li> * <li>name - If this is a valid telephone number, the match will be done to * ensure that the same phone number written in different ways will be * included in the group. See {@link #fetchNameWhereClause(Long, String)} * for more information.</li> * </ol> * * @param localContactId Local contact Id or NULL if the activity is not * associated with a contact. * @param name Name of contact or contact address (telephone number, email, * etc). * @param newUpdateTime The time that the given activity has occurred * @param flag Bitmap of types including: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * </ul> * @param activityTypes A list of native types to include in the grouping. * Currently, only two groups are supported (see above). If this * parameter is null the contact will be added to the * "all group", otherwise the contact is added to the native * group. * @param writableDb Writable SQLite database * @return The latest contact status value which should be added to the * current activities grouping. */ private static int removeContactGroup(final Long localContactId, final String name, final Long newUpdateTime, final int flag, final TimelineNativeTypes[] activityTypes, final SQLiteDatabase writableDb) { String whereClause = ""; int andVal = 1; if (activityTypes != null) { whereClause = DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), activityTypes, "OR"); whereClause += " AND "; andVal = 2; } String nameWhereClause = fetchNameWhereClause(localContactId, name); if (nameWhereClause == null) { return 0; } whereClause += nameWhereClause; Long prevTime = null; Long prevLocalId = null; Integer prevLatestContactStatus = null; Cursor cursor = null; try { cursor = writableDb.rawQuery("SELECT " + Field.TIMESTAMP + "," + Field.LOCAL_ACTIVITY_ID + "," + Field.LATEST_CONTACT_STATUS + " FROM " + TABLE_NAME + " WHERE " + whereClause + " AND " + "(" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") AND (" + Field.FLAG + "&" + flag + ") ORDER BY " + Field.TIMESTAMP + " DESC", null); if (cursor.moveToFirst()) { prevTime = cursor.getLong(0); prevLocalId = cursor.getLong(1); prevLatestContactStatus = cursor.getInt(2); } } catch (SQLException e) { return 0; } finally { CloseUtils.close(cursor); } if (prevTime != null && newUpdateTime != null) { if (newUpdateTime >= prevTime) { ContentValues cv = new ContentValues(); cv.put(Field.LATEST_CONTACT_STATUS.toString(), prevLatestContactStatus & (~andVal)); if (writableDb.update(TABLE_NAME, cv, Field.LOCAL_ACTIVITY_ID + "=" + prevLocalId, null) <= 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "Unable to update timeline as the latest"); return 0; } return andVal; } else { return 0; } } return andVal; } /** * Checks if an activity exists in the database. * * @param item The native SMS item to check against our client activities DB table. * * @return true if the activity was found, false otherwise * */ private static boolean findNativeActivity(TimelineSummaryItem item, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.findNativeActivity()"); Cursor cursor = null; boolean result = false; try { final String[] args = { Integer.toString(item.mNativeItemId), Integer.toString(item.mNativeItemType), Long.toString(item.mTimestamp) }; cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_ID + "=? AND " + Field.NATIVE_ITEM_TYPE + "=?" + " AND " + Field.TIMESTAMP + "=?", args); if (cursor.moveToFirst()) { result = true; } } finally { CloseUtils.close(cursor); } return result; } /** * Returns a string which can be added to the where clause in an SQL query * on the activities table, to filter the result for a specific contact or * name. The clause will prioritise in the following way: * <ol> * <li>Use localContactId - If it not null</li> * <li>Use name - If this is a valid telephone number, the match will be * done to ensure that the same phone number written in different ways will * be included in the group. * </ol> * * @param localContactId The local contact ID, or null if the contact does * not exist in the People database. * @param name A string containing the name, or a telephone number/email * identifying the contact. * @return The where clause string */ private static String fetchNameWhereClause(final Long localContactId, final String name) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNameWhereClause()"); if (localContactId != null) { return Field.LOCAL_CONTACT_ID + "=" + localContactId; } if (name == null) { - return "1=1"; + return "1=1"; // we need to return something that evaluates to true as this method is called after a SQL AND-operator } final String searchName = DatabaseUtils.sqlEscapeString(name); if (PhoneNumberUtils.isWellFormedSmsAddress(name)) { return "(PHONE_NUMBERS_EQUAL(" + Field.CONTACT_NAME + "," + searchName + ") OR "+ Field.CONTACT_NAME + "=" + searchName+")"; } else { return Field.CONTACT_NAME + "=" + searchName; } } /** * Returns the timeline summary data from the current location of the given * cursor. The cursor can be obtained using * {@link #fetchTimelineEventList(Long, TimelineNativeTypes[], * SQLiteDatabase)} or * {@link #fetchTimelineEventsForContact(Long, Long, String, * TimelineNativeTypes[], SQLiteDatabase)}. * * @param cursor Cursor in the required position. * @return A filled out TimelineSummaryItem object */ public static TimelineSummaryItem getTimelineData(final Cursor cursor) { DatabaseHelper.trace(false, "DatabaseHelper.getTimelineData()"); TimelineSummaryItem item = new TimelineSummaryItem(); item.mLocalActivityId = SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); item.mTimestamp = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); item.mContactName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); if (!cursor.isNull( cursor.getColumnIndex(Field.CONTACT_AVATAR_URL.toString()))) { item.mHasAvatar = true; } item.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); item.mTitle = SqlUtils.setString(cursor, Field.TITLE.toString()); item.mDescription = SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); item.mContactNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); item.mNativeItemType = SqlUtils.setInt(cursor, Field.NATIVE_ITEM_TYPE.toString(), null); item.mNativeItemId = SqlUtils.setInt(cursor, Field.NATIVE_ITEM_ID.toString(), null); item.mType = SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); item.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); item.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); item.mNativeThreadId = SqlUtils.setInt(cursor, Field.NATIVE_THREAD_ID.toString(), null); item.mContactAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); item.mIncoming = SqlUtils.setTimelineSummaryItemType(cursor, Field.INCOMING.toString()); return item; } /** * Fetches timeline events for a specific contact identified by local * contact ID, name or address. Events returned will be in * reverse-chronological order. If a native type list is provided the result * will be filtered by the list. * * @param timeStamp Only events from this time will be returned * @param localContactId The local contact ID if the contact is in the * People database, or null. * @param name The name or address of the contact (required if local contact * ID is NULL). * @param nativeTypes A list of required native types to filter the result, * or null to return all timeline events for the contact. * @param readableDb Readable SQLite database * @param networkName The name of the network the contacts belongs to * (required in order to provide appropriate chat messages * filtering) If the parameter is null messages from all networks * will be returned. The values are the * SocialNetwork.VODAFONE.toString(), * SocialNetwork.GOOGLE.toString(), or * SocialNetwork.MICROSOFT.toString() results. * @return The cursor that can be read using * {@link #getTimelineData(Cursor)}. */ public static Cursor fetchTimelineEventsForContact(final Long timeStamp, final Long localContactId, final String name, final TimelineNativeTypes[] nativeTypes, final String networkName, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "fetchTimelineEventsForContact()"); try { String typesQuery = " AND "; if (nativeTypes.length > 0) { StringBuffer typesQueryBuffer = new StringBuffer(); typesQueryBuffer.append(" AND ("); for (int i = 0; i < nativeTypes.length; i++) { final TimelineNativeTypes type = nativeTypes[i]; typesQueryBuffer.append(Field.NATIVE_ITEM_TYPE + "=" + type.ordinal()); if (i < nativeTypes.length - 1) { typesQueryBuffer.append(" OR "); } } typesQueryBuffer.append(") AND "); typesQuery = typesQueryBuffer.toString(); } /** Filter by account. **/ String networkQuery = ""; String queryNetworkName = networkName; if (queryNetworkName != null) { if (queryNetworkName.equals(SocialNetwork.PC.toString()) || queryNetworkName.equals( SocialNetwork.MOBILE.toString())) { queryNetworkName = SocialNetwork.VODAFONE.toString(); } networkQuery = Field.CONTACT_NETWORK + "='" + queryNetworkName + "' AND "; } String whereAppend; if (localContactId == null) { whereAppend = Field.LOCAL_CONTACT_ID + " IS NULL AND " + fetchNameWhereClause(localContactId, name); if (whereAppend == null) { return null; } } else { whereAppend = Field.LOCAL_CONTACT_ID + "=" + localContactId; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + networkQuery + whereAppend + " ORDER BY " + Field.TIMESTAMP + " ASC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchTimelineEventsForContact() " + "Unable to fetch timeline event for contact list", e); return null; } } /** * Mark the chat timeline events for a given contact as read. * * @param localContactId Local contact ID. * @param networkName Name of the SNS. * @param writableDb Writable SQLite reference. * @return Number of rows affected by database update. */ public static int markChatTimelineEventsForContactAsRead( final Long localContactId, final String networkName, final SQLiteDatabase writableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "fetchTimelineEventsForContact()"); ContentValues values = new ContentValues(); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); String networkQuery = ""; if (networkName != null) { networkQuery = " AND (" + Field.CONTACT_NETWORK + "='" + networkName + "')"; } final String where = Field.LOCAL_CONTACT_ID + "=" + localContactId + " AND " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" /** * If the network is null, set all messages as read for this * contact. */ + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")" + networkQuery; return writableDb.update(TABLE_NAME, values, where, null); } /** * Returns the latest status event for a contact with the given local contact id. * * @param local contact id Server contact ID. * @param readableDb Readable SQLite database. * @return The ActivityItem representing the latest status event for given local contact id, * or null if nothing was found. */ public static ActivityItem getLatestStatusForContact(final long localContactId, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper getLatestStatusForContact"); Cursor cursor = null; try { StringBuffer query = StringBufferPool.getStringBuffer(SQLKeys.SELECT); query.append(getFullQueryList()).append(SQLKeys.FROM).append(TABLE_NAME).append(SQLKeys.WHERE). append(Field.FLAG).append('&').append(ActivityItem.STATUS_ITEM).append(SQLKeys.AND). append(Field.LOCAL_CONTACT_ID).append('=').append(localContactId). append(" ORDER BY ").append(Field.TIMESTAMP).append(" DESC"); cursor = readableDb.rawQuery(StringBufferPool.toStringThenRelease(query), null); if (cursor.moveToFirst()) { final ActivityItem activityItem = new ActivityItem(); final ActivityContact activityContact = new ActivityContact(); ActivitiesTable.getQueryData(cursor, activityItem, activityContact); return activityItem; } } finally { CloseUtils.close(cursor); cursor = null; } return null; } /** * Updates timeline when a new contact is added to the People database. * Updates all timeline events that are not associated with a contact and * have a phone number that matches the oldName parameter. * * @param oldName The telephone number (since is the name of an activity * that is not associated with a contact) * @param newName The new name * @param newLocalContactId The local Contact Id for the added contact. * @param newContactId The server Contact Id for the added contact (or null * if the contact has not yet been synced). * @param witeableDb Writable SQLite database */ public static void updateTimelineContactNameAndId(final String oldName, final String newName, final Long newLocalContactId, final Long newContactId, final SQLiteDatabase witeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "updateTimelineContactNameAndId()"); try { ContentValues values = new ContentValues(); if (newName != null) { values.put(Field.CONTACT_NAME.toString(), newName); } else { LogUtils.logE("updateTimelineContactNameAndId() " + "newName should never be null"); } if (newLocalContactId != null) { values.put(Field.LOCAL_CONTACT_ID.toString(), newLocalContactId); } else { LogUtils.logE("updateTimelineContactNameAndId() " + "newLocalContactId should never be null"); } if (newContactId != null) { values.put(Field.CONTACT_ID.toString(), newContactId); } else { /** * newContactId will be null if adding a contact from the UI. */ LogUtils.logI("updateTimelineContactNameAndId() " + "newContactId is null"); /** * We haven't got server Contact it, it means it haven't been * synced yet. */ } String name = ""; if (oldName != null) { name = oldName; LogUtils.logW("ActivitiesTable." + "updateTimelineContactNameAndId() oldName is NULL"); } String[] args = { "2", name }; String whereClause = Field.LOCAL_CONTACT_ID + " IS NULL AND " + Field.FLAG + "=? AND PHONE_NUMBERS_EQUAL(" + Field.CONTACT_ADDRESS + ",?)"; witeableDb.update(TABLE_NAME, values, whereClause, args); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.updateTimelineContactNameAndId() " + "Unable update table", e); throw e; } } /** * Updates the timeline when a contact name is modified in the database. * * @param newName The new name. * @param localContactId Local contact Id which was modified. * @param witeableDb Writable SQLite database */ public static void updateTimelineContactNameAndId(final String newName, final Long localContactId, final SQLiteDatabase witeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "updateTimelineContactNameAndId()"); if (newName == null || localContactId == null) { LogUtils.logE("updateTimelineContactNameAndId() newName or " + "localContactId == null newName(" + newName + ") localContactId(" + localContactId + ")"); return; } try { ContentValues values = new ContentValues(); Long cId = ContactsTable.fetchServerId(localContactId, witeableDb); values.put(Field.CONTACT_NAME.toString(), newName); if (cId != null) { values.put(Field.CONTACT_ID.toString(), cId); } String[] args = { localContactId.toString() }; String whereClause = Field.LOCAL_CONTACT_ID + "=?"; witeableDb.update(TABLE_NAME, values, whereClause, args); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.updateTimelineContactNameAndId()" + " Unable update table", e); } } /** * Updates the timeline entries in the activities table to remove deleted * contact info. * * @param localContactId - the contact id that has been deleted * @param writeableDb - reference to the database */ public static void removeTimelineContactData(final Long localContactId, final SQLiteDatabase writeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "removeTimelineContactData()"); if (localContactId == null) { LogUtils.logE("removeTimelineContactData() localContactId == null " + "localContactId(" + localContactId + ")"); return; } try { //Remove all the Chat Entries removeChatTimelineForContact(localContactId, writeableDb); String[] args = { localContactId.toString() }; String query = "UPDATE " + TABLE_NAME + " SET " + Field.LOCAL_CONTACT_ID + "=NULL, " + Field.CONTACT_ID + "=NULL, " + Field.CONTACT_NAME + "=" + Field.CONTACT_ADDRESS + " WHERE " + Field.LOCAL_CONTACT_ID + "=? AND (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")"; writeableDb.execSQL(query, args); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.removeTimelineContactData() Unable " + "to update table: \n", e); } } /** * Removes all the items from the chat timeline for the given contact. * * @param localContactId Given contact ID. * @param writeableDb Writable SQLite database. */ private static void removeChatTimelineForContact( final Long localContactId, final SQLiteDatabase writeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "removeChatTimelineForContact()"); if (localContactId == null || (localContactId == -1)) { LogUtils.logE("removeChatTimelineForContact() localContactId == " + "null " + "localContactId(" + localContactId + ")"); return; } final String query = Field.LOCAL_CONTACT_ID + "=" + localContactId + " AND (" + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + ")"; try { writeableDb.delete(TABLE_NAME, query, null); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.removeChatTimelineForContact() " + "Unable to update table", e); } } /** * Removes items from the chat timeline that are not for the given contact. * * @param localContactId Given contact ID. * @param writeableDb Writable SQLite database. */ public static void removeChatTimelineExceptForContact( final Long localContactId, final SQLiteDatabase writeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "removeTimelineContactData()"); if (localContactId == null || (localContactId == -1)) { LogUtils.logE("removeTimelineContactData() localContactId == null " + "localContactId(" + localContactId + ")"); return; } try { final long olderThan = System.currentTimeMillis() - Settings.HISTORY_IS_WEEK_LONG; final String query = Field.LOCAL_CONTACT_ID + "!=" + localContactId + " AND (" + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + ") AND (" + Field.TIMESTAMP + "<" + olderThan + ")"; writeableDb.delete(TABLE_NAME, query, null); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.removeTimelineContactData() " + "Unable to update table", e); } } /*** * Returns the number of users have currently have unread chat messages. * * @param readableDb Reference to a readable database. * @return Number of users with unread chat messages. */ public static int getNumberOfUnreadChatUsers( final SQLiteDatabase readableDb) { final String query = "SELECT " + Field.LOCAL_CONTACT_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" /** * This condition below means the timeline is not yet marked * as READ. */ + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; Cursor cursor = null; try { cursor = readableDb.rawQuery(query, null); ArrayList<Long> ids = new ArrayList<Long>(); Long id = null; while (cursor.moveToNext()) { id = cursor.getLong(0); if (!ids.contains(id)) { ids.add(id); } } return ids.size(); } finally { CloseUtils.close(cursor); } } /*** * Returns the number of unread chat messages. * * @param readableDb Reference to a readable database. * @return Number of unread chat messages. */ public static int getNumberOfUnreadChatMessages( final SQLiteDatabase readableDb) { final String query = "SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; Cursor cursor = null; try { cursor = readableDb.rawQuery(query, null); return cursor.getCount(); } finally { CloseUtils.close(cursor); } } /*** * Returns the number of unread chat messages for this contact besides this * network. * * @param localContactId Given contact ID. * @param network SNS name. * @param readableDb Reference to a readable database. * @return Number of unread chat messages. */ public static int getNumberOfUnreadChatMessagesForContactAndNetwork( final long localContactId, final String network, final SQLiteDatabase readableDb) { final String query = "SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ") AND (" + Field.LOCAL_CONTACT_ID + "=" + localContactId + ") AND (" + Field.CONTACT_NETWORK + "!=\"" + network + "\")"; Cursor cursor = null; try { cursor = readableDb.rawQuery(query, null); return cursor.getCount(); } finally { CloseUtils.close(cursor); } } /*** * Returns the newest unread chat message. * * @param readableDb Reference to a readable database. * @return TimelineSummaryItem of the newest unread chat message, or NULL if * none are found. */
360/360-Engine-for-Android
510edfd612b6c8c3c9b5e3947201529c6984e6ac
fixed activities table to handle showing of timeline items with unknown numbers
diff --git a/src/com/vodafone360/people/database/tables/ActivitiesTable.java b/src/com/vodafone360/people/database/tables/ActivitiesTable.java index 81a9614..3554dbc 100644 --- a/src/com/vodafone360/people/database/tables/ActivitiesTable.java +++ b/src/com/vodafone360/people/database/tables/ActivitiesTable.java @@ -449,1320 +449,1324 @@ public abstract class ActivitiesTable { SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); activityContact.mNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); activityContact.mAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); activityContact.mAvatarUrl = SqlUtils.setString(cursor, Field.CONTACT_AVATAR_URL.toString()); } /*** * Provides a ContentValues object that can be used to update the table. * * @param item The source activity item * @param contactIdx The index of the contact to use for the update, or null * to exclude contact specific information. * @return ContentValues for use in an SQL update or insert. * @note Items that are NULL will be not modified in the database. */ private static ContentValues fillUpdateData(final ActivityItem item, final Integer contactIdx) { DatabaseHelper.trace(false, "DatabaseHelper.fillUpdateData()"); ContentValues activityItemValues = new ContentValues(); ActivityContact ac = null; if (contactIdx != null) { ac = item.contactList.get(contactIdx); } activityItemValues.put(Field.ACTIVITY_ID.toString(), item.activityId); activityItemValues.put(Field.TIMESTAMP.toString(), item.time); if (item.type != null) { activityItemValues.put(Field.TYPE.toString(), item.type.getTypeCode()); } if (item.uri != null) { activityItemValues.put(Field.URI.toString(), item.uri); } /** TODO: Not sure if we need this. **/ // activityItemValues.put(Field.INCOMING.toString(), false); activityItemValues.put(Field.TITLE.toString(), item.title); activityItemValues.put(Field.DESCRIPTION.toString(), item.description); if (item.previewUrl != null) { activityItemValues.put(Field.PREVIEW_URL.toString(), item.previewUrl); } if (item.store != null) { activityItemValues.put(Field.STORE.toString(), item.store); } if (item.activityFlags != null) { activityItemValues.put(Field.FLAG.toString(), item.activityFlags); } if (item.parentActivity != null) { activityItemValues.put(Field.PARENT_ACTIVITY.toString(), item.parentActivity); } if (item.hasChildren != null) { activityItemValues.put(Field.HAS_CHILDREN.toString(), item.hasChildren); } if (item.visibilityFlags != null) { activityItemValues.put(Field.VISIBILITY.toString(), item.visibilityFlags); } if (ac != null) { activityItemValues.put(Field.CONTACT_ID.toString(), ac.mContactId); activityItemValues.put(Field.USER_ID.toString(), ac.mUserId); activityItemValues.put(Field.CONTACT_NAME.toString(), ac.mName); activityItemValues.put(Field.LOCAL_CONTACT_ID.toString(), ac.mLocalContactId); if (ac.mNetwork != null) { activityItemValues.put(Field.CONTACT_NETWORK.toString(), ac.mNetwork); } if (ac.mAddress != null) { activityItemValues.put(Field.CONTACT_ADDRESS.toString(), ac.mAddress); } if (ac.mAvatarUrl != null) { activityItemValues.put(Field.CONTACT_AVATAR_URL.toString(), ac.mAvatarUrl); } } return activityItemValues; } /** * Fetches a list of status items from the given time stamp. * * @param timeStamp Time stamp in milliseconds * @param readableDb Readable SQLite database * @return A cursor (use one of the {@link #getQueryData} methods to read * the data) */ public static Cursor fetchStatusEventList(final long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchStatusEventList()"); return readableDb.rawQuery("SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + " & " + ActivityItem.STATUS_ITEM + ") AND " + Field.TIMESTAMP + " > " + timeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); } /** * Returns a list of activity IDs already synced, in reverse chronological * order Fetches from the given timestamp. * * @param actIdList An empty list which will be filled with the result * @param timeStamp The time stamp to start the fetch * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus fetchActivitiesIds(final List<Long> actIdList, final Long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchActivitiesIds()"); Cursor cursor = null; try { long queryTimeStamp; if (timeStamp != null) { queryTimeStamp = timeStamp; } else { queryTimeStamp = 0; } cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.TIMESTAMP + " >= " + queryTimeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); while (cursor.moveToNext()) { actIdList.add(cursor.getLong(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchActivitiesIds()" + "Unable to fetch group list", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Adds a list of activities to table. The activities added will be grouped * in the database, based on local contact Id, name or contact address (see * {@link #removeContactGroup(Long, String, Long, int, * TimelineNativeTypes[], SQLiteDatabase)} * for more information on how the grouping works. * * @param actList The list of activities * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus addActivities(final List<ActivityItem> actList, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addActivities()"); SQLiteStatement statement = ContactsTable.fetchLocalFromServerIdStatement(writableDb); for (ActivityItem activity : actList) { try { writableDb.beginTransaction(); if (activity.contactList != null) { int clistSize = activity.contactList.size(); for (int i = 0; i < clistSize; i++) { final ActivityContact activityContact = activity.contactList.get(i); activityContact.mLocalContactId = ContactsTable.fetchLocalFromServerId( activityContact.mContactId, statement); int latestStatusVal = removeContactGroup( activityContact.mLocalContactId, activityContact.mName, activity.time, activity.activityFlags, null, writableDb); ContentValues cv = fillUpdateData(activity, i); cv.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); activity.localActivityId = writableDb.insertOrThrow(TABLE_NAME, null, cv); } } else { activity.localActivityId = writableDb.insertOrThrow( TABLE_NAME, null, fillUpdateData(activity, null)); } if (activity.localActivityId < 0) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } if(statement != null) { statement.close(); statement = null; } return ServiceStatus.SUCCESS; } /** * Deletes all activities from the table. * * @param flag Can be a bitmap of: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * <li>NULL - to delete all activities</li> * </ul> * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteActivities(final Integer flag, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteActivities()"); try { String whereClause = null; if (flag != null) { whereClause = Field.FLAG + "&" + flag; } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } public static ServiceStatus fetchNativeIdsFromLocalContactId(List<Integer > nativeItemIdList, final long localContactId, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNativeIdsFromLocalContactId()"); Cursor cursor = null; try { cursor = readableDb.rawQuery("SELECT " + Field.NATIVE_ITEM_ID + " FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + " = " + localContactId, null); while (cursor.moveToNext()) { nativeItemIdList.add(cursor.getInt(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchNativeIdsFromLocalContactId()" + "Unable to fetch list of NativeIds from localcontactId", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Deletes specified timeline activity from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivity(final Context context, final TimelineSummaryItem timelineItem, final SQLiteDatabase writableDb, final SQLiteDatabase readableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteTimelineActivity()"); try { List<Integer > nativeItemIdList = new ArrayList<Integer>() ; //Delete from Native Database if(timelineItem.mNativeThreadId != null) { //Sms Native Database final Uri smsUri = Uri.parse("content://sms"); context.getContentResolver().delete(smsUri , "thread_id=" + timelineItem.mNativeThreadId, null); //Mms Native Database final Uri mmsUri = Uri.parse("content://mms"); context.getContentResolver().delete(mmsUri, "thread_id=" + timelineItem.mNativeThreadId, null); } else { // For CallLogs if(timelineItem.mLocalContactId != null) { fetchNativeIdsFromLocalContactId(nativeItemIdList, timelineItem.mLocalContactId, readableDb); if(nativeItemIdList.size() > 0) { //CallLog Native Database for(Integer nativeItemId : nativeItemIdList) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + nativeItemId, null); } } } else { if(timelineItem.mContactAddress != null) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls.NUMBER + "=" + timelineItem.mContactAddress, null); } } } String whereClause = null; //Delete from People Client database if(timelineItem.mLocalContactId != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } else if(timelineItem.mContactAddress != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } /** * Deletes all the timeline activities for a particular contact from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivities(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.deleteTimelineActivities()"); Cursor cursor = null; try { TimelineNativeTypes[] typeList = null; TimelineSummaryItem timelineItem = null; //For CallLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } //For SmsLog/MmsLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } //For ChatLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }; cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * Fetches timeline events grouped by local contact ID, name or contact * address. Events returned will be in reverse-chronological order. If a * native type list is provided the result will be filtered by the list. * * @param minTimeStamp Only timeline events from this date will be returned * @param nativeTypes A list of native types to filter the result, or null * to return all. * @param readableDb Readable SQLite database * @return A cursor containing the result. The * {@link #getTimelineData(Cursor)} method should be used for * reading the cursor. */ public static Cursor fetchTimelineEventList(final Long minTimeStamp, final TimelineNativeTypes[] nativeTypes, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchTimelineEventList() " + "minTimeStamp[" + minTimeStamp + "]"); try { int andVal = 1; String typesQuery = " AND "; if (nativeTypes != null) { typesQuery += DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), nativeTypes, "OR"); typesQuery += " AND "; andVal = 2; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + Field.TIMESTAMP + " > " + minTimeStamp + " AND (" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") ORDER BY " + Field.TIMESTAMP + " DESC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchLastUpdateTime() " + "Unable to fetch timeline event list", e); return null; } } /** * Adds a list of timeline events to the database. Each event is grouped by * contact and grouped by contact + native type. * * @param itemList List of timeline events * @param isCallLog true to group all activities with call logs, false to * group with messaging * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error */ public static ServiceStatus addTimelineEvents( final ArrayList<TimelineSummaryItem> itemList, final boolean isCallLog, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addTimelineEvents()"); TimelineNativeTypes[] activityTypes; if (isCallLog) { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; } else { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; } for (TimelineSummaryItem item : itemList) { try { writableDb.beginTransaction(); if (findNativeActivity(item, writableDb)) { continue; } int latestStatusVal = 0; if (item.mContactName != null || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, activityTypes, writableDb); + } else if ((item.mContactAddress == null) && (item.mLocalContactId == null)) { // unknown contact + latestStatusVal = 1; } + + ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM); values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } item.mLocalActivityId = writableDb.insert(TABLE_NAME, null, values); if (item.mLocalActivityId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "ERROR_DATABASE_CORRUPT - Unable to add " + "timeline list to database"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /** * The method returns the ROW_ID i.e. the INTEGER PRIMARY KEY AUTOINCREMENT * field value for the inserted row, i.e. LOCAL_ID. * * @param item TimelineSummaryItem. * @param read - TRUE if the chat message is outgoing or gets into the * timeline history view for a contact with LocalContactId. * @param writableDb Writable SQLite database. * @return LocalContactID or -1 if the row was not inserted. */ public static long addChatTimelineEvent(final TimelineSummaryItem item, final boolean read, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addChatTimelineEvent()"); try { writableDb.beginTransaction(); int latestStatusVal = 0; if (item.mContactName != null || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }, writableDb); } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); /** Chat message body. **/ values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); if (read) { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); } else { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | 0); } values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); /** Conversation ID for chat message. **/ // values.put(Field.URI.toString(), item.conversationId); // 0 for incoming, 1 for outgoing if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } final long itemId = writableDb.insert(TABLE_NAME, null, values); if (itemId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() - " + "Unable to add timeline list to database, index<0:" + itemId); return -1; } writableDb.setTransactionSuccessful(); return itemId; } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return -1; } finally { writableDb.endTransaction(); } } /** * Clears the grouping of an activity in the database, if the given activity * is newer. This is so that only the latest activity is returned for a * particular group. Each activity is associated with two groups: * <ol> * <li>All group - Grouped by contact only</li> * <li>Native group - Grouped by contact and native type (call log or * messaging)</li> * </ol> * The group to be removed is determined by the activityTypes parameter. * Grouping must also work for timeline events that are not associated with * a contact. The following fields are used to do identify a contact for the * grouping (in order of priority): * <ol> * <li>localContactId - If it not null</li> * <li>name - If this is a valid telephone number, the match will be done to * ensure that the same phone number written in different ways will be * included in the group. See {@link #fetchNameWhereClause(Long, String)} * for more information.</li> * </ol> * * @param localContactId Local contact Id or NULL if the activity is not * associated with a contact. * @param name Name of contact or contact address (telephone number, email, * etc). * @param newUpdateTime The time that the given activity has occurred * @param flag Bitmap of types including: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * </ul> * @param activityTypes A list of native types to include in the grouping. * Currently, only two groups are supported (see above). If this * parameter is null the contact will be added to the * "all group", otherwise the contact is added to the native * group. * @param writableDb Writable SQLite database * @return The latest contact status value which should be added to the * current activities grouping. */ private static int removeContactGroup(final Long localContactId, final String name, final Long newUpdateTime, final int flag, final TimelineNativeTypes[] activityTypes, final SQLiteDatabase writableDb) { String whereClause = ""; int andVal = 1; if (activityTypes != null) { whereClause = DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), activityTypes, "OR"); whereClause += " AND "; andVal = 2; } String nameWhereClause = fetchNameWhereClause(localContactId, name); if (nameWhereClause == null) { return 0; } whereClause += nameWhereClause; Long prevTime = null; Long prevLocalId = null; Integer prevLatestContactStatus = null; Cursor cursor = null; try { cursor = writableDb.rawQuery("SELECT " + Field.TIMESTAMP + "," + Field.LOCAL_ACTIVITY_ID + "," + Field.LATEST_CONTACT_STATUS + " FROM " + TABLE_NAME + " WHERE " + whereClause + " AND " + "(" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") AND (" + Field.FLAG + "&" + flag + ") ORDER BY " + Field.TIMESTAMP + " DESC", null); if (cursor.moveToFirst()) { prevTime = cursor.getLong(0); prevLocalId = cursor.getLong(1); prevLatestContactStatus = cursor.getInt(2); } } catch (SQLException e) { return 0; } finally { CloseUtils.close(cursor); } if (prevTime != null && newUpdateTime != null) { if (newUpdateTime >= prevTime) { ContentValues cv = new ContentValues(); cv.put(Field.LATEST_CONTACT_STATUS.toString(), prevLatestContactStatus & (~andVal)); if (writableDb.update(TABLE_NAME, cv, Field.LOCAL_ACTIVITY_ID + "=" + prevLocalId, null) <= 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "Unable to update timeline as the latest"); return 0; } return andVal; } else { return 0; } } return andVal; } /** * Checks if an activity exists in the database. * * @param item The native SMS item to check against our client activities DB table. * * @return true if the activity was found, false otherwise * */ private static boolean findNativeActivity(TimelineSummaryItem item, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.findNativeActivity()"); Cursor cursor = null; boolean result = false; try { final String[] args = { Integer.toString(item.mNativeItemId), Integer.toString(item.mNativeItemType), Long.toString(item.mTimestamp) }; cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_ID + "=? AND " + Field.NATIVE_ITEM_TYPE + "=?" + " AND " + Field.TIMESTAMP + "=?", args); if (cursor.moveToFirst()) { result = true; } } finally { CloseUtils.close(cursor); } return result; } /** * Returns a string which can be added to the where clause in an SQL query * on the activities table, to filter the result for a specific contact or * name. The clause will prioritise in the following way: * <ol> * <li>Use localContactId - If it not null</li> * <li>Use name - If this is a valid telephone number, the match will be * done to ensure that the same phone number written in different ways will * be included in the group. * </ol> * * @param localContactId The local contact ID, or null if the contact does * not exist in the People database. * @param name A string containing the name, or a telephone number/email * identifying the contact. * @return The where clause string */ private static String fetchNameWhereClause(final Long localContactId, final String name) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNameWhereClause()"); if (localContactId != null) { return Field.LOCAL_CONTACT_ID + "=" + localContactId; } if (name == null) { - return null; + return "1=1"; } final String searchName = DatabaseUtils.sqlEscapeString(name); if (PhoneNumberUtils.isWellFormedSmsAddress(name)) { return "(PHONE_NUMBERS_EQUAL(" + Field.CONTACT_NAME + "," + searchName + ") OR "+ Field.CONTACT_NAME + "=" + searchName+")"; } else { return Field.CONTACT_NAME + "=" + searchName; } } /** * Returns the timeline summary data from the current location of the given * cursor. The cursor can be obtained using * {@link #fetchTimelineEventList(Long, TimelineNativeTypes[], * SQLiteDatabase)} or * {@link #fetchTimelineEventsForContact(Long, Long, String, * TimelineNativeTypes[], SQLiteDatabase)}. * * @param cursor Cursor in the required position. * @return A filled out TimelineSummaryItem object */ public static TimelineSummaryItem getTimelineData(final Cursor cursor) { DatabaseHelper.trace(false, "DatabaseHelper.getTimelineData()"); TimelineSummaryItem item = new TimelineSummaryItem(); item.mLocalActivityId = SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); item.mTimestamp = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); item.mContactName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); if (!cursor.isNull( cursor.getColumnIndex(Field.CONTACT_AVATAR_URL.toString()))) { item.mHasAvatar = true; } item.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); item.mTitle = SqlUtils.setString(cursor, Field.TITLE.toString()); item.mDescription = SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); item.mContactNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); item.mNativeItemType = SqlUtils.setInt(cursor, Field.NATIVE_ITEM_TYPE.toString(), null); item.mNativeItemId = SqlUtils.setInt(cursor, Field.NATIVE_ITEM_ID.toString(), null); item.mType = SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); item.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); item.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); item.mNativeThreadId = SqlUtils.setInt(cursor, Field.NATIVE_THREAD_ID.toString(), null); item.mContactAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); item.mIncoming = SqlUtils.setTimelineSummaryItemType(cursor, Field.INCOMING.toString()); return item; } /** * Fetches timeline events for a specific contact identified by local * contact ID, name or address. Events returned will be in * reverse-chronological order. If a native type list is provided the result * will be filtered by the list. * * @param timeStamp Only events from this time will be returned * @param localContactId The local contact ID if the contact is in the * People database, or null. * @param name The name or address of the contact (required if local contact * ID is NULL). * @param nativeTypes A list of required native types to filter the result, * or null to return all timeline events for the contact. * @param readableDb Readable SQLite database * @param networkName The name of the network the contacts belongs to * (required in order to provide appropriate chat messages * filtering) If the parameter is null messages from all networks * will be returned. The values are the * SocialNetwork.VODAFONE.toString(), * SocialNetwork.GOOGLE.toString(), or * SocialNetwork.MICROSOFT.toString() results. * @return The cursor that can be read using * {@link #getTimelineData(Cursor)}. */ public static Cursor fetchTimelineEventsForContact(final Long timeStamp, final Long localContactId, final String name, final TimelineNativeTypes[] nativeTypes, final String networkName, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "fetchTimelineEventsForContact()"); try { String typesQuery = " AND "; if (nativeTypes.length > 0) { StringBuffer typesQueryBuffer = new StringBuffer(); typesQueryBuffer.append(" AND ("); for (int i = 0; i < nativeTypes.length; i++) { final TimelineNativeTypes type = nativeTypes[i]; typesQueryBuffer.append(Field.NATIVE_ITEM_TYPE + "=" + type.ordinal()); if (i < nativeTypes.length - 1) { typesQueryBuffer.append(" OR "); } } typesQueryBuffer.append(") AND "); typesQuery = typesQueryBuffer.toString(); } /** Filter by account. **/ String networkQuery = ""; String queryNetworkName = networkName; if (queryNetworkName != null) { if (queryNetworkName.equals(SocialNetwork.PC.toString()) || queryNetworkName.equals( SocialNetwork.MOBILE.toString())) { queryNetworkName = SocialNetwork.VODAFONE.toString(); } networkQuery = Field.CONTACT_NETWORK + "='" + queryNetworkName + "' AND "; } String whereAppend; if (localContactId == null) { whereAppend = Field.LOCAL_CONTACT_ID + " IS NULL AND " + fetchNameWhereClause(localContactId, name); if (whereAppend == null) { return null; } } else { whereAppend = Field.LOCAL_CONTACT_ID + "=" + localContactId; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + networkQuery + whereAppend + " ORDER BY " + Field.TIMESTAMP + " ASC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchTimelineEventsForContact() " + "Unable to fetch timeline event for contact list", e); return null; } } /** * Mark the chat timeline events for a given contact as read. * * @param localContactId Local contact ID. * @param networkName Name of the SNS. * @param writableDb Writable SQLite reference. * @return Number of rows affected by database update. */ public static int markChatTimelineEventsForContactAsRead( final Long localContactId, final String networkName, final SQLiteDatabase writableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "fetchTimelineEventsForContact()"); ContentValues values = new ContentValues(); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); String networkQuery = ""; if (networkName != null) { networkQuery = " AND (" + Field.CONTACT_NETWORK + "='" + networkName + "')"; } final String where = Field.LOCAL_CONTACT_ID + "=" + localContactId + " AND " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" /** * If the network is null, set all messages as read for this * contact. */ + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")" + networkQuery; return writableDb.update(TABLE_NAME, values, where, null); } /** * Returns the latest status event for a contact with the given local contact id. * * @param local contact id Server contact ID. * @param readableDb Readable SQLite database. * @return The ActivityItem representing the latest status event for given local contact id, * or null if nothing was found. */ public static ActivityItem getLatestStatusForContact(final long localContactId, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper getLatestStatusForContact"); Cursor cursor = null; try { StringBuffer query = StringBufferPool.getStringBuffer(SQLKeys.SELECT); query.append(getFullQueryList()).append(SQLKeys.FROM).append(TABLE_NAME).append(SQLKeys.WHERE). append(Field.FLAG).append('&').append(ActivityItem.STATUS_ITEM).append(SQLKeys.AND). append(Field.LOCAL_CONTACT_ID).append('=').append(localContactId). append(" ORDER BY ").append(Field.TIMESTAMP).append(" DESC"); cursor = readableDb.rawQuery(StringBufferPool.toStringThenRelease(query), null); if (cursor.moveToFirst()) { final ActivityItem activityItem = new ActivityItem(); final ActivityContact activityContact = new ActivityContact(); ActivitiesTable.getQueryData(cursor, activityItem, activityContact); return activityItem; } } finally { CloseUtils.close(cursor); cursor = null; } return null; } /** * Updates timeline when a new contact is added to the People database. * Updates all timeline events that are not associated with a contact and * have a phone number that matches the oldName parameter. * * @param oldName The telephone number (since is the name of an activity * that is not associated with a contact) * @param newName The new name * @param newLocalContactId The local Contact Id for the added contact. * @param newContactId The server Contact Id for the added contact (or null * if the contact has not yet been synced). * @param witeableDb Writable SQLite database */ public static void updateTimelineContactNameAndId(final String oldName, final String newName, final Long newLocalContactId, final Long newContactId, final SQLiteDatabase witeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "updateTimelineContactNameAndId()"); try { ContentValues values = new ContentValues(); if (newName != null) { values.put(Field.CONTACT_NAME.toString(), newName); } else { LogUtils.logE("updateTimelineContactNameAndId() " + "newName should never be null"); } if (newLocalContactId != null) { values.put(Field.LOCAL_CONTACT_ID.toString(), newLocalContactId); } else { LogUtils.logE("updateTimelineContactNameAndId() " + "newLocalContactId should never be null"); } if (newContactId != null) { values.put(Field.CONTACT_ID.toString(), newContactId); } else { /** * newContactId will be null if adding a contact from the UI. */ LogUtils.logI("updateTimelineContactNameAndId() " + "newContactId is null"); /** * We haven't got server Contact it, it means it haven't been * synced yet. */ } String name = ""; if (oldName != null) { name = oldName; LogUtils.logW("ActivitiesTable." + "updateTimelineContactNameAndId() oldName is NULL"); } String[] args = { "2", name }; String whereClause = Field.LOCAL_CONTACT_ID + " IS NULL AND " + Field.FLAG + "=? AND PHONE_NUMBERS_EQUAL(" + Field.CONTACT_ADDRESS + ",?)"; witeableDb.update(TABLE_NAME, values, whereClause, args); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.updateTimelineContactNameAndId() " + "Unable update table", e); throw e; } } /** * Updates the timeline when a contact name is modified in the database. * * @param newName The new name. * @param localContactId Local contact Id which was modified. * @param witeableDb Writable SQLite database */ public static void updateTimelineContactNameAndId(final String newName, final Long localContactId, final SQLiteDatabase witeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "updateTimelineContactNameAndId()"); if (newName == null || localContactId == null) { LogUtils.logE("updateTimelineContactNameAndId() newName or " + "localContactId == null newName(" + newName + ") localContactId(" + localContactId + ")"); return; } try { ContentValues values = new ContentValues(); Long cId = ContactsTable.fetchServerId(localContactId, witeableDb); values.put(Field.CONTACT_NAME.toString(), newName); if (cId != null) { values.put(Field.CONTACT_ID.toString(), cId); } String[] args = { localContactId.toString() }; String whereClause = Field.LOCAL_CONTACT_ID + "=?"; witeableDb.update(TABLE_NAME, values, whereClause, args); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.updateTimelineContactNameAndId()" + " Unable update table", e); } } /** * Updates the timeline entries in the activities table to remove deleted * contact info. * * @param localContactId - the contact id that has been deleted * @param writeableDb - reference to the database */ public static void removeTimelineContactData(final Long localContactId, final SQLiteDatabase writeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "removeTimelineContactData()"); if (localContactId == null) { LogUtils.logE("removeTimelineContactData() localContactId == null " + "localContactId(" + localContactId + ")"); return; } try { //Remove all the Chat Entries removeChatTimelineForContact(localContactId, writeableDb); String[] args = { localContactId.toString() }; String query = "UPDATE " + TABLE_NAME + " SET " + Field.LOCAL_CONTACT_ID + "=NULL, " + Field.CONTACT_ID + "=NULL, " + Field.CONTACT_NAME + "=" + Field.CONTACT_ADDRESS + " WHERE " + Field.LOCAL_CONTACT_ID + "=? AND (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")"; writeableDb.execSQL(query, args); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.removeTimelineContactData() Unable " + "to update table: \n", e); } } /** * Removes all the items from the chat timeline for the given contact. * * @param localContactId Given contact ID. * @param writeableDb Writable SQLite database. */ private static void removeChatTimelineForContact( final Long localContactId, final SQLiteDatabase writeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "removeChatTimelineForContact()"); if (localContactId == null || (localContactId == -1)) { LogUtils.logE("removeChatTimelineForContact() localContactId == " + "null " + "localContactId(" + localContactId + ")"); return; } final String query = Field.LOCAL_CONTACT_ID + "=" + localContactId + " AND (" + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + ")"; try { writeableDb.delete(TABLE_NAME, query, null); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.removeChatTimelineForContact() " + "Unable to update table", e); } } /** * Removes items from the chat timeline that are not for the given contact. * * @param localContactId Given contact ID. * @param writeableDb Writable SQLite database. */ public static void removeChatTimelineExceptForContact( final Long localContactId, final SQLiteDatabase writeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "removeTimelineContactData()"); if (localContactId == null || (localContactId == -1)) { LogUtils.logE("removeTimelineContactData() localContactId == null " + "localContactId(" + localContactId + ")"); return; } try { final long olderThan = System.currentTimeMillis() - Settings.HISTORY_IS_WEEK_LONG; final String query = Field.LOCAL_CONTACT_ID + "!=" + localContactId + " AND (" + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + ") AND (" + Field.TIMESTAMP + "<" + olderThan + ")"; writeableDb.delete(TABLE_NAME, query, null); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.removeTimelineContactData() " + "Unable to update table", e); } } /*** * Returns the number of users have currently have unread chat messages. * * @param readableDb Reference to a readable database. * @return Number of users with unread chat messages. */ public static int getNumberOfUnreadChatUsers( final SQLiteDatabase readableDb) { final String query = "SELECT " + Field.LOCAL_CONTACT_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" /** * This condition below means the timeline is not yet marked * as READ. */ + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; Cursor cursor = null; try { cursor = readableDb.rawQuery(query, null); ArrayList<Long> ids = new ArrayList<Long>(); Long id = null; while (cursor.moveToNext()) { id = cursor.getLong(0); if (!ids.contains(id)) { ids.add(id); } } return ids.size(); } finally { CloseUtils.close(cursor); } } /*** * Returns the number of unread chat messages. * * @param readableDb Reference to a readable database. * @return Number of unread chat messages. */ public static int getNumberOfUnreadChatMessages( final SQLiteDatabase readableDb) { final String query = "SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; Cursor cursor = null; try { cursor = readableDb.rawQuery(query, null); return cursor.getCount(); } finally { CloseUtils.close(cursor); } } /*** * Returns the number of unread chat messages for this contact besides this * network. * * @param localContactId Given contact ID. * @param network SNS name. * @param readableDb Reference to a readable database. * @return Number of unread chat messages. */ public static int getNumberOfUnreadChatMessagesForContactAndNetwork( final long localContactId, final String network, final SQLiteDatabase readableDb) { final String query = "SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ") AND (" + Field.LOCAL_CONTACT_ID + "=" + localContactId + ") AND (" + Field.CONTACT_NETWORK + "!=\"" + network + "\")"; Cursor cursor = null; try { cursor = readableDb.rawQuery(query, null); return cursor.getCount(); } finally { CloseUtils.close(cursor); } } /*** * Returns the newest unread chat message. * * @param readableDb Reference to a readable database. * @return TimelineSummaryItem of the newest unread chat message, or NULL if * none are found. */
360/360-Engine-for-Android
0c43cbbcd90e84bf46da6f5bd601ea2a89045c11
Adding some buffering again to MicroHessianInput
diff --git a/src/com/caucho/hessian/micro/MicroHessianInput.java b/src/com/caucho/hessian/micro/MicroHessianInput.java index 8a9f391..c7170a8 100644 --- a/src/com/caucho/hessian/micro/MicroHessianInput.java +++ b/src/com/caucho/hessian/micro/MicroHessianInput.java @@ -1,535 +1,550 @@ /* * Copyright (c) 2001-2006 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Scott Ferguson * */ package com.caucho.hessian.micro; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Hashtable; import java.util.Vector; import com.vodafone360.people.utils.LogUtils; +import com.vodafone360.people.utils.ResetableBufferedInputStream; /** * Input stream for Hessian requests, compatible with microedition Java. It only * uses classes and types available to J2ME. In particular, it does not have any * support for the &lt;double> type. * <p> * MicroHessianInput does not depend on any classes other than in J2ME, so it * can be extracted independently into a smaller package. * <p> * MicroHessianInput is unbuffered, so any client needs to provide its own * buffering. * * <pre> * InputStream is = ...; // from http connection * MicroHessianInput in = new MicroHessianInput(is); * String value; * in.startReply(); // read reply header * value = in.readString(); // read string value * in.completeReply(); // read reply footer * </pre> */ public class MicroHessianInput { protected DataInputStream is; - + /** + * Using a special BufferedInputstream, which is constructed once and then reused. + * Saves a lot of GC time. + */ + protected ResetableBufferedInputStream rbis; + /** Using fast but not thread safe StringBuilder for constructing strings */ private StringBuilder mStringBuilder = new StringBuilder(255); /** * Creates a new Hessian input stream, initialized with an underlying input * stream. * * @param is the underlying input stream. */ public MicroHessianInput(InputStream is) { init(is); } /** * Creates an uninitialized Hessian input stream. */ public MicroHessianInput() { } /** * Initialize the hessian stream with the underlying input stream. */ public void init(InputStream is) { + //use the reusable resetablebufferedinputstream here + if (rbis==null){ + // create it only once + rbis=new ResetableBufferedInputStream(is,2048); + }else{ + // then reuse it + rbis.reset(is); + } + this.is = new DataInputStream(is); } /** * Starts reading the reply * <p> * A successful completion will have a single value: * * <pre> * r x01 x00 * </pre> */ public void startReply() throws IOException { int tag = is.read(); if (tag != 'r') throw protocolException("expected hessian reply"); // remove some bits from the input stream is.skip(2); } /** * Completes reading the call * <p> * A successful completion will have a single value: * * <pre> * z * </pre> */ public void completeReply() throws IOException { int tag = is.read(); if (tag != 'z') throw protocolException("expected end of reply"); } /** * Reads a boolean * * <pre> * T * F * </pre> */ public boolean readBoolean() throws IOException { int tag = is.read(); switch (tag) { case 'T': return true; case 'F': return false; default: throw expect("boolean", tag); } } /** * Reads an integer * * <pre> * I b32 b24 b16 b8 * </pre> */ public int readInt() throws IOException { int tag = is.read(); return readInt(tag); } public int readInt(int tag) throws IOException { if (tag != 'I') throw expect("integer", tag); return is.readInt(); } /** * Reads a long * * <pre> * L b64 b56 b48 b40 b32 b24 b16 b8 * </pre> */ public long readLong() throws IOException { int tag = is.read(); return readLong(tag); } private long readLong(int tag) throws IOException { if (tag != 'L') throw protocolException("expected long"); return is.readLong(); } /** * Reads a date. * * <pre> * T b64 b56 b48 b40 b32 b24 b16 b8 * </pre> */ public long readUTCDate() throws IOException { int tag = is.read(); if (tag != 'd') throw protocolException("expected date"); return is.readLong(); } /** * Reads a byte array * * @return byte[] array extracted from Hessian stream, NULL if 'N' specified * in data. * @throws IOException. */ public byte[] readBytes() throws IOException { int tag = is.read(); return readBytes(tag); } private byte[] readBytes(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'B') throw expect("bytes", tag); int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; byte[] bytes = new byte[len]; is.read(bytes); return bytes; } /** * Reads an arbitrary object the input stream. */ public Object readObject(Class<?> expectedClass) throws IOException { int tag = is.read(); switch (tag) { case 'N': return null; case 'T': return true; case 'F': return false; case 'I': { return readInt(tag); } case 'L': { return readLong(tag); } case 'd': { return new Date(is.readLong()); } case 'S': case 'X': { int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; return readStringImpl(len); } case 'B': { return readBytes(tag); } default: throw new IOException("unknown code:" + (char)tag); } } public Vector<Object> readVector() throws IOException { int tag = is.read(); return readVector(tag); } private Vector<Object> readVector(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'V') throw expect("vector", tag); Vector<Object> v = new Vector<Object>(); Object o = decodeTag(); if (o instanceof End) return v; if (o instanceof Type) o = decodeTag(); if (o instanceof End) return v; int len = 0; if (o instanceof Integer) { len = ((Integer)o); o = decodeTag(); } for (int i = 0; i < len; i++) { v.addElement(o); o = decodeTag(); } return v; } public Fault readFault() throws IOException { decodeTag(); int tag = is.read(); if (tag == 'S') { return new Fault(readString(tag)); } return null; } public Object decodeTag() throws IOException { int tag = is.read(); // HessianUtils.printTagValue(tag); return decodeType(tag); } public Object decodeType(int tag) throws IOException { // LogUtils.logD("HessianDecoder.decodeType() tag["+tag+"]"); switch (tag) { case 't': // tag is.skip(2); Type type = new Type(); return type; case 'l': // length int i = 0; i += (is.read() << 24); i += (is.read() << 16); i += (is.read() << 8); i += is.read(); Integer len = i; return len; case 'z': // end End end = new End(); return end; case 'N': // null return null; case 'r': // reply startReply should have retrieved this? return null; case 'M': return readHashMap(tag); case 'V': // array/Vector return readVector(tag); case 'T': // boolean true return true; case 'F': // boolean false return false; case 'I': // integer return readInt(tag); case 'L': // read long return readLong(tag); case 'd': // UTC date return null; case 'S': // String return readString(tag); case 'B': // read byte array return readBytes(tag); case 'f': return readFault(); default: LogUtils.logE("HessianDecoder.decodeType() Unknown type"); return null; } } /** * Reads a string * * <pre> * S b16 b8 string value * </pre> */ public String readString() throws IOException { int tag = is.read(); return readString(tag); } private String readString(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'S') throw expect("string", tag); int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; return readStringImpl(len); } /** * Reads a string from the underlying stream. */ private String readStringImpl(int length) throws IOException { // reset the StringBuilder. Recycling is better than making always a // new one. mStringBuilder.setLength(0); for (int i = 0; i < length; i++) { int ch = is.read(); if (ch < 0x80) mStringBuilder.append((char)ch); else if ((ch & 0xe0) == 0xc0) { int ch1 = is.read(); int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f); mStringBuilder.append((char)v); } else if ((ch & 0xf0) == 0xe0) { int ch1 = is.read(); int ch2 = is.read(); int v = ((ch & 0x0f) << 12) + ((ch1 & 0x3f) << 6) + (ch2 & 0x3f); mStringBuilder.append((char)v); } else if ((ch & 0xff) >= 0xf0 && (ch & 0xff) <= 0xf4) { // UTF-4 final byte[] b = new byte[4]; b[0] = (byte)ch; b[1] = (byte)is.read(); b[2] = (byte)is.read(); b[3] = (byte)is.read(); mStringBuilder.append(new String(b, "utf-8")); i++; } else throw new IOException("bad utf-8 encoding"); } return mStringBuilder.substring(0, mStringBuilder.length()); } public Hashtable<String, Object> readHashMap() throws IOException { // read map type int tag = is.read(); return readHashMap(tag); } public Hashtable<String, Object> readHashMap(int tag) throws IOException { // read map type if (tag == 'N') return null; if (tag != 'M') throw expect("map", tag); Hashtable<String, Object> ht = new Hashtable<String, Object>(); Object obj = decodeTag(); if (obj instanceof Type) { // get following object obj = decodeTag(); } Object obj1 = null; while (obj != null && !(obj instanceof End)) // 'z' = list-end { obj1 = decodeTag(); ht.put(obj.toString(), obj1); obj = decodeTag(); } return ht; } protected IOException expect(String expect, int ch) { if (ch < 0) return protocolException("expected " + expect + " at end of file"); else return protocolException("expected " + expect + " at " + (char)ch); } protected IOException protocolException(String message) { return new IOException(message); } /** * Place-holder class for End tag 'z' */ private static class End { } /** * Place-holder class for Type tag 't' */ private static class Type { } /** * Class holding error string returned during Hessian decoding */ public static class Fault { private String mErrString = null; private Fault(String eString) { mErrString = eString; } public String errString() { return mErrString; } } } diff --git a/src/com/vodafone360/people/utils/ResetableBufferedInputStream.java b/src/com/vodafone360/people/utils/ResetableBufferedInputStream.java new file mode 100644 index 0000000..f13ee13 --- /dev/null +++ b/src/com/vodafone360/people/utils/ResetableBufferedInputStream.java @@ -0,0 +1,80 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the Common Development + * and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at + * src/com/vodafone360/people/VODAFONE.LICENSE.txt or + * http://github.com/360/360-Engine-for-Android + * See the License for the specific language governing permissions and + * limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each file and + * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. + * If applicable, add the following below this CDDL HEADER, with the fields + * enclosed by brackets "[]" replaced with your own identifying information: + * Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + * + * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. + * Use is subject to license terms. + */ + +package com.vodafone360.people.utils; +import java.io.BufferedInputStream; +import java.io.InputStream; + +/** + * Extended BufferedInputStream with a possibility to reset it and reuse it. + * This way one can avoid GC issues that happen to come with the BufferedInputStream + * which allways has to be recreated for new use. + * @author admin + * + */ +public class ResetableBufferedInputStream extends BufferedInputStream { + + /** + * This method takes a new InputStream and sets all counts and markers back to initial values. + * The buffer will not be touched so it can be reused + * @param in New InputStream to use + */ + public void reset(InputStream in){ + this.in=in; + count=0; + marklimit=0; + markpos = -1; + pos=0; + } + + /** + * Constructs a new {@code ResetableBufferedInputStream} on the {@link InputStream} + * {@code in}. The default buffer size (8 KB) is allocated and all reads + * can now be filtered through this stream. + * + * @param in + * the InputStream the buffer reads from. + */ + public ResetableBufferedInputStream(InputStream in) { + super(in); + } + + /** + * Constructs a new {@code ResetableBufferedInputStream} on the {@link InputStream} + * {@code in}. The buffer size is specified by the parameter {@code size} + * and all reads are now filtered through this stream. + * + * @param in + * the input stream the buffer reads from. + * @param size + * the size of buffer to allocate. + * @throws IllegalArgumentException + * if {@code size < 0}. + */ + public ResetableBufferedInputStream(InputStream in, int size) { + super(in,size); + } + +}
360/360-Engine-for-Android
a279fe59f1f1a7bd862e5ad992f1c85e70f26f9a
PAND-1985: Fixed the login after removeUserData
diff --git a/src/com/vodafone360/people/engine/login/LoginEngine.java b/src/com/vodafone360/people/engine/login/LoginEngine.java index d0c092b..655c2ee 100644 --- a/src/com/vodafone360/people/engine/login/LoginEngine.java +++ b/src/com/vodafone360/people/engine/login/LoginEngine.java @@ -895,526 +895,526 @@ public class LoginEngine extends BaseEngine { } /** * Clears the session and registration complete information so that the user * will need to manually login again to use the now+ services. Does not * currently send a request to the server to log out. */ private void startLogout() { LogUtils.logD("LoginEngine.startLogout()"); setRegistrationComplete(false); setActivatedSession(null); completeUiRequest(ServiceStatus.SUCCESS, null); } /** * Clears the session and registration complete information so that the user * will need to manually login again to use the now+ services. Does not * currently send a request to the server to log out. */ public final void logoutAndRemoveUser() { LogUtils.logD("LoginEngine.startLogout()"); addUiRemoveUserDataRequest(); LoginPreferences.clearPreferencesFile(mContext); mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UNSOLICITED_GO_TO_LANDING_PAGE, null); } /** * Retries to log the user in based on credential information stored in the * database. * * @return true if the login process was able to start */ public boolean retryAutoLogin() { LogUtils.logD("LoginEngine.retryAutoLogin()"); setActivatedSession(null); if (ServiceStatus.SUCCESS != mDb.fetchLogonCredentialsAndPublicKey(mLoginDetails, mPublicKey)) { LogUtils .logE("LoginEngine.retryAutoLogin() - Unable to fetch credentials from database"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } // AA: commented the condition out if (Settings.ENABLE_ACTIVATION) { // AA: the old version if (mCurrentSubscriberId == null || // !mCurrentSubscriberId.equals(mLoginDetails.mSubscriberId)) { // // logging off/fail will be done in another way according to bug 8288 if (mCurrentSubscriberId != null && !mCurrentSubscriberId.equals(mLoginDetails.mSubscriberId)) { LogUtils.logV("LoginEngine.retryAutoLogin() -" + " SIM card has changed or is missing (old subId = " + mLoginDetails.mSubscriberId + ", new subId = " + mCurrentSubscriberId + ")"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } // } if (mLoginDetails.mUsername == null || mLoginDetails.mPassword == null || mLoginDetails.mMobileNo == null) { LogUtils.logV("LoginEngine.retryAutoLogin() - Username, password " + "or mobile number are missing (old username = " + mLoginDetails.mUsername + ", mobile no = " + mLoginDetails.mMobileNo + ")"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } mAreLoginDetailsValid = true; if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { newState(State.LOGGED_OFF_WAITING_FOR_NETWORK); LogUtils.logV("LoginEngine.retryAutoLogin() - Internet connection down. " + "Will try again when connection is available"); return false; } newState(State.CREATING_SESSION_AUTO); if (!setReqId(Auth.getSessionByCredentials(this, mLoginDetails.mUsername, mLoginDetails.mPassword, null))) { return false; } return true; } /** * Helper function to set the registration complete flag and update the * database with the new state. * * @param value true if registration is completed */ private void setRegistrationComplete(boolean value) { LogUtils.logD("LoginEngine.setRegistrationComplete(" + value + ")"); if (value != mIsRegistrationComplete) { StateTable.setRegistrationComplete(value, mDb.getWritableDatabase()); mIsRegistrationComplete = value; if (mIsRegistrationComplete) { // Create NAB Account at this point (does nothing on 1.X // devices) final NativeContactsApi nabApi = NativeContactsApi.getInstance(); if (!nabApi.isPeopleAccountCreated()) { // TODO: React upon failure to create account nabApi.addPeopleAccount(LoginPreferences.getUsername()); } } } } /** * Changes the state of the engine. Also displays the login notification if * necessary. * * @param newState The new state */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("LoginEngine.newState: " + oldState + " -> " + mState); Intent intent = null; // Update notification switch (mState) { case LOGIN_FAILED_WRONG_CREDENTIALS: intent = new Intent(); intent.setAction(Intents.START_LOGIN_ACTIVITY); mContext.sendBroadcast(intent); setRegistrationComplete(false); break; // here should be no break case NOT_REGISTERED: case LOGIN_FAILED: intent = new Intent(); intent.setAction(Intents.LOGIN_FAILED); mContext.sendBroadcast(intent); setRegistrationComplete(false); // startLogout(); // mDb.removeUserData(); // sending user to login screen again // should be done by UI itself because // when it's done from here it cause problems when user tries to // login // giving wrong credentials, ui flow will be broken break; case LOGGED_OFF: case LOGGED_OFF_WAITING_FOR_NETWORK: case LOGGED_OFF_WAITING_FOR_RETRY: case LOGGED_ON: intent = new Intent(); intent.setAction(Intents.HIDE_LOGIN_NOTIFICATION); mContext.sendBroadcast(intent); break; default:// do nothing break; } // Update listeners with any state changes switch (mState) { case NOT_REGISTERED: case LOGIN_FAILED: case LOGIN_FAILED_WRONG_CREDENTIALS: case LOGGED_OFF: onLoginStateChanged(false); break; case LOGGED_ON: onLoginStateChanged(true); break; default: // do nothing. break; } } /** * Called when the engine transitions between the logged in and logged out * states. Notifies listeners. * * @param loggedIn true if the user is now logged in, false otherwise. */ private synchronized void onLoginStateChanged(boolean loggedIn) { LogUtils.logD("LoginEngine.onLoginStateChanged() Login state changed to " + (loggedIn ? "logged in." : "logged out.")); if (loggedIn == mCurrentLoginState) { return; } mCurrentLoginState = loggedIn; for (ILoginEventsListener listener : mEventsListener) { listener.onLoginStateChanged(loggedIn); } } /** * A helper function which determines which activity should be displayed * when the UI is loaded. * * @return true if landing page should be displayed, false otherwise */ public synchronized boolean getLoginRequired() { LogUtils.logD("LoginEngine.getLoginRequired() - " + !mIsRegistrationComplete); return !mIsRegistrationComplete; } /** * Retrieves the active comms session. * * @return The session or NULL if the user is logged out. */ public static AuthSessionHolder getSession() { return sActivatedSession; } /** * Helper function to store the new session in the database and inform * clients that the session has changed. * * @param session The new session or NULL if the user has logged off. */ public synchronized void setActivatedSession(AuthSessionHolder session) { LogUtils.logD("LoginEngine.setActivatedSession() session[" + session + "]"); sActivatedSession = session; if (session != null) { LogUtils.logD("LoginEngine.setActivatedSession() Login successful"); } else { LogUtils.logW("LoginEngine.setActivatedSession() " + "Login unsuccessful, the session is NULL"); } StateTable.setSession(session, mDb.getWritableDatabase()); } /** * Called when a response to the sign-up API is received. In case of success * sets a timeout value waiting for the activation SMS to arrive. * * @param data The received data */ private void handleSignUpResponse(List<BaseDataType> data) { ServiceStatus errorStatus = getResponseStatus(BaseDataType.CONTACT_DATA_TYPE, data); LogUtils.logD("LoginEngine.handleSignUpResponse() errorStatus[" + errorStatus.name() + "]"); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils.logD("LoginEngine.handleSignUpResponse() - Registration successful"); if (!Settings.ENABLE_ACTIVATION) { startGetSessionManual(); } else { // Now waiting for SMS... setTimeout(ACTIVATE_LOGIN_TIMEOUT); } // AA } else if (errorStatus == ServiceStatus.ERROR_INVALID_PUBLIC_KEY) { // start new key retrieval and make the new cycle getNewPublicKey(); } else { completeUiRequest(errorStatus, null); } } /** * Called when a response to the server fetch public key request is * received. Validates the response and stores the new public key details. * * @param mDataTypes Response data from server. */ private void handleNewPublicKeyResponse(List<BaseDataType> mDataTypes) { LogUtils.logD("LoginEngine.handleNewPublicKeyResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.PUBLIC_KEY_DETAILS_DATA_TYPE, mDataTypes); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils.logD("LoginEngine.handleNewPublicKeyResponse() - Succesfully retrieved"); // AA // 1. save to DB; save the flag that we aren't using default and // have to use one from DB // 2. start registration again mPublicKey = (PublicKeyDetails)mDataTypes.get(0); // done in startRegistrationProcessCrypted already // mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); startRegistrationProcessCrypted(mRegistrationDetails); } else { completeUiRequest(errorStatus, null); } } /** * Called when a response to the GetSessionByCredentials API is received * (manual login). In case of success, tries to activate the account using * the activation code received by SMS. * * @param data The received data */ private void handleCreateSessionManualResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleCreateSessionManualResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AUTH_SESSION_HOLDER_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS && (data.size() > 0)) { setActivatedSession((AuthSessionHolder)data.get(0)); startActivateAccount(); return; } completeUiRequest(errorStatus, null); } /** * Called when a response to the GetSessionByCredentials API is received * (auto login). In case of success, moves to the logged in state * * @param data The received data */ private void handleCreateSessionAutoResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleCreateSessionResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AUTH_SESSION_HOLDER_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { clearTimeout(); setActivatedSession((AuthSessionHolder)data.get(0)); newState(State.LOGGED_ON); } else { LogUtils.logE("LoginEngine.handleCreateSessionResponse() - Auto Login Failed Error " + errorStatus); // AA:the 1st retry failed, just go to the start page, // if (loginAttemptsRemaining() // && errorStatus!=ServiceStatus.ERROR_INVALID_PASSWORD) { // newState(State.LOGGED_OFF_WAITING_FOR_RETRY); // setTimeout(LOGIN_RETRY_TIME); // } else { // mAreLoginDetailsValid = false; if (errorStatus == ServiceStatus.ERROR_INVALID_PASSWORD) { mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED_WRONG_CREDENTIALS); } else { newState(State.LOGIN_FAILED); } // } } } /** * Called when a response to the RequestActivationCode API is received * (manual login). In case of success, tries to fetch a login session from * the server. * * @param data The received data */ private void handleRequestingActivationResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleRequestingActivationResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { // Now waiting for SMS... setTimeout(ACTIVATE_LOGIN_TIMEOUT); return; } completeUiRequest(errorStatus, null); } /** * Called when a response to the Activate API is received (manual login or * sign-up). In case of success, moves to the logged in state and completes * the manual login or sign-up request. * * @param data The received data */ private void handleActivateAccountResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleActivateAccountResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils .logD("LoginEngine.handleActivateAccountResponse: ** Mobile number activated **"); setRegistrationComplete(true); completeUiRequest(ServiceStatus.SUCCESS, null); return; } setActivatedSession(null); completeUiRequest(ServiceStatus.ERROR_ACCOUNT_ACTIVATION_FAILED, null); } /** * Called when a response to the GetTermsAndConditions, GetPrivacyStatement * and GetUsernameState APIs are received. In case of success, completes the * request and passes the response data to the UI. * * @param data The received data */ private void handleServerSimpleTextResponse(List<BaseDataType> data, State type) { LogUtils.logV("LoginEngine.handleServerSimpleTextResponse()"); ServiceStatus serviceStatus = getResponseStatus(BaseDataType.SIMPLE_TEXT_DATA_TYPE, data); String result = null; if (serviceStatus == ServiceStatus.SUCCESS) { result = ((SimpleText) data.get(0)).mValue.toString().replace( CARRIAGE_RETURN_CHARACTER, SPACE_CHARACTER); switch (type) { case FETCHING_TERMS_OF_SERVICE: LogUtils.logD("LoginEngine.handleServerSimpleTextResponse() Terms of Service"); ApplicationCache.setTermsOfService(result, mContext); break; case FETCHING_PRIVACY_STATEMENT: LogUtils.logD("LoginEngine.handleServerSimpleTextResponse() Privacy Statemet"); ApplicationCache.setPrivacyStatemet(result, mContext); break; case FETCHING_USERNAME_STATE: // TODO: Unused by UI. break; } } updateTermsState(serviceStatus, result); } /*** * Informs the UI to update any terms which are being shown on screen. * * @param serviceStatus Current ServiceStatus. * @param messageText Legacy call for old UI (TODO: remove after UI-Refresh * merge). NULL when combined with a ServiceStatus of * ERROR_COMMS, or contains the Privacy or Terms and Conditions * text to be displayed in the UI. */ private void updateTermsState(ServiceStatus serviceStatus, String messageText) { ApplicationCache.setTermsStatus(serviceStatus); /** Trigger UiAgent. **/ mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.TERMS_CHANGED_EVENT, null); /** Clear this request from the UI queue. **/ completeUiRequest(serviceStatus, messageText); } /** * A broadcast receiver which is used to receive notifications when a data * SMS arrives. */ private final BroadcastReceiver mEventReceiver = new BroadcastReceiver() { /** * Called when an SMS arrives. The activation code is extracted from the * given intent and the worker thread kicked. * * @param context Context from which the intent was broadcast * @param intent Will only process the SMS which the action is * {@link SmsBroadcastReceiver#ACTION_ACTIVATION_CODE}. */ @Override public void onReceive(Context context, Intent intent) { LogUtils.logD("LoginEngine.BroadcastReceiver.onReceive - Processing data sms"); if (intent.getAction().equals(SmsBroadcastReceiver.ACTION_ACTIVATION_CODE)) { String activationCode = intent.getStringExtra("code"); LogUtils .logD("LoginEngine.BroadcastReceiver.onReceive - Activation code Received: " + activationCode); synchronized (LoginEngine.this) { mActivationCode = activationCode; } mEventCallback.kickWorkerThread(); } } }; /** * Called when an SMS is received during sign-up or manual login. Starts * requesting a session from the server. */ private void handleSmsResponse() { LogUtils.logD("LoginEngine.handleSmsResponse(" + mActivationCode + ")"); clearTimeout(); startGetSessionManual(); } /** * Called by the base engine implementation whenever a UI request is * completed to do any necessary cleanup. We use it to restore our state to * a suitable value. */ @Override protected void onRequestComplete() { LogUtils.logD("LoginEngine.onRequestComplete()"); restoreLoginState(); } /** * Handles timeouts for SMS activation and auto login retries. */ protected synchronized void onTimeoutEvent() { LogUtils.logD("LoginEngine.onTimeoutEvent()"); switch (mState) { case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: completeUiRequest(ServiceStatus.ERROR_SMS_CODE_NOT_RECEIVED, null); break; case LOGGED_OFF_WAITING_FOR_RETRY: retryAutoLogin(); break; default: // do nothing. break; } } /** * Called by the framework before a remove user data operation takes place. * Initiates a suitable UI request which will kick the worker thread. */ @Override public void onReset() { // reset the engine as if it was just created super.onReset(); setRegistrationComplete(false); setActivatedSession(null); mState = State.NOT_INITIALISED; mRegistrationDetails = new RegistrationDetails(); mActivationCode = null; - mCurrentLoginState = false; + onLoginStateChanged(false); // Remove NAB Account at this point (does nothing on 1.X) NativeContactsApi.getInstance().removePeopleAccount(); } /** * Set 'dummy' auth session for test purposes only. * * @param session 'dummy' session supplied to LoginEngine */ public static void setTestSession(AuthSessionHolder session) { sActivatedSession = session; } }
360/360-Engine-for-Android
a73da82841fcc8d05a6f10d9cd5a2d650d1cf049
Fixed a bug in TCPConnectionThread
diff --git a/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java b/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java index ab6e747..74bf920 100644 --- a/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java +++ b/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java @@ -1,552 +1,551 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.transport.tcp; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import com.jcraft.jsch.jce.Random; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.DecoderThread; import com.vodafone360.people.service.transport.IConnection; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.TimeOutWatcher; import com.vodafone360.people.service.utils.hessian.HessianUtils; import com.vodafone360.people.utils.LogUtils; public class TcpConnectionThread implements Runnable, IConnection { private static final String RPG_FALLBACK_TCP_URL = "rpg.vodafone360.com"; private static final int RPG_DEFAULT_TCP_PORT = 9900; private static final int TCP_DEFAULT_TIMEOUT = 120000; private static final int ERROR_RETRY_INTERVAL = 10000; /** * If we have a connection error we try to restart after 60 seconds earliest */ private static final int CONNECTION_RESTART_INTERVAL = 60000; /** * The maximum number of retries to reestablish a connection until we sleep * until the user uses the UI or * Settings.TCP_RETRY_BROKEN_CONNECTION_INTERVAL calls another retry. */ private static final int MAX_NUMBER_RETRIES = 3; private static final int BYTE_ARRAY_OUTPUT_STREAM_SIZE = 2048; // bytes private Thread mThread; private RemoteService mService; private DecoderThread mDecoder; private boolean mConnectionShouldBeRunning; private boolean mDidCriticalErrorOccur; private BufferedInputStream mBufferedInputStream; private OutputStream mOs; private String mRpgTcpUrl; private int mRpgTcpPort; private Socket mSocket; private HeartbeatSenderThread mHeartbeatSender; private ResponseReaderThread mResponseReader; private long mLastErrorRetryTime, mLastErrorTimestamp; private ByteArrayOutputStream mBaos; public TcpConnectionThread(DecoderThread decoder, RemoteService service) { mSocket = new Socket(); mBaos = new ByteArrayOutputStream(BYTE_ARRAY_OUTPUT_STREAM_SIZE); mConnectionShouldBeRunning = true; mDecoder = decoder; mService = service; mLastErrorRetryTime = System.currentTimeMillis(); mLastErrorTimestamp = 0; try { mRpgTcpUrl = SettingsManager.getProperty(Settings.TCP_RPG_URL_KEY); mRpgTcpPort = Integer.parseInt(SettingsManager.getProperty(Settings.TCP_RPG_PORT_KEY)); } catch (Exception e) { HttpConnectionThread.logE("TcpConnectionThread()", "Could not parse URL or Port!", e); mRpgTcpUrl = RPG_FALLBACK_TCP_URL; mRpgTcpPort = RPG_DEFAULT_TCP_PORT; } } public void run() { QueueManager queueManager = QueueManager.getInstance(); mDidCriticalErrorOccur = false; try { // start the initial connection reconnectSocket(); HeartbeatSenderThread hbSender = new HeartbeatSenderThread(this, mService, mSocket); hbSender.setOutputStream(mOs); hbSender.sendHeartbeat(); hbSender = null; // TODO run this when BE supports it but keep HB in front! /* * ConnectionTester connTester = new ConnectionTester(mIs, mOs); if * (connTester.runTest()) { } else {} */ startHelperThreads(); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTED); } catch (IOException e) { haltAndRetryConnection(1); } catch (Exception e) { haltAndRetryConnection(1); } while (mConnectionShouldBeRunning) { try { if ((null != mOs) && (!mDidCriticalErrorOccur)) { List<Request> reqs = QueueManager.getInstance().getRpgRequests(); int reqNum = reqs.size(); List<Integer> reqIdList = null; if (Settings.ENABLED_TRANSPORT_TRACE || Settings.sEnableSuperExpensiveResponseFileLogging) { reqIdList = new ArrayList<Integer>(); } if (reqNum > 0) { mBaos.reset(); // batch payloads for (int i = 0; i < reqNum; i++) { Request req = reqs.get(i); if ((null == req) || (req.getAuthenticationType() == Request.USE_API)) { HttpConnectionThread.logV("TcpConnectionThread.run()", "Ignoring non-RPG method"); continue; } HttpConnectionThread.logD("TcpConnectionThread.run()", "Preparing [" + req.getRequestId() + "] for sending via RPG..."); req.setActive(true); req.writeToOutputStream(mBaos, true); if (req.isFireAndForget()) { // f-a-f, no response, // remove from queue HttpConnectionThread.logD("TcpConnectionThread.run()", "Removed F&F-Request: " + req.getRequestId()); queueManager.removeRequest(req.getRequestId()); } if (Settings.ENABLED_TRANSPORT_TRACE) { reqIdList.add(req.getRequestId()); HttpConnectionThread.logD("HttpConnectionThread.run()", "Req ID: " + req.getRequestId() + " <-> Auth: " + req.getAuth()); } } mBaos.flush(); byte[] payload = mBaos.toByteArray(); if (null != payload) { // log file containing response to SD card if (Settings.sEnableSuperExpensiveResponseFileLogging) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < reqIdList.size(); i++) { sb.append(reqIdList.get(i)); sb.append("_"); } LogUtils.logE("XXXXXXYYYXXXXXX Do not Remove this!"); LogUtils.logToFile(payload, "people_" +( reqIdList.size()>0?reqIdList.get(0):0)+ "_" + System.currentTimeMillis() + "_req_" + ((int)payload[2]) // message // type + ".txt"); } // end log file containing response to SD card if (Settings.ENABLED_TRANSPORT_TRACE) { Long userID = null; AuthSessionHolder auth = LoginEngine.getSession(); if (auth != null) { userID = auth.userID; } HttpConnectionThread.logI("TcpConnectionThread.run()", "\n > Sending request(s) " + reqIdList.toString() + ", for user ID " + userID + " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + HessianUtils.getInHessian( new ByteArrayInputStream(payload), true) + "\n "); } try { synchronized (mOs) { mOs.write(payload); mOs.flush(); } } catch (IOException ioe) { HttpConnectionThread.logE("TcpConnectionThread.run()", "Could not send request", ioe); notifyOfNetworkProblems(); } payload = null; } } } synchronized (this) { if (!mDidCriticalErrorOccur) { wait(); } else { while (mDidCriticalErrorOccur) { // loop until a retry // succeeds HttpConnectionThread.logI("TcpConnectionThread.run()", "Wait() for next connection retry has started."); wait(Settings.TCP_RETRY_BROKEN_CONNECTION_INTERVAL); if (mConnectionShouldBeRunning) { haltAndRetryConnection(1); } } } } } catch (Throwable t) { // FlurryAgent.onError("ERROR_TCP_THREAD_CRASHED", "run()", // "TcpConnectionThread"); HttpConnectionThread.logE("TcpConnectionThread.run()", "Unknown Error: ", t); } } stopConnection(); } /** * Gets notified whenever the user is using the UI. In this special case * whenever an error occured with the connection and this method was not * called a short time before */ @Override public void notifyOfUiActivity() { if (mDidCriticalErrorOccur) { if ((System.currentTimeMillis() - mLastErrorRetryTime) >= CONNECTION_RESTART_INTERVAL) { synchronized (this) { notify(); } mLastErrorRetryTime = System.currentTimeMillis(); } } } @Override public void notifyOfRegainedNetworkCoverage() { synchronized (this) { notify(); } } /** * Called back by the response reader, which should notice network problems * first */ protected void notifyOfNetworkProblems() { HttpConnectionThread.logE("TcpConnectionThread.notifyOfNetworkProblems()", "Houston, we have a network problem!", null); haltAndRetryConnection(1); } /** * Attempts to reconnect the socket if it has been closed for some reason. * * @throws IOException Thrown if something goes wrong while reconnecting the * socket. */ private void reconnectSocket() throws IOException { HttpConnectionThread.logI("TcpConnectionThread.reconnectSocket()", "Reconnecting Socket on " + mRpgTcpUrl + ":" + mRpgTcpPort); mSocket = null; mSocket = new Socket(); mSocket.connect(new InetSocketAddress(mRpgTcpUrl, mRpgTcpPort), TCP_DEFAULT_TIMEOUT); mBufferedInputStream = new BufferedInputStream(mSocket.getInputStream()); mOs = mSocket.getOutputStream(); HttpConnectionThread.logI("TcpConnectionThread.reconnectSocket()", "Socket started: " + mRpgTcpUrl + ":" + mRpgTcpPort); } /** * <p> * Retries to establish a network connection after a network error has * occurred or the coverage of the network was lost. The amount of retries * depends on MAX_NUMBER_RETRIES. * </p> * <p> * A new retry is carried out each time an exception is thrown until the * limit of retries has been reached. * </p> * * @param numberOfRetries The amount of retries carried out until the * connection is given up. */ synchronized private void haltAndRetryConnection(int numberOfRetries) { HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "\n \n \nRETRYING CONNECTION: " + numberOfRetries + " tries."); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTING); if (!mConnectionShouldBeRunning) { // connection was killed by service // agent HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "Connection " + "was disconnected by Service Agent. Stopping retries!"); return; } stopConnection(); // stop to kill anything that might cause further IOEs // if we retried enough, we just return and end further retries if (numberOfRetries > MAX_NUMBER_RETRIES) { invalidateRequests(); mDidCriticalErrorOccur = true; mLastErrorTimestamp = System.currentTimeMillis(); /* * FlurryAgent.onError("ERROR_TCP_FAILED", * "Failed reconnecting for the 3rd time. Stopping!" + * mLastErrorTimestamp, "TcpConnectionThread"); */ synchronized (this) { notify(); // notify as we might be currently blocked on a // request's wait() } ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_DISCONNECTED); return; } try { // sleep a while to let the connection recover int sleepVal = (ERROR_RETRY_INTERVAL / 2) * numberOfRetries; Thread.sleep(sleepVal); } catch (InterruptedException ie) { } if (!mConnectionShouldBeRunning) { return; } try { reconnectSocket(); // TODO switch this block with the test connection block below // once the RPG implements this correctly. HeartbeatSenderThread hbSender = new HeartbeatSenderThread(this, mService, mSocket); hbSender.setOutputStream(mOs); hbSender.sendHeartbeat(); hbSender = null; mDidCriticalErrorOccur = false; if (!mConnectionShouldBeRunning) { return; } startHelperThreads(); // restart our connections // TODO add this once the BE supports it! /* * ConnectionTester connTester = new ConnectionTester(mIs, mOs); if * (connTester.runTest()) { mDidCriticalErrorOccur = false; * startHelperThreads(); // restart our connections Map<String, * String> map = new HashMap<String, String>(); * map.put("Last Error Timestamp", "" + mLastErrorTimestamp); * map.put("Last Error Retry Timestamp", "" + mLastErrorRetryTime); * map.put("Current Timestamp", "" + System.currentTimeMillis()); * map.put("Number of Retries", "" + numberOfRetries); * FlurryAgent.onEvent("RecoveredFromTCPError", map); } else { * HttpConnectionThread * .log("TcpConnectionThread.haltAndRetryConnection()", * "Could not receive TCP test response. need to retry..."); * haltAndRetryConnection(++numberOfRetries); } */ Map<String, String> map = new HashMap<String, String>(); map.put("Last Error Timestamp", "" + mLastErrorTimestamp); map.put("Last Error Retry Timestamp", "" + mLastErrorRetryTime); map.put("Current Timestamp", "" + System.currentTimeMillis()); map.put("Number of Retries", "" + numberOfRetries); // FlurryAgent.onEvent("RecoveredFromTCPError", map); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTED); } catch (IOException ioe) { HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "Failed sending heartbeat. Need to retry..."); haltAndRetryConnection(++numberOfRetries); } catch (Exception e) { HttpConnectionThread.logE("TcpConnectionThread.haltAndRetryConnection()", "An unknown error occured: ", e); haltAndRetryConnection(++numberOfRetries); } } /** * Invalidates all the requests so that the engines can either resend or * post an error message for the user. */ private void invalidateRequests() { QueueManager reqQueue = QueueManager.getInstance(); if (null != reqQueue) { TimeOutWatcher timeoutWatcher = reqQueue.getRequestTimeoutWatcher(); if (null != timeoutWatcher) { timeoutWatcher.invalidateAllRequests(); } } } @Override public void startThread() { if ((null != mThread) && (mThread.isAlive()) && (mConnectionShouldBeRunning)) { HttpConnectionThread.logI("TcpConnectionThread.startThread()", "No need to start Thread. " + "Already there. Returning"); return; } mConnectionShouldBeRunning = true; mThread = new Thread(this); mThread.start(); } @Override public void stopThread() { HttpConnectionThread.logI("TcpConnectionThread.stopThread()", "Stop Thread was called!"); mConnectionShouldBeRunning = false; stopConnection(); synchronized (this) { notify(); } } /** * Starts the helper threads in order to be able to read responses and send * heartbeats and passes them the needed input and output streams. */ private void startHelperThreads() { HttpConnectionThread.logI("TcpConnectionThread.startHelperThreads()", "STARTING HELPER THREADS."); if (null == mHeartbeatSender) { mHeartbeatSender = new HeartbeatSenderThread(this, mService, mSocket); HeartbeatSenderThread.mCurrentThread = mHeartbeatSender; } else { HttpConnectionThread.logE("TcpConnectionThread.startHelperThreads()", "HeartbeatSenderThread was not null!", null); } if (null == mResponseReader) { mResponseReader = new ResponseReaderThread(this, mDecoder, mSocket); ResponseReaderThread.mCurrentThread = mResponseReader; } else { HttpConnectionThread.logE("TcpConnectionThread.startHelperThreads()", "ResponseReaderThread was not null!", null); } mHeartbeatSender.setOutputStream(mOs); mResponseReader.setInputStream(mBufferedInputStream); if (!mHeartbeatSender.getIsActive()) { mHeartbeatSender.startConnection(); mResponseReader.startConnection(); } } /** * Stops the helper threads and closes the input and output streams. As the * response reader is at this point in time probably in a blocking * read()-state an IOException will need to be caught. */ private void stopHelperThreads() { HttpConnectionThread.logI("TcpConnectionThread.stopHelperThreads()", "STOPPING HELPER THREADS: " + ((null != mHeartbeatSender) ? mHeartbeatSender.getIsActive() : false)); if (null != mResponseReader) { mResponseReader.stopConnection(); } if (null != mHeartbeatSender) { mHeartbeatSender.stopConnection(); } mOs = null; mBufferedInputStream = null; mHeartbeatSender = null; mResponseReader = null; } /** * Stops the connection and its underlying socket implementation. Keeps the * thread running to allow further logins from the user. */ synchronized private void stopConnection() { HttpConnectionThread.logI("TcpConnectionThread.stopConnection()", "Closing socket..."); stopHelperThreads(); if (null != mSocket) { try {
360/360-Engine-for-Android
eece262ff36e495eb43e6341758c3ab44f43efda
Simplified Hessian parsing of longs, ints and dates.
diff --git a/src/com/caucho/hessian/micro/MicroHessianInput.java b/src/com/caucho/hessian/micro/MicroHessianInput.java index 294ee6d..8a9f391 100644 --- a/src/com/caucho/hessian/micro/MicroHessianInput.java +++ b/src/com/caucho/hessian/micro/MicroHessianInput.java @@ -1,599 +1,535 @@ /* * Copyright (c) 2001-2006 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Scott Ferguson * */ package com.caucho.hessian.micro; import java.io.DataInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Hashtable; import java.util.Vector; import com.vodafone360.people.utils.LogUtils; /** * Input stream for Hessian requests, compatible with microedition Java. It only * uses classes and types available to J2ME. In particular, it does not have any * support for the &lt;double> type. * <p> * MicroHessianInput does not depend on any classes other than in J2ME, so it * can be extracted independently into a smaller package. * <p> * MicroHessianInput is unbuffered, so any client needs to provide its own * buffering. * * <pre> * InputStream is = ...; // from http connection * MicroHessianInput in = new MicroHessianInput(is); * String value; * in.startReply(); // read reply header * value = in.readString(); // read string value * in.completeReply(); // read reply footer * </pre> */ public class MicroHessianInput { protected DataInputStream is; /** Using fast but not thread safe StringBuilder for constructing strings */ private StringBuilder mStringBuilder = new StringBuilder(255); /** * Creates a new Hessian input stream, initialized with an underlying input * stream. * * @param is the underlying input stream. */ public MicroHessianInput(InputStream is) { init(is); } /** * Creates an uninitialized Hessian input stream. */ public MicroHessianInput() { } /** * Initialize the hessian stream with the underlying input stream. */ public void init(InputStream is) { this.is = new DataInputStream(is); } /** * Starts reading the reply * <p> * A successful completion will have a single value: * * <pre> * r x01 x00 * </pre> */ public void startReply() throws IOException { int tag = is.read(); if (tag != 'r') throw protocolException("expected hessian reply"); // remove some bits from the input stream is.skip(2); } /** * Completes reading the call * <p> * A successful completion will have a single value: * * <pre> * z * </pre> */ public void completeReply() throws IOException { int tag = is.read(); if (tag != 'z') throw protocolException("expected end of reply"); } /** * Reads a boolean * * <pre> * T * F * </pre> */ public boolean readBoolean() throws IOException { int tag = is.read(); switch (tag) { case 'T': return true; case 'F': return false; default: throw expect("boolean", tag); } } /** * Reads an integer * * <pre> * I b32 b24 b16 b8 * </pre> */ public int readInt() throws IOException { int tag = is.read(); return readInt(tag); } public int readInt(int tag) throws IOException { if (tag != 'I') throw expect("integer", tag); - int b32 = is.read(); - int b24 = is.read(); - int b16 = is.read(); - int b8 = is.read(); - - return (b32 << 24) + (b24 << 16) + (b16 << 8) + b8; + return is.readInt(); } /** * Reads a long * * <pre> * L b64 b56 b48 b40 b32 b24 b16 b8 * </pre> */ public long readLong() throws IOException { int tag = is.read(); return readLong(tag); } private long readLong(int tag) throws IOException { if (tag != 'L') throw protocolException("expected long"); - long b64 = is.read(); - long b56 = is.read(); - long b48 = is.read(); - long b40 = is.read(); - long b32 = is.read(); - long b24 = is.read(); - long b16 = is.read(); - long b8 = is.read(); - - return ((b64 << 56) + (b56 << 48) + (b48 << 40) + (b40 << 32) + (b32 << 24) + (b24 << 16) - + (b16 << 8) + b8); + return is.readLong(); } /** * Reads a date. * * <pre> * T b64 b56 b48 b40 b32 b24 b16 b8 * </pre> */ public long readUTCDate() throws IOException { int tag = is.read(); if (tag != 'd') throw protocolException("expected date"); - long b64 = is.read(); - long b56 = is.read(); - long b48 = is.read(); - long b40 = is.read(); - long b32 = is.read(); - long b24 = is.read(); - long b16 = is.read(); - long b8 = is.read(); - - return ((b64 << 56) + (b56 << 48) + (b48 << 40) + (b40 << 32) + (b32 << 24) + (b24 << 16) - + (b16 << 8) + b8); + return is.readLong(); } /** * Reads a byte array * * @return byte[] array extracted from Hessian stream, NULL if 'N' specified * in data. * @throws IOException. */ public byte[] readBytes() throws IOException { int tag = is.read(); return readBytes(tag); } private byte[] readBytes(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'B') throw expect("bytes", tag); int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; byte[] bytes = new byte[len]; is.read(bytes); return bytes; } /** * Reads an arbitrary object the input stream. */ public Object readObject(Class<?> expectedClass) throws IOException { int tag = is.read(); switch (tag) { case 'N': return null; case 'T': return true; case 'F': return false; case 'I': { - int b32 = is.read(); - int b24 = is.read(); - int b16 = is.read(); - int b8 = is.read(); - - return ((b32 << 24) + (b24 << 16) + (b16 << 8) + b8); + return readInt(tag); } case 'L': { - long b64 = is.read(); - long b56 = is.read(); - long b48 = is.read(); - long b40 = is.read(); - long b32 = is.read(); - long b24 = is.read(); - long b16 = is.read(); - long b8 = is.read(); - - return ((b64 << 56) + (b56 << 48) + (b48 << 40) + (b40 << 32) + (b32 << 24) - + (b24 << 16) + (b16 << 8) + b8); + return readLong(tag); } case 'd': { - long b64 = is.read(); - long b56 = is.read(); - long b48 = is.read(); - long b40 = is.read(); - long b32 = is.read(); - long b24 = is.read(); - long b16 = is.read(); - long b8 = is.read(); - - return new Date((b64 << 56) + (b56 << 48) + (b48 << 40) + (b40 << 32) + (b32 << 24) - + (b24 << 16) + (b16 << 8) + b8); + return new Date(is.readLong()); } case 'S': case 'X': { int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; return readStringImpl(len); } case 'B': { - if (tag != 'B') - throw expect("bytes", tag); - - int b16 = is.read(); - int b8 = is.read(); - - int len = (b16 << 8) + b8; - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - for (int i = 0; i < len; i++) - bos.write(is.read()); - - return bos.toByteArray(); + return readBytes(tag); } default: throw new IOException("unknown code:" + (char)tag); } } public Vector<Object> readVector() throws IOException { int tag = is.read(); return readVector(tag); } private Vector<Object> readVector(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'V') throw expect("vector", tag); Vector<Object> v = new Vector<Object>(); Object o = decodeTag(); if (o instanceof End) return v; if (o instanceof Type) o = decodeTag(); if (o instanceof End) return v; int len = 0; if (o instanceof Integer) { len = ((Integer)o); o = decodeTag(); } for (int i = 0; i < len; i++) { v.addElement(o); o = decodeTag(); } return v; } public Fault readFault() throws IOException { decodeTag(); int tag = is.read(); if (tag == 'S') { return new Fault(readString(tag)); } return null; } public Object decodeTag() throws IOException { int tag = is.read(); // HessianUtils.printTagValue(tag); return decodeType(tag); } public Object decodeType(int tag) throws IOException { // LogUtils.logD("HessianDecoder.decodeType() tag["+tag+"]"); switch (tag) { case 't': // tag is.skip(2); Type type = new Type(); return type; case 'l': // length int i = 0; i += (is.read() << 24); i += (is.read() << 16); i += (is.read() << 8); i += is.read(); Integer len = i; return len; case 'z': // end End end = new End(); return end; case 'N': // null return null; case 'r': // reply startReply should have retrieved this? return null; case 'M': return readHashMap(tag); case 'V': // array/Vector return readVector(tag); case 'T': // boolean true return true; case 'F': // boolean false return false; case 'I': // integer return readInt(tag); case 'L': // read long return readLong(tag); case 'd': // UTC date return null; case 'S': // String return readString(tag); case 'B': // read byte array return readBytes(tag); case 'f': return readFault(); default: LogUtils.logE("HessianDecoder.decodeType() Unknown type"); return null; } } /** * Reads a string * * <pre> * S b16 b8 string value * </pre> */ public String readString() throws IOException { int tag = is.read(); return readString(tag); } private String readString(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'S') throw expect("string", tag); int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; return readStringImpl(len); } /** * Reads a string from the underlying stream. */ private String readStringImpl(int length) throws IOException { // reset the StringBuilder. Recycling is better than making always a // new one. mStringBuilder.setLength(0); for (int i = 0; i < length; i++) { int ch = is.read(); if (ch < 0x80) mStringBuilder.append((char)ch); else if ((ch & 0xe0) == 0xc0) { int ch1 = is.read(); int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f); mStringBuilder.append((char)v); } else if ((ch & 0xf0) == 0xe0) { int ch1 = is.read(); int ch2 = is.read(); int v = ((ch & 0x0f) << 12) + ((ch1 & 0x3f) << 6) + (ch2 & 0x3f); mStringBuilder.append((char)v); } else if ((ch & 0xff) >= 0xf0 && (ch & 0xff) <= 0xf4) { // UTF-4 final byte[] b = new byte[4]; b[0] = (byte)ch; b[1] = (byte)is.read(); b[2] = (byte)is.read(); b[3] = (byte)is.read(); mStringBuilder.append(new String(b, "utf-8")); i++; } else throw new IOException("bad utf-8 encoding"); } return mStringBuilder.substring(0, mStringBuilder.length()); } public Hashtable<String, Object> readHashMap() throws IOException { // read map type int tag = is.read(); return readHashMap(tag); } public Hashtable<String, Object> readHashMap(int tag) throws IOException { // read map type if (tag == 'N') return null; if (tag != 'M') throw expect("map", tag); Hashtable<String, Object> ht = new Hashtable<String, Object>(); Object obj = decodeTag(); if (obj instanceof Type) { // get following object obj = decodeTag(); } Object obj1 = null; while (obj != null && !(obj instanceof End)) // 'z' = list-end { obj1 = decodeTag(); ht.put(obj.toString(), obj1); obj = decodeTag(); } return ht; } protected IOException expect(String expect, int ch) { if (ch < 0) return protocolException("expected " + expect + " at end of file"); else return protocolException("expected " + expect + " at " + (char)ch); } protected IOException protocolException(String message) { return new IOException(message); } /** * Place-holder class for End tag 'z' */ private static class End { } /** * Place-holder class for Type tag 't' */ private static class Type { } /** * Class holding error string returned during Hessian decoding */ public static class Fault { private String mErrString = null; private Fault(String eString) { mErrString = eString; } public String errString() { return mErrString; } } }
360/360-Engine-for-Android
d2c28e18b475ba787cacfd5588e14ea7daafd5b6
Changed input stream type to DataInputStream which provides us with all the decoding capabilities that we need.
diff --git a/src/com/caucho/hessian/micro/MicroHessianInput.java b/src/com/caucho/hessian/micro/MicroHessianInput.java index 687ff79..294ee6d 100644 --- a/src/com/caucho/hessian/micro/MicroHessianInput.java +++ b/src/com/caucho/hessian/micro/MicroHessianInput.java @@ -1,599 +1,599 @@ /* * Copyright (c) 2001-2006 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Scott Ferguson * */ package com.caucho.hessian.micro; -import java.io.BufferedInputStream; +import java.io.DataInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Hashtable; import java.util.Vector; import com.vodafone360.people.utils.LogUtils; /** * Input stream for Hessian requests, compatible with microedition Java. It only * uses classes and types available to J2ME. In particular, it does not have any * support for the &lt;double> type. * <p> * MicroHessianInput does not depend on any classes other than in J2ME, so it * can be extracted independently into a smaller package. * <p> * MicroHessianInput is unbuffered, so any client needs to provide its own * buffering. * * <pre> * InputStream is = ...; // from http connection * MicroHessianInput in = new MicroHessianInput(is); * String value; * in.startReply(); // read reply header * value = in.readString(); // read string value * in.completeReply(); // read reply footer * </pre> */ public class MicroHessianInput { - protected BufferedInputStream is; + protected DataInputStream is; /** Using fast but not thread safe StringBuilder for constructing strings */ private StringBuilder mStringBuilder = new StringBuilder(255); - + /** * Creates a new Hessian input stream, initialized with an underlying input * stream. * * @param is the underlying input stream. */ public MicroHessianInput(InputStream is) { init(is); } /** * Creates an uninitialized Hessian input stream. */ public MicroHessianInput() { } /** * Initialize the hessian stream with the underlying input stream. */ public void init(InputStream is) { - this.is = new BufferedInputStream(is); + this.is = new DataInputStream(is); } /** * Starts reading the reply * <p> * A successful completion will have a single value: * * <pre> * r x01 x00 * </pre> */ public void startReply() throws IOException { int tag = is.read(); if (tag != 'r') throw protocolException("expected hessian reply"); // remove some bits from the input stream is.skip(2); } /** * Completes reading the call * <p> * A successful completion will have a single value: * * <pre> * z * </pre> */ public void completeReply() throws IOException { int tag = is.read(); if (tag != 'z') throw protocolException("expected end of reply"); } /** * Reads a boolean * * <pre> * T * F * </pre> */ public boolean readBoolean() throws IOException { int tag = is.read(); switch (tag) { case 'T': return true; case 'F': return false; default: throw expect("boolean", tag); } } /** * Reads an integer * * <pre> * I b32 b24 b16 b8 * </pre> */ public int readInt() throws IOException { int tag = is.read(); return readInt(tag); } public int readInt(int tag) throws IOException { if (tag != 'I') throw expect("integer", tag); int b32 = is.read(); int b24 = is.read(); int b16 = is.read(); int b8 = is.read(); return (b32 << 24) + (b24 << 16) + (b16 << 8) + b8; } /** * Reads a long * * <pre> * L b64 b56 b48 b40 b32 b24 b16 b8 * </pre> */ public long readLong() throws IOException { int tag = is.read(); return readLong(tag); } private long readLong(int tag) throws IOException { if (tag != 'L') throw protocolException("expected long"); long b64 = is.read(); long b56 = is.read(); long b48 = is.read(); long b40 = is.read(); long b32 = is.read(); long b24 = is.read(); long b16 = is.read(); long b8 = is.read(); return ((b64 << 56) + (b56 << 48) + (b48 << 40) + (b40 << 32) + (b32 << 24) + (b24 << 16) + (b16 << 8) + b8); } /** * Reads a date. * * <pre> * T b64 b56 b48 b40 b32 b24 b16 b8 * </pre> */ public long readUTCDate() throws IOException { int tag = is.read(); if (tag != 'd') throw protocolException("expected date"); long b64 = is.read(); long b56 = is.read(); long b48 = is.read(); long b40 = is.read(); long b32 = is.read(); long b24 = is.read(); long b16 = is.read(); long b8 = is.read(); return ((b64 << 56) + (b56 << 48) + (b48 << 40) + (b40 << 32) + (b32 << 24) + (b24 << 16) + (b16 << 8) + b8); } /** * Reads a byte array * * @return byte[] array extracted from Hessian stream, NULL if 'N' specified * in data. * @throws IOException. */ public byte[] readBytes() throws IOException { int tag = is.read(); return readBytes(tag); } private byte[] readBytes(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'B') throw expect("bytes", tag); int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; byte[] bytes = new byte[len]; is.read(bytes); return bytes; } /** * Reads an arbitrary object the input stream. */ public Object readObject(Class<?> expectedClass) throws IOException { int tag = is.read(); switch (tag) { case 'N': return null; case 'T': return true; case 'F': return false; case 'I': { int b32 = is.read(); int b24 = is.read(); int b16 = is.read(); int b8 = is.read(); return ((b32 << 24) + (b24 << 16) + (b16 << 8) + b8); } case 'L': { long b64 = is.read(); long b56 = is.read(); long b48 = is.read(); long b40 = is.read(); long b32 = is.read(); long b24 = is.read(); long b16 = is.read(); long b8 = is.read(); return ((b64 << 56) + (b56 << 48) + (b48 << 40) + (b40 << 32) + (b32 << 24) + (b24 << 16) + (b16 << 8) + b8); } case 'd': { long b64 = is.read(); long b56 = is.read(); long b48 = is.read(); long b40 = is.read(); long b32 = is.read(); long b24 = is.read(); long b16 = is.read(); long b8 = is.read(); return new Date((b64 << 56) + (b56 << 48) + (b48 << 40) + (b40 << 32) + (b32 << 24) + (b24 << 16) + (b16 << 8) + b8); } case 'S': case 'X': { int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; return readStringImpl(len); } case 'B': { if (tag != 'B') throw expect("bytes", tag); int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (int i = 0; i < len; i++) bos.write(is.read()); return bos.toByteArray(); } default: throw new IOException("unknown code:" + (char)tag); } } public Vector<Object> readVector() throws IOException { int tag = is.read(); return readVector(tag); } private Vector<Object> readVector(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'V') throw expect("vector", tag); Vector<Object> v = new Vector<Object>(); Object o = decodeTag(); if (o instanceof End) return v; if (o instanceof Type) o = decodeTag(); if (o instanceof End) return v; int len = 0; if (o instanceof Integer) { len = ((Integer)o); o = decodeTag(); } for (int i = 0; i < len; i++) { v.addElement(o); o = decodeTag(); } return v; } public Fault readFault() throws IOException { decodeTag(); int tag = is.read(); if (tag == 'S') { return new Fault(readString(tag)); } return null; } public Object decodeTag() throws IOException { int tag = is.read(); // HessianUtils.printTagValue(tag); return decodeType(tag); } public Object decodeType(int tag) throws IOException { // LogUtils.logD("HessianDecoder.decodeType() tag["+tag+"]"); switch (tag) { case 't': // tag is.skip(2); Type type = new Type(); return type; case 'l': // length int i = 0; i += (is.read() << 24); i += (is.read() << 16); i += (is.read() << 8); i += is.read(); Integer len = i; return len; case 'z': // end End end = new End(); return end; case 'N': // null return null; case 'r': // reply startReply should have retrieved this? return null; case 'M': return readHashMap(tag); case 'V': // array/Vector return readVector(tag); case 'T': // boolean true return true; case 'F': // boolean false return false; case 'I': // integer return readInt(tag); case 'L': // read long return readLong(tag); case 'd': // UTC date return null; case 'S': // String return readString(tag); case 'B': // read byte array return readBytes(tag); case 'f': return readFault(); default: LogUtils.logE("HessianDecoder.decodeType() Unknown type"); return null; } } /** * Reads a string * * <pre> * S b16 b8 string value * </pre> */ public String readString() throws IOException { int tag = is.read(); return readString(tag); } private String readString(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'S') throw expect("string", tag); int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; return readStringImpl(len); } /** * Reads a string from the underlying stream. */ private String readStringImpl(int length) throws IOException { // reset the StringBuilder. Recycling is better than making always a // new one. mStringBuilder.setLength(0); for (int i = 0; i < length; i++) { int ch = is.read(); if (ch < 0x80) mStringBuilder.append((char)ch); else if ((ch & 0xe0) == 0xc0) { int ch1 = is.read(); int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f); mStringBuilder.append((char)v); } else if ((ch & 0xf0) == 0xe0) { int ch1 = is.read(); int ch2 = is.read(); int v = ((ch & 0x0f) << 12) + ((ch1 & 0x3f) << 6) + (ch2 & 0x3f); mStringBuilder.append((char)v); } else if ((ch & 0xff) >= 0xf0 && (ch & 0xff) <= 0xf4) { // UTF-4 final byte[] b = new byte[4]; b[0] = (byte)ch; b[1] = (byte)is.read(); b[2] = (byte)is.read(); b[3] = (byte)is.read(); mStringBuilder.append(new String(b, "utf-8")); i++; } else throw new IOException("bad utf-8 encoding"); } return mStringBuilder.substring(0, mStringBuilder.length()); } public Hashtable<String, Object> readHashMap() throws IOException { // read map type int tag = is.read(); return readHashMap(tag); } public Hashtable<String, Object> readHashMap(int tag) throws IOException { // read map type if (tag == 'N') return null; if (tag != 'M') throw expect("map", tag); Hashtable<String, Object> ht = new Hashtable<String, Object>(); Object obj = decodeTag(); if (obj instanceof Type) { // get following object obj = decodeTag(); } Object obj1 = null; while (obj != null && !(obj instanceof End)) // 'z' = list-end { obj1 = decodeTag(); ht.put(obj.toString(), obj1); obj = decodeTag(); } return ht; } protected IOException expect(String expect, int ch) { if (ch < 0) return protocolException("expected " + expect + " at end of file"); else return protocolException("expected " + expect + " at " + (char)ch); } protected IOException protocolException(String message) { return new IOException(message); } /** * Place-holder class for End tag 'z' */ private static class End { } /** * Place-holder class for Type tag 't' */ private static class Type { } /** * Class holding error string returned during Hessian decoding */ public static class Fault { private String mErrString = null; private Fault(String eString) { mErrString = eString; } public String errString() { return mErrString; } } }
360/360-Engine-for-Android
bba79251c7bc99fe44f2fb13532f05542cdee185
Fix in Logger
diff --git a/src/com/vodafone360/people/service/transport/tcp/ResponseReaderThread.java b/src/com/vodafone360/people/service/transport/tcp/ResponseReaderThread.java index ca14631..cd34553 100644 --- a/src/com/vodafone360/people/service/transport/tcp/ResponseReaderThread.java +++ b/src/com/vodafone360/people/service/transport/tcp/ResponseReaderThread.java @@ -1,331 +1,331 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.transport.tcp; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import com.vodafone360.people.Settings; import com.vodafone360.people.service.io.rpg.RpgHeader; import com.vodafone360.people.service.transport.DecoderThread; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.hessian.HessianUtils; import com.vodafone360.people.utils.LogUtils; /** * Reads responses from a TCP sockets and adds them to the response decoder. * Errors are called and passed back to the RpgTcpConnectionThread. * * @author Rudy Norff ([email protected]) */ public class ResponseReaderThread implements Runnable { /** * Sleep time (in milliseconds) of the thread in between reads. */ private static final long THREAD_SLEEP_TIME = 300; // ms /** * The ResponseReaderThread that was created by the TcpConnectionThread. It * will be compared to this thread. If they differ this thread must be a * lock thread that got stuck when the user changed APNs or switched from * WiFi to another data connection type. */ protected static ResponseReaderThread mCurrentThread; /** * Decodes all responses coming in. */ private DecoderThread mDecoder; /** * The main connection thread to call back when an error occured. */ private TcpConnectionThread mConnThread; /** * The input stream to read responses from. */ protected DataInputStream mIs; /** * Indicates that the thread is active and connected. */ protected boolean mIsConnectionRunning; /** * Represents the thread that reads responses. */ protected Thread mThread; /** * The socket to read from. */ private Socket mSocket; /** * Constructs a new response reader used for reading bytes from a socket * connection. * * @param connThread The connection thread that manages this and the * heartbeat sender thread. It is called back whenever an error * occured reading from the socket input stream. * @param decoder Used to decode all incoming responses. */ public ResponseReaderThread(TcpConnectionThread connThread, DecoderThread decoder, Socket socket) { mConnThread = connThread; mDecoder = decoder; mSocket = socket; if (null != mSocket) { try { mSocket.setSoTimeout(Settings.TCP_SOCKET_READ_TIMEOUT); } catch (SocketException se) { HttpConnectionThread.logE("ResponseReaderThread()", "Could not set socket to!", se); } } } /** * Starts the connection by setting the connection flag and spawning a new * thread in which responses can be read without interfering with the rest * of the client. */ public void startConnection() { HttpConnectionThread.logI("RpgTcpResponseReader.startConnection()", "STARTING Response Reader!"); mIsConnectionRunning = true; mThread = new Thread(this, "RpgTcpResponseReader"); mThread.start(); } /** * Stops the connection by closing the input stream and setting it to null. * Attempts to stop the thread and sets it to null. */ public void stopConnection() { mIsConnectionRunning = false; if (null != mSocket) { try { mSocket.shutdownInput(); } catch (IOException ioe) { HttpConnectionThread.logE("RpgTcpHeartbeatSender.stopConnection()", "Could not shutdown InputStream", ioe); } finally { mSocket = null; } } if (null != mIs) { try { mIs.close(); } catch (IOException ioe) { HttpConnectionThread.logE("RpgTcpResponseReader.stopConnection()", "Could not close InputStream", ioe); } finally { mIs = null; } } try { mThread.join(60); // give it 60 millis max } catch (InterruptedException ie) { } } /** * Sets the input stream that will be used to read responses from. * * @param inputStream The input stream to read from. Should not be null as * this would trigger a reconnect of the whole socket and cause * all transport-threads to be restarted. */ public void setInputStream(BufferedInputStream inputStream) { HttpConnectionThread.logI("RpgTcpResponseReader.setInputStream()", "Setting new IS: " + ((null != inputStream) ? "not null" : "null")); if (null != inputStream) { mIs = new DataInputStream(inputStream); } else { mIs = null; } } /** * Overrides the Thread.run() method and continuously calls the * readResponses() method which blocks and reads responses or throws an * exception that needs to be handled by reconnecting the sockets. */ public void run() { while (mIsConnectionRunning) { checkForDuplicateThreads(); try { byte[] response = readNextResponse(); if ((null != response) && (response.length >= RpgHeader.HEADER_LENGTH)) { mDecoder.handleResponse(response); } } catch (Throwable t) { HttpConnectionThread.logE("RpgTcpResponseReader.run()", "Could not read Response. Unknown: ", t); if ((null != mConnThread) && (mIsConnectionRunning)) { mIsConnectionRunning = false; mConnThread.notifyOfNetworkProblems(); } } try { Thread.sleep(THREAD_SLEEP_TIME); } catch (InterruptedException ie) { } } } /** * <p> * Attempts to read all the bytes from the DataInputStream and writes them * to a byte array where they are processed for further use. * </p> * <p> * As this method uses InputStream.read() it blocks the execution until a * byte has been read, the socket was closed (at which point an IOException * will be thrown), or the end of the file has been reached (resulting in a * EOFException being thrown). * </p> * * @throws IOException Thrown if something went wrong trying to read or * write a byte from or to a stream. * @throws EOFException Thrown if the end of the stream has been reached * unexpectedly. * @return A byte-array if the response was read successfully or null if the * response could not be read. */ private byte[] readNextResponse() throws IOException, EOFException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); int offset = 0; for (int i = 0; i < 2; i++) { // read delimiter, this method blocks int tag = -1; try { tag = mIs.read(); } catch (SocketTimeoutException ste) { HttpConnectionThread.logW("ResponseReaderThread.readNextResponse()", "Socket timed out reading!"); checkForDuplicateThreads(); return null; } if (tag != RpgHeader.DELIMITER_BYTE) { if (tag == -1) { // we reached EOF. This is a network issue throw new EOFException(); } HttpConnectionThread.logI("RpgTcpResponseReader.readResponses()", "Returning... Tag is " + tag + " (" + (char)tag + ")"); return null; } } final byte msgType = mIs.readByte(); final int reqId = mIs.readInt(); final int other = mIs.readInt(); final int payloadSize = mIs.readInt(); final byte compression = mIs.readByte(); dos.writeByte(RpgHeader.DELIMITER_BYTE); dos.writeByte(RpgHeader.DELIMITER_BYTE); dos.writeByte(msgType); dos.writeInt(reqId); dos.writeInt(other); dos.writeInt(payloadSize); dos.writeByte(compression); byte[] payload = new byte[payloadSize]; // read the payload while (offset < payloadSize) { offset += mIs.read(payload, offset, payloadSize - offset); } dos.write(payload); dos.flush(); dos.close(); final byte[] response = baos.toByteArray(); if (Settings.ENABLED_TRANSPORT_TRACE) { if (reqId != 0) { // regular response HttpConnectionThread.logI("ResponseReader.readResponses()", "\n" + " < Response for ID " + reqId + " with payload-length " + payloadSize + " received <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" + HessianUtils.getInHessian(new ByteArrayInputStream(response), false) + "\n "); } else { // push response HttpConnectionThread.logI("ResponseReader.readResponses()", "\n" + " < Push response " + " with payload-length " + payloadSize + " received <x<x<x<x<x<x<x<x<x<x<x<x<x<x<x<x<x<x<x<x<x<x" + HessianUtils.getInHessian(new ByteArrayInputStream(response), false) + "\n "); } - - // log file containing response to SD card - if (Settings.sEnableSuperExpensiveResponseFileLogging) { - LogUtils.logE("XXXXXXYYYXXXXXX Do not Remove this!"); - LogUtils.logToFile(response, "people_" + reqId + "_" + System.currentTimeMillis() - + "_resp_" + ((int)msgType) - + ((compression == 1) ? ".gzip_w_rpg_header" : ".txt")); - } // end log file containing response to SD card } + // log file containing response to SD card + if (Settings.sEnableSuperExpensiveResponseFileLogging) { + LogUtils.logE("XXXXXXYYYXXXXXX Do not Remove this!"); + LogUtils.logToFile(response, "people_" + reqId + "_" + System.currentTimeMillis() + + "_resp_" + ((int)msgType) + + ((compression == 1) ? ".gzip_w_rpg_header" : ".txt")); + } // end log file containing response to SD card + return response; } /** * Checks whether the current thread is not the same as the thread that * should be running. If it is not the connection and the thread is stopped. */ private void checkForDuplicateThreads() { if (!this.equals(mCurrentThread)) { // The current thread created by the TcpConnectionThread is not // equal to this thread. // This thread must be old (locked due to the user changing his // network settings. HttpConnectionThread.logE("ResponseReaderThread.run()", "This thread is a " + "locked thread caused by the connection settings being switched.", null); stopConnection(); // exit this thread } } } diff --git a/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java b/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java index 58886e1..ab6e747 100644 --- a/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java +++ b/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java @@ -1,590 +1,591 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.transport.tcp; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import com.jcraft.jsch.jce.Random; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.DecoderThread; import com.vodafone360.people.service.transport.IConnection; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.TimeOutWatcher; import com.vodafone360.people.service.utils.hessian.HessianUtils; import com.vodafone360.people.utils.LogUtils; public class TcpConnectionThread implements Runnable, IConnection { private static final String RPG_FALLBACK_TCP_URL = "rpg.vodafone360.com"; private static final int RPG_DEFAULT_TCP_PORT = 9900; private static final int TCP_DEFAULT_TIMEOUT = 120000; private static final int ERROR_RETRY_INTERVAL = 10000; /** * If we have a connection error we try to restart after 60 seconds earliest */ private static final int CONNECTION_RESTART_INTERVAL = 60000; /** * The maximum number of retries to reestablish a connection until we sleep * until the user uses the UI or * Settings.TCP_RETRY_BROKEN_CONNECTION_INTERVAL calls another retry. */ private static final int MAX_NUMBER_RETRIES = 3; private static final int BYTE_ARRAY_OUTPUT_STREAM_SIZE = 2048; // bytes private Thread mThread; private RemoteService mService; private DecoderThread mDecoder; private boolean mConnectionShouldBeRunning; private boolean mDidCriticalErrorOccur; private BufferedInputStream mBufferedInputStream; private OutputStream mOs; private String mRpgTcpUrl; private int mRpgTcpPort; private Socket mSocket; private HeartbeatSenderThread mHeartbeatSender; private ResponseReaderThread mResponseReader; private long mLastErrorRetryTime, mLastErrorTimestamp; private ByteArrayOutputStream mBaos; public TcpConnectionThread(DecoderThread decoder, RemoteService service) { mSocket = new Socket(); mBaos = new ByteArrayOutputStream(BYTE_ARRAY_OUTPUT_STREAM_SIZE); mConnectionShouldBeRunning = true; mDecoder = decoder; mService = service; mLastErrorRetryTime = System.currentTimeMillis(); mLastErrorTimestamp = 0; try { mRpgTcpUrl = SettingsManager.getProperty(Settings.TCP_RPG_URL_KEY); mRpgTcpPort = Integer.parseInt(SettingsManager.getProperty(Settings.TCP_RPG_PORT_KEY)); } catch (Exception e) { HttpConnectionThread.logE("TcpConnectionThread()", "Could not parse URL or Port!", e); mRpgTcpUrl = RPG_FALLBACK_TCP_URL; mRpgTcpPort = RPG_DEFAULT_TCP_PORT; } } public void run() { QueueManager queueManager = QueueManager.getInstance(); mDidCriticalErrorOccur = false; try { // start the initial connection reconnectSocket(); HeartbeatSenderThread hbSender = new HeartbeatSenderThread(this, mService, mSocket); hbSender.setOutputStream(mOs); hbSender.sendHeartbeat(); hbSender = null; // TODO run this when BE supports it but keep HB in front! /* * ConnectionTester connTester = new ConnectionTester(mIs, mOs); if * (connTester.runTest()) { } else {} */ startHelperThreads(); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTED); } catch (IOException e) { haltAndRetryConnection(1); } catch (Exception e) { haltAndRetryConnection(1); } while (mConnectionShouldBeRunning) { try { if ((null != mOs) && (!mDidCriticalErrorOccur)) { List<Request> reqs = QueueManager.getInstance().getRpgRequests(); int reqNum = reqs.size(); List<Integer> reqIdList = null; if (Settings.ENABLED_TRANSPORT_TRACE || Settings.sEnableSuperExpensiveResponseFileLogging) { reqIdList = new ArrayList<Integer>(); } if (reqNum > 0) { mBaos.reset(); // batch payloads for (int i = 0; i < reqNum; i++) { Request req = reqs.get(i); if ((null == req) || (req.getAuthenticationType() == Request.USE_API)) { HttpConnectionThread.logV("TcpConnectionThread.run()", "Ignoring non-RPG method"); continue; } HttpConnectionThread.logD("TcpConnectionThread.run()", "Preparing [" + req.getRequestId() + "] for sending via RPG..."); req.setActive(true); req.writeToOutputStream(mBaos, true); if (req.isFireAndForget()) { // f-a-f, no response, // remove from queue HttpConnectionThread.logD("TcpConnectionThread.run()", "Removed F&F-Request: " + req.getRequestId()); queueManager.removeRequest(req.getRequestId()); } if (Settings.ENABLED_TRANSPORT_TRACE) { reqIdList.add(req.getRequestId()); HttpConnectionThread.logD("HttpConnectionThread.run()", "Req ID: " + req.getRequestId() + " <-> Auth: " + req.getAuth()); } } mBaos.flush(); byte[] payload = mBaos.toByteArray(); if (null != payload) { // log file containing response to SD card if (Settings.sEnableSuperExpensiveResponseFileLogging) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < reqIdList.size(); i++) { sb.append(reqIdList.get(i)); sb.append("_"); } LogUtils.logE("XXXXXXYYYXXXXXX Do not Remove this!"); - LogUtils.logToFile(payload, "people_" + reqIdList.get(0) + "_" + LogUtils.logToFile(payload, "people_" +( reqIdList.size()>0?reqIdList.get(0):0)+ "_" + System.currentTimeMillis() + "_req_" + ((int)payload[2]) // message // type + ".txt"); } // end log file containing response to SD card if (Settings.ENABLED_TRANSPORT_TRACE) { Long userID = null; AuthSessionHolder auth = LoginEngine.getSession(); if (auth != null) { userID = auth.userID; } HttpConnectionThread.logI("TcpConnectionThread.run()", "\n > Sending request(s) " + reqIdList.toString() + ", for user ID " + userID + " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + HessianUtils.getInHessian( new ByteArrayInputStream(payload), true) + "\n "); } try { synchronized (mOs) { mOs.write(payload); mOs.flush(); } } catch (IOException ioe) { HttpConnectionThread.logE("TcpConnectionThread.run()", "Could not send request", ioe); notifyOfNetworkProblems(); } payload = null; } } } synchronized (this) { if (!mDidCriticalErrorOccur) { wait(); } else { while (mDidCriticalErrorOccur) { // loop until a retry // succeeds HttpConnectionThread.logI("TcpConnectionThread.run()", "Wait() for next connection retry has started."); wait(Settings.TCP_RETRY_BROKEN_CONNECTION_INTERVAL); if (mConnectionShouldBeRunning) { haltAndRetryConnection(1); } } } } } catch (Throwable t) { // FlurryAgent.onError("ERROR_TCP_THREAD_CRASHED", "run()", // "TcpConnectionThread"); HttpConnectionThread.logE("TcpConnectionThread.run()", "Unknown Error: ", t); } } stopConnection(); } /** * Gets notified whenever the user is using the UI. In this special case * whenever an error occured with the connection and this method was not * called a short time before */ @Override public void notifyOfUiActivity() { if (mDidCriticalErrorOccur) { if ((System.currentTimeMillis() - mLastErrorRetryTime) >= CONNECTION_RESTART_INTERVAL) { synchronized (this) { notify(); } mLastErrorRetryTime = System.currentTimeMillis(); } } } @Override public void notifyOfRegainedNetworkCoverage() { synchronized (this) { notify(); } } /** * Called back by the response reader, which should notice network problems * first */ protected void notifyOfNetworkProblems() { HttpConnectionThread.logE("TcpConnectionThread.notifyOfNetworkProblems()", "Houston, we have a network problem!", null); haltAndRetryConnection(1); } /** * Attempts to reconnect the socket if it has been closed for some reason. * * @throws IOException Thrown if something goes wrong while reconnecting the * socket. */ private void reconnectSocket() throws IOException { HttpConnectionThread.logI("TcpConnectionThread.reconnectSocket()", "Reconnecting Socket on " + mRpgTcpUrl + ":" + mRpgTcpPort); mSocket = null; mSocket = new Socket(); mSocket.connect(new InetSocketAddress(mRpgTcpUrl, mRpgTcpPort), TCP_DEFAULT_TIMEOUT); mBufferedInputStream = new BufferedInputStream(mSocket.getInputStream()); mOs = mSocket.getOutputStream(); HttpConnectionThread.logI("TcpConnectionThread.reconnectSocket()", "Socket started: " + mRpgTcpUrl + ":" + mRpgTcpPort); } /** * <p> * Retries to establish a network connection after a network error has * occurred or the coverage of the network was lost. The amount of retries * depends on MAX_NUMBER_RETRIES. * </p> * <p> * A new retry is carried out each time an exception is thrown until the * limit of retries has been reached. * </p> * * @param numberOfRetries The amount of retries carried out until the * connection is given up. */ synchronized private void haltAndRetryConnection(int numberOfRetries) { HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "\n \n \nRETRYING CONNECTION: " + numberOfRetries + " tries."); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTING); if (!mConnectionShouldBeRunning) { // connection was killed by service // agent HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "Connection " + "was disconnected by Service Agent. Stopping retries!"); return; } stopConnection(); // stop to kill anything that might cause further IOEs // if we retried enough, we just return and end further retries if (numberOfRetries > MAX_NUMBER_RETRIES) { invalidateRequests(); mDidCriticalErrorOccur = true; mLastErrorTimestamp = System.currentTimeMillis(); /* * FlurryAgent.onError("ERROR_TCP_FAILED", * "Failed reconnecting for the 3rd time. Stopping!" + * mLastErrorTimestamp, "TcpConnectionThread"); */ synchronized (this) { notify(); // notify as we might be currently blocked on a // request's wait() } ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_DISCONNECTED); return; } try { // sleep a while to let the connection recover int sleepVal = (ERROR_RETRY_INTERVAL / 2) * numberOfRetries; Thread.sleep(sleepVal); } catch (InterruptedException ie) { } if (!mConnectionShouldBeRunning) { return; } try { reconnectSocket(); // TODO switch this block with the test connection block below // once the RPG implements this correctly. HeartbeatSenderThread hbSender = new HeartbeatSenderThread(this, mService, mSocket); hbSender.setOutputStream(mOs); hbSender.sendHeartbeat(); hbSender = null; mDidCriticalErrorOccur = false; if (!mConnectionShouldBeRunning) { return; } startHelperThreads(); // restart our connections // TODO add this once the BE supports it! /* * ConnectionTester connTester = new ConnectionTester(mIs, mOs); if * (connTester.runTest()) { mDidCriticalErrorOccur = false; * startHelperThreads(); // restart our connections Map<String, * String> map = new HashMap<String, String>(); * map.put("Last Error Timestamp", "" + mLastErrorTimestamp); * map.put("Last Error Retry Timestamp", "" + mLastErrorRetryTime); * map.put("Current Timestamp", "" + System.currentTimeMillis()); * map.put("Number of Retries", "" + numberOfRetries); * FlurryAgent.onEvent("RecoveredFromTCPError", map); } else { * HttpConnectionThread * .log("TcpConnectionThread.haltAndRetryConnection()", * "Could not receive TCP test response. need to retry..."); * haltAndRetryConnection(++numberOfRetries); } */ Map<String, String> map = new HashMap<String, String>(); map.put("Last Error Timestamp", "" + mLastErrorTimestamp); map.put("Last Error Retry Timestamp", "" + mLastErrorRetryTime); map.put("Current Timestamp", "" + System.currentTimeMillis()); map.put("Number of Retries", "" + numberOfRetries); // FlurryAgent.onEvent("RecoveredFromTCPError", map); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTED); } catch (IOException ioe) { HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "Failed sending heartbeat. Need to retry..."); haltAndRetryConnection(++numberOfRetries); } catch (Exception e) { HttpConnectionThread.logE("TcpConnectionThread.haltAndRetryConnection()", "An unknown error occured: ", e); haltAndRetryConnection(++numberOfRetries); } } /** * Invalidates all the requests so that the engines can either resend or * post an error message for the user. */ private void invalidateRequests() { QueueManager reqQueue = QueueManager.getInstance(); if (null != reqQueue) { TimeOutWatcher timeoutWatcher = reqQueue.getRequestTimeoutWatcher(); if (null != timeoutWatcher) { timeoutWatcher.invalidateAllRequests(); } } } @Override public void startThread() { if ((null != mThread) && (mThread.isAlive()) && (mConnectionShouldBeRunning)) { HttpConnectionThread.logI("TcpConnectionThread.startThread()", "No need to start Thread. " + "Already there. Returning"); return; } mConnectionShouldBeRunning = true; mThread = new Thread(this); mThread.start(); } @Override public void stopThread() { HttpConnectionThread.logI("TcpConnectionThread.stopThread()", "Stop Thread was called!"); mConnectionShouldBeRunning = false; stopConnection(); synchronized (this) { notify(); } } /** * Starts the helper threads in order to be able to read responses and send * heartbeats and passes them the needed input and output streams. */ private void startHelperThreads() { HttpConnectionThread.logI("TcpConnectionThread.startHelperThreads()", "STARTING HELPER THREADS."); if (null == mHeartbeatSender) { mHeartbeatSender = new HeartbeatSenderThread(this, mService, mSocket); HeartbeatSenderThread.mCurrentThread = mHeartbeatSender; } else { HttpConnectionThread.logE("TcpConnectionThread.startHelperThreads()", "HeartbeatSenderThread was not null!", null); } if (null == mResponseReader) { mResponseReader = new ResponseReaderThread(this, mDecoder, mSocket); ResponseReaderThread.mCurrentThread = mResponseReader; } else { HttpConnectionThread.logE("TcpConnectionThread.startHelperThreads()", "ResponseReaderThread was not null!", null); } mHeartbeatSender.setOutputStream(mOs); mResponseReader.setInputStream(mBufferedInputStream); if (!mHeartbeatSender.getIsActive()) { mHeartbeatSender.startConnection(); mResponseReader.startConnection(); } } /** * Stops the helper threads and closes the input and output streams. As the * response reader is at this point in time probably in a blocking * read()-state an IOException will need to be caught. */ private void stopHelperThreads() { HttpConnectionThread.logI("TcpConnectionThread.stopHelperThreads()", "STOPPING HELPER THREADS: " + ((null != mHeartbeatSender) ? mHeartbeatSender.getIsActive() : false)); if (null != mResponseReader) { mResponseReader.stopConnection(); } if (null != mHeartbeatSender) { mHeartbeatSender.stopConnection(); } mOs = null; mBufferedInputStream = null; mHeartbeatSender = null; mResponseReader = null; } /** * Stops the connection and its underlying socket implementation. Keeps the * thread running to allow further logins from the user. */ synchronized private void stopConnection() { HttpConnectionThread.logI("TcpConnectionThread.stopConnection()", "Closing socket..."); stopHelperThreads(); if (null != mSocket) { try { mSocket.close(); } catch (IOException ioe) { HttpConnectionThread.logE("TcpConnectionThread.stopConnection()", "Could not close Socket!", ioe); } finally { mSocket = null; } } QueueManager.getInstance().clearAllRequests(); } @Override public void notifyOfItemInRequestQueue() { HttpConnectionThread.logV("TcpConnectionThread.notifyOfItemInRequestQueue()", "NEW REQUEST AVAILABLE!"); synchronized (this) { notify(); } } @Override public boolean getIsConnected() { return mConnectionShouldBeRunning; } @Override public boolean getIsRpgConnectionActive() { if ((null != mHeartbeatSender) && (mHeartbeatSender.getIsActive())) { return true; } return false; } @Override public void onLoginStateChanged(boolean isLoggedIn) { } }
360/360-Engine-for-Android
f10a59fd91504a0ce815a84aba604ac2ffa65606
PAND-1962: Disable native sync for 1.X
diff --git a/src/com/vodafone360/people/Settings.java b/src/com/vodafone360/people/Settings.java index 5ee7747..ecd66d0 100644 --- a/src/com/vodafone360/people/Settings.java +++ b/src/com/vodafone360/people/Settings.java @@ -1,293 +1,296 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; /** * All application settings. */ public final class Settings { /* * LogCat. */ /** LogCat TAG prefix. **/ public static final String LOG_TAG = "People_"; /* * Transport. */ /** Milliseconds until HTTP connection will time out. */ public static final int HTTP_CONNECTION_TIMEOUT = 30000; /** Maximum number of HTTP connection attempts. */ public static final int HTTP_MAX_RETRY_COUNT = 3; /** HTTP header content type. */ public static final String HTTP_HEADER_CONTENT_TYPE = "application/binary"; /** Number of empty RPG poll responses before stopping RPG poll. */ public static final int BLANK_RPG_HEADER_COUNT = 4; /** TCP Heartbeat interval (10 seconds). */ public static final long TCP_VF_HEARTBEAT_INTERVAL = 10 * 60 * 1000; /** TCP retry interval if we have lost the connection (30 seconds). */ public static final long TCP_RETRY_BROKEN_CONNECTION_INTERVAL = 30 * 60 * 1000; /** TCP socket read time out for the read-operation. */ public static final int TCP_SOCKET_READ_TIMEOUT = 10 * 60 * 1000; /* * Notifications. */ /** LED colour. */ public static final int NOTIFICATION_LED_COLOR = 0xff00ff00; // Green /** LED on time. */ public static final int NOTIFICATION_LED_OFF_TIME = 300; /** LED on time. */ public static final int NOTIFICATION_LED_ON_TIME = 1000; /* * Upgrade Engine */ /** * See UpdateSettingsActivity.FREQUENCY_SETTING_LONG array for meaning (i.e. * Every 6 hours) */ public static final int PREFS_CHECK_FREQUENCY_DEFAULT = 3; /** Show the upgrade dialog box every 10 minutes. */ public static final int DIALOG_CHECK_FREQUENCY_MILLIS = 10 * 60 * 1000; /** * Component trace flags (always checked in as false, not part of build * script). */ /** Trace output for engine components. **/ public static final boolean ENABLED_ENGINE_TRACE = false; /** Trace output for database components. **/ public static final boolean ENABLED_DATABASE_TRACE = false; /** Trace output for transport (i.e. network IO) components. **/ public static final boolean ENABLED_TRANSPORT_TRACE = false; /** Trace output for contact synchronisation components. **/ public static final boolean ENABLED_CONTACTS_SYNC_TRACE = false; /** Log engine runtime information to file for profiling. **/ public static final boolean ENABLED_PROFILE_ENGINES = false; /** * This is a list of strings containing the names of engines to be * deactivated in the build. A de-activated engine is constructed but will * never be run (nor will onCreate or onDestroy be called). Any UI requests * will be automatically completed by the framework with a * ServiceStatus.ERROR_NOT_IMPLEMENTED error. */ public static final String DEACTIVATE_ENGINE_LIST_KEY = "deactivated-engines-list"; /* * Hard coded settings */ /** Enable dialler cheat code. **/ public static final boolean DIALER_CHEATCODES_ENABLED = true; /** Enable SMS account activation. **/ public static final boolean ENABLE_ACTIVATION = false; /** * Enable SIM inserted check. Always set to TRUE. Makes the application * unusable if there is no valid SIM card inserted into the device. */ public static final boolean ENABLE_SIM_CHECK = true; /** Enable fetching native contacts. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS = true; /** Enable fetching native contacts on change. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS_ON_CHANGE = true; /** Enable ME profile synchronisation. **/ public static final boolean ENABLE_ME_PROFILE_SYNC = true; /** Enable server contact synchronisation. **/ public static final boolean ENABLE_SERVER_CONTACT_SYNC = true; /** Enable server thumbnail synchronisation. **/ public static final boolean ENABLE_THUMBNAIL_SYNC = true; /** Enable update native contacts synchronisation. **/ public static final boolean ENABLE_UPDATE_NATIVE_CONTACTS = true; /** Enable hiding of connected friends group. **/ public static final boolean HIDE_CONNECTED_FRIENDS_GROUP = true; + + /** Disable the native sync after the first time import for Android 1.X devices only **/ + public static final boolean DISABLE_NATIVE_SYNC_AFTER_IMPORT_ON_ANDROID_1X = true; /* * Keys for properties that can be changed at build time. */ /** Key for application ID setting. **/ public static final String APP_KEY_ID = "app-key-id"; /** Key for application secret key setting. **/ public static final String APP_SECRET_KEY = "app-secret-key"; /** Key for enable logging setting. **/ protected static final String ENABLE_LOGCAT_KEY = "enable-logcat"; /** Key for enable RPG setting. **/ public static final String ENABLE_RPG_KEY = "use-rpg"; /** Key for enable SNS resource icon setting. **/ public static final String ENABLE_SNS_RESOURCE_ICON_KEY = "enable-sns-resource-icon"; /** Key for RPG server URL setting. **/ public static final String RPG_SERVER_KEY = "rpg-url"; /** Key for Hessian URL setting. **/ public static final String SERVER_URL_HESSIAN_KEY = "hessian-url"; /* * Keys without defaults. */ /** Key for TCP server URL setting. **/ public static final String TCP_RPG_URL_KEY = "rpg-tcp-url"; /** Key for TCP port setting. **/ public static final String TCP_RPG_PORT_KEY = "rpg-tcp-port"; /** Key for upgrade check URL setting. **/ public static final String UPGRADE_CHECK_URL_KEY = "upgrade-url"; /* * Default for properties that can be changed at build time. */ /** Default for logging enabled setting. **/ protected static final String DEFAULT_ENABLE_LOGCAT = "true"; /** Default for RPG enabled setting. **/ protected static final String DEFAULT_ENABLE_RPG = "true"; /** Default for SNS resource icon setting. **/ protected static final String DEFAULT_ENABLE_SNS_RESOURCE_ICON = "true"; /** Default for RPG server URL setting. **/ protected static final String DEFAULT_RPG_SERVER = "http://rpg.vodafone360.com/rpg/mcomet/"; /** Default for Hessian URL setting. **/ protected static final String DEFAULT_SERVER_URL_HESSIAN = "http://api.vodafone360.com/services/hessian/"; /* * Request timeouts for all engines and requests, except for fire and * forget calls to RPG: SET_AVAILABILITY and SEND_CHAT_MSG. */ /** Do not handle timeouts for this API. **/ private static final long DONT_HANDLE_TIMEOUTS = -1; /** Generic timeout for requests. **/ private static final long ALL_ENGINES_REQUESTS_TIMEOUT = 60000; /** Timeout for all presence API requests. **/ private static final long PRESENCE_ENGINE_REQUESTS_TIMEOUT = 120000; /** Number of milliseconds in a week. **/ public static final long HISTORY_IS_WEEK_LONG = 7 * 24 * 60 * 60 * 1000; /** Timeout for request waiting in queue. **/ public static final long REMOVE_REQUEST_FROM_QUEUE_MILLIS = 15 * 60 * 1000; /* * The timeouts in milliseconds for the different APIs. */ /** Timeout for activities API. **/ public static final long API_REQUESTS_TIMEOUT_ACTIVITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for authentication API. **/ public static final long API_REQUESTS_TIMEOUT_AUTH = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat create conversation API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_CREATE_CONV = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat send message API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_SEND_MESSAGE = DONT_HANDLE_TIMEOUTS; /** Timeout for contacts API. **/ public static final long API_REQUESTS_TIMEOUT_CONTACTS = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for group privacy API. **/ public static final long API_REQUESTS_TIMEOUT_GROUP_PRIVACY = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for identities API. **/ public static final long API_REQUESTS_TIMEOUT_IDENTITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for presence list API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_LIST = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Timeout for presence set availability API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Enable Facebook chat. **/ public static boolean sEnableFacebookChat = true; /** * Danger! Only set to true if you know what you are doing! This logs each * response no matter if gzipped or not to the SD card under the given * request ID. */ public static boolean sEnableSuperExpensiveResponseFileLogging = false; /** * Private constructor to prevent instantiation. */ private Settings() { } } \ No newline at end of file diff --git a/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java b/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java index f736cf9..ae3fd07 100644 --- a/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java +++ b/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java @@ -1,1718 +1,1743 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.security.InvalidParameterException; import java.util.ArrayList; import android.content.ContentResolver; import android.content.Context; import android.os.Handler; import android.os.Message; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.Settings; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.DatabaseHelper.DatabaseChangeType; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.content.ThumbnailHandler; import com.vodafone360.people.service.PersistSettings; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.agent.NetworkAgent.AgentState; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.utils.LogUtils; +import com.vodafone360.people.utils.VersionUtils; /** * Implementation of engine handling Contact-sync. Contact sync is a multi-stage * process, involving sync of contacts from the native database, sync of server * contacts, fetching of groups and thumbnails. Each phase is handled by a * separate processor created and managed by the Contact sync engine. */ public class ContactSyncEngine extends BaseEngine implements IContactSyncCallback, NativeContactsApi.ContactsObserver { /** * Definition of states for Contact sync. */ public static enum State { IDLE, FETCHING_NATIVE_CONTACTS, UPDATING_NATIVE_CONTACTS, FETCHING_SERVER_CONTACTS, UPDATING_SERVER_CONTACTS, } /** * Defines the contact sync mode. The mode determines the sequence in which * the contact sync processors are run. */ public static enum Mode { NONE, FULL_SYNC_FIRST_TIME, FULL_SYNC, SERVER_SYNC, THUMBNAIL_SYNC, FETCH_NATIVE_SYNC, UPDATE_NATIVE_SYNC } /** * Mutex for thread synchronization */ private final Object mMutex = new Object(); private final UiAgent mUiAgent = mEventCallback.getUiAgent(); private final ApplicationCache mCache = mEventCallback.getApplicationCache(); /** The last known status of the contacts sync. */ private ServiceStatus mLastStatus = ServiceStatus.SUCCESS; /** * Holds parameters for the UI sync request */ private static class SyncParams { /** * the sync type */ public boolean isFull; /** * the delay before executing the request */ public long delay; /** * Constructor. * * @param isFull true if full sync, false if only a server sync * @param delay in milliseconds before executing the request */ public SyncParams(boolean isFull, long delay) { this.isFull = isFull; this.delay = delay; } } /** * Observer interface allowing interested parties to receive notification of * changes in Contact sync state. */ public static interface IContactSyncObserver { /** * Called a contact sync finishes. * * @param status SUCCESS if the sync was successful, a suitable error * code otherwise. */ void onSyncComplete(ServiceStatus status); /** * Called when the contact sync engine changes state or mode * * @param mode Current mode * @param oldState Previous state * @param newState New state */ void onContactSyncStateChange(Mode mode, State oldState, State newState); /** * Called to update interested parties on contact sync progress. This is * made up of two parts the state and the percentage. Each time the * state changes the percentage value will go back to 0. * * @param currentState What the contact sync engine is currently doing * @param percent Percentage complete for the current task */ void onProgressEvent(State currentState, int percent); } /** * Number of retries when first time sync fails */ private static final long FULL_SYNC_RETRIES = 3; /** * Counter for first time sync failures */ private int mFullSyncRetryCount = 0; /** * Current state of the contact sync engine (determines which processor is * currently active) */ private State mState = State.IDLE; /** * Current mode (or stragegy) the contact sync engine is in. The mode * determines the order which the processors are run. */ private Mode mMode = Mode.NONE; /** * A failure list (currently containing unlocalised English strings) of * contacts which could not be sync'ed to the server. */ private String mFailureList; /** * Database changed flag. Will be set to true if at any stage of the contact * sync the NowPlus database is changed. */ private boolean mDatabaseChanged; /** * Last time the database was updated (in milliseconds) */ private Long mLastDbUpdateTime; /** * DatabaseHelper object used for accessing NowPlus database. */ private DatabaseHelper mDb; /** * Currently active processor (the processor which is running) or null */ private BaseSyncProcessor mActiveProcessor; /** * The factory class which is used for creating processors for a particular * state. */ private ProcessorFactory mProcessorFactory; /** * If a contacts sync is triggered by the Contact tab, we should wait a * little bit of time before beginning any heavy background work. This * will give the main thread a chance to render its UI. */ private static final long UI_PING_SYNC_DELAY = 3 * 1000L; /** * Time to wait after the user modifies a contact before a contact sync with * the server will be initiated (in milliseconds). The timer will be reset * each time a modification takes place. */ private static final long SERVER_CONTACT_SYNC_TIMEOUT_MS = 30000L; /** * Time to wait after the user modifies a contact before a contact sync with * the native database will be initiated (in milliseconds). The timer will * be reset each time a modification takes place. */ private static final long NATIVE_CONTACT_SYNC_TIMEOUT_MS = 30000L; /** * The time to wait before requesting a new server sync when the user is * using the application. */ private static final long USER_ACTIVITY_SERVER_SYNC_TIMEOUT_MS = 20 * 60 * 1000; /** * Determines the time that should be waited between publishing database * change events. This is to prevent the UI updating too frequently during a * contact sync. The time is specified in nanoseconds. */ private static final long UI_REFRESH_WAIT_TIME_NANO = 5000000000L; private static final long SYNC_ERROR_WAIT_TIMEOUT = 300000L; /** * Specifies the time that a server sync should be started relative to * current time in milliseconds. Will be NULL when a server sync timeout is * not required. */ private volatile Long mServerSyncTimeout; /** * Specifies the time that a fetch native sync should be started relative to * current time in milliseconds. Will be NULL when a fetch native sync * timeout is not required. */ private volatile Long mFetchNativeSyncTimeout; /** * Specifies the time that a update native sync should be started relative * to current time in milliseconds. Will be NULL when a update native sync * timeout is not required. */ private volatile Long mUpdateNativeSyncTimeout; /** * Keeps track of the last time a server sync happened. */ private Long mLastServerSyncTime = 0L; /** * The content resolver object mainly used for accessing the native database */ private ContentResolver mCr = null; /** * The context of the People service */ private Context mContext = null; /** * Flag which matches the persisted equivalent in the NowPlus database state * table. Will be set to true when the first time sync is completed and will * remain true until a remove user data is performed. */ private boolean mFirstTimeSyncComplete; /** * Flag which matches the persisted equivalent in the NowPlus database state * table. Will be set to true when the first time sync is started and will * remain true until a remove user data is performed. */ private boolean mFirstTimeSyncStarted; /** * Flag which matches the persisted equivalent in the NowPlus database state * table. Will be set to true when the part of the first time sync to fetch * native contacts is started and will remain true until a remove user data * is performed. Once this flag has been set to true, the next time a full * sync is started the full sync normal mode will be used instead of full * sync first time. */ private volatile boolean mFirstTimeNativeSyncComplete; /** * True if a full sync should be started as soon as possible */ private boolean mFullSyncRequired; /** * True if a server sync should be started as soon as possible */ private boolean mServerSyncRequired; /** * True if a native fetch sync should be started as soon as possible */ private boolean mNativeFetchSyncRequired; /** * True if a native update sync should be started as soon as possible */ private boolean mNativeUpdateSyncRequired; /** * True if a server thumbnail (avatar) sync should be started as soon as * possible */ private boolean mThumbnailSyncRequired; /** * Maintains a list of contact sync observers */ private final ArrayList<IContactSyncObserver> mEventCallbackList = new ArrayList<IContactSyncObserver>(); /** * Current progress value (used to check if the progress has changed) */ private int mCurrentProgressPercent = 0; /** * Flag which is set when the current processor changes the database */ private boolean mDbChangedByProcessor; /** * Backup of the previous active request before processing the new one. */ private ServiceUiRequest mActiveUiRequestBackup = null; /** * Native Contacts API access. The appropriate version should be used * depending on the SDK. */ private final NativeContactsApi mNativeContactsApi = NativeContactsApi.getInstance(); + + /** + * True if changes on native contacts shall be detected. + */ + private final boolean mFetchNativeContactsOnChange; + + /** + * True if native contacts shall be fetched from native. + */ + private final boolean mFetchNativeContacts; + + /** + * True if changes on 360 contacts shall be forwarded to native contacts. + */ + private final boolean mUpdateNativeContacts; /** * Used to listen for NowPlus database change events. Such events will be * received when the user modifies a contact in the people application. */ private final Handler mDbChangeHandler = new Handler() { /** * Processes a database change event */ @Override public void handleMessage(Message msg) { processDbMessage(msg); } }; /** * ContactSyncEngine constructor. * * @param eventCallback Engine-event callback interface allowing engine to * report back to client on request completion. * @param context Context. * @param db Handle to People database. * @param processorFactory the processor factory */ public ContactSyncEngine(IEngineEventCallback eventCallback, Context context, DatabaseHelper db, ProcessorFactory processorFactory) { super(eventCallback); mDb = db; mEngineId = EngineId.CONTACT_SYNC_ENGINE; mContext = context; + + final boolean enableNativeSync = VersionUtils.is2XPlatform() || !Settings.DISABLE_NATIVE_SYNC_AFTER_IMPORT_ON_ANDROID_1X; + mFetchNativeContactsOnChange = Settings.ENABLE_FETCH_NATIVE_CONTACTS_ON_CHANGE && enableNativeSync; + mFetchNativeContacts = Settings.ENABLE_FETCH_NATIVE_CONTACTS && enableNativeSync; + mUpdateNativeContacts = Settings.ENABLE_UPDATE_NATIVE_CONTACTS && enableNativeSync; + // use standard processor factory if provided one is null mProcessorFactory = (processorFactory == null) ? new DefaultProcessorFactory() : processorFactory; } /** * Called after the engine has been created to do some extra initialisation. */ @Override public void onCreate() { mDb.addEventCallback(mDbChangeHandler); mCr = mContext.getContentResolver(); PersistSettings setting1 = mDb.fetchOption(PersistSettings.Option.FIRST_TIME_SYNC_STARTED); PersistSettings setting2 = mDb.fetchOption(PersistSettings.Option.FIRST_TIME_SYNC_COMPLETE); PersistSettings setting3 = mDb .fetchOption(PersistSettings.Option.FIRST_TIME_NATIVE_SYNC_COMPLETE); if (setting1 != null) { mFirstTimeSyncStarted = setting1.getFirstTimeSyncStarted(); } if (setting2 != null) { mFirstTimeSyncComplete = setting2.getFirstTimeSyncComplete(); } if (setting3 != null) { mFirstTimeNativeSyncComplete = setting3.getFirstTimeNativeSyncComplete(); } - if (Settings.ENABLE_FETCH_NATIVE_CONTACTS_ON_CHANGE) { + if (mFetchNativeContactsOnChange) { mNativeContactsApi.registerObserver(this); } if (mFirstTimeSyncComplete) { // native sync shall be performed only if the first time sync has // been completed startUpdateNativeContactSyncTimer(); startFetchNativeContactSyncTimer(); } } /** * Called just before engine is about to be closed. Cleans up resources. */ @Override public void onDestroy() { - if (Settings.ENABLE_FETCH_NATIVE_CONTACTS_ON_CHANGE) { + if (mFetchNativeContactsOnChange) { mNativeContactsApi.unregisterObserver(); } mDb.removeEventCallback(mDbChangeHandler); } /** * Triggers a full contact sync from the UI (via the service interface). * Will start a first time sync if necessary, otherwise a normal full sync * will be executed. A {@link ServiceUiRequest#NOWPLUSSYNC} event will be * sent to notify the UI when the sync has completed. */ public void addUiStartFullSync() { // reset last status to enable synchronization of contacts again mLastStatus = ServiceStatus.SUCCESS; LogUtils.logI("ContactSyncEngine.addUiStartFullSync()"); final SyncParams params = new SyncParams(true, 0); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.NOWPLUSSYNC, params); } /** * Triggers a server contact sync from the UI (via service interface). Only * the contacts will be updated, not the me profile. * * @param delay the delay in milliseconds from now when the sync should * start */ public void addUiStartServerSync(long delay) { // reset last status to enable synchronization of contacts again mLastStatus = ServiceStatus.SUCCESS; LogUtils.logI("ContactSyncEngine.addUiStartServerSync(delay=" + delay + ")"); synchronized (this) { if ((mMode == Mode.FULL_SYNC_FIRST_TIME || mMode == Mode.FULL_SYNC || mMode == Mode.SERVER_SYNC) && mState != State.IDLE) { // Already performing a server sync or full sync, just ignore // the request return; } else if (mServerSyncTimeout != null) { final long currentDelay = mServerSyncTimeout.longValue() - System.currentTimeMillis(); LogUtils.logD("delay=" + delay + ", currentDelay=" + currentDelay); if (currentDelay < delay) { // a timer on the server sync with an earlier time is // already set, just ignore the request return; } } } final SyncParams params = new SyncParams(false, delay); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.NOWPLUSSYNC, params); } /** * Tells the ContactSyncEngine that the user is actively using the service * and adjust sync timeout accordingly. Note: A server sync should occur * every 20 minutes during application intensive usage or immediately if the * application is used again after sleeping more than 20 minutes. */ public void pingUserActivity() { LogUtils.logI("ContactSyncEngine.pingUserActivity()"); long delay; synchronized (this) { final long currentDelay = System.currentTimeMillis() - mLastServerSyncTime.longValue(); if ((mMode == Mode.FULL_SYNC_FIRST_TIME || mMode == Mode.FULL_SYNC || mMode == Mode.SERVER_SYNC) && mState != State.IDLE) { // Already performing a sync, scheduling a new one in // USER_ACTIVITY_SERVER_SYNC_TIMEOUT_MS delay = USER_ACTIVITY_SERVER_SYNC_TIMEOUT_MS; } else if (currentDelay >= USER_ACTIVITY_SERVER_SYNC_TIMEOUT_MS) { // Last sync timeout has passed, schedule a new one now delay = UI_PING_SYNC_DELAY; } else if ((currentDelay < USER_ACTIVITY_SERVER_SYNC_TIMEOUT_MS) && (mServerSyncTimeout == null)) { // Last sync timeout has not passed but no new one is scheduled, // schedule one to happen accordingly with the timeout delay = USER_ACTIVITY_SERVER_SYNC_TIMEOUT_MS - currentDelay; } else { // Nothing to do, a timeout will trigger the new sync LogUtils.logD("A new sync is already scheduled in " + (USER_ACTIVITY_SERVER_SYNC_TIMEOUT_MS - currentDelay) + " milliseconds"); return; } } // TODO: check if we should call directly // startServerContactSyncTimer(delay) instead LogUtils.logD("Scheduling a new sync in " + delay + " milliseconds"); final SyncParams params = new SyncParams(false, delay); if (delay == 0) { // AA: I added it emptyUiRequestQueue(); } addUiRequestToQueue(ServiceUiRequest.NOWPLUSSYNC, params); } /** * Determines if the first time contact sync has been completed. * * @return true if completed. */ public synchronized boolean isFirstTimeSyncComplete() { return mFirstTimeSyncComplete; } // TODO: RE-ENABLE SYNC VIA SYSTEM // /** // * Check if syncing is ongoing // * @return true if syncing is ongoing, false if it is not // */ // public synchronized boolean isSyncing() { // return mMode != Mode.NONE; // } /** * Add observer of Contact-sync. * * @param observer IContactSyncObserver handle. */ public synchronized void addEventCallback(IContactSyncObserver observer) { if (!mEventCallbackList.contains(observer)) { mEventCallbackList.add(observer); } } /** * Starts a timer to trigger a server contact sync in a short while * (normally around 30 seconds). */ private void startServerContactSyncTimer(long delay) { if (!Settings.ENABLE_SERVER_CONTACT_SYNC) { return; } synchronized (this) { if (mServerSyncTimeout == null) { LogUtils .logI("ContactSyncEngine - will sync contacts with server shortly... (in about " + delay + " milliseconds)"); } mServerSyncTimeout = System.currentTimeMillis() + delay; if (mCurrentTimeout == null || mCurrentTimeout.compareTo(mServerSyncTimeout) > 0) { mCurrentTimeout = mServerSyncTimeout; } } if (mCurrentTimeout.equals(mServerSyncTimeout)) { mEventCallback.kickWorkerThread(); } } /** * Starts a timer to trigger a fetch native contact sync in a short while * (normally around 30 seconds). */ private void startFetchNativeContactSyncTimer() { - if (!Settings.ENABLE_FETCH_NATIVE_CONTACTS) { + if (!mFetchNativeContacts) { return; } synchronized (this) { if (mFetchNativeSyncTimeout == null) { LogUtils.logI("ContactSyncEngine - will fetch native contacts shortly..."); } mFetchNativeSyncTimeout = System.currentTimeMillis() + NATIVE_CONTACT_SYNC_TIMEOUT_MS; if (mCurrentTimeout == null || mCurrentTimeout.compareTo(mFetchNativeSyncTimeout) > 0) { mCurrentTimeout = mFetchNativeSyncTimeout; mEventCallback.kickWorkerThread(); } } } /** * Starts a timer to trigger a update native contact sync in a short while * (normally around 30 seconds). */ private void startUpdateNativeContactSyncTimer() { - if (!Settings.ENABLE_UPDATE_NATIVE_CONTACTS) { + if (!mUpdateNativeContacts) { return; } synchronized (this) { if (mUpdateNativeSyncTimeout == null) { LogUtils.logI("ContactSyncEngine - will update native contacts shortly..."); } mUpdateNativeSyncTimeout = System.currentTimeMillis() + NATIVE_CONTACT_SYNC_TIMEOUT_MS; if (mCurrentTimeout == null || mCurrentTimeout.compareTo(mUpdateNativeSyncTimeout) > 0) { mCurrentTimeout = mUpdateNativeSyncTimeout; } } if (mCurrentTimeout.equals(mUpdateNativeSyncTimeout)) { mEventCallback.kickWorkerThread(); } } /** * Helper function to start a processor running. * * @param processor Processor which was created by processor factory. */ private void startProcessor(BaseSyncProcessor processor) { if (mActiveProcessor != null) { LogUtils.logE("ContactSyncEngine.startProcessor - Cannot start " + processor.getClass() + ", because the processor " + mActiveProcessor.getClass() + " is running"); throw new RuntimeException( "ContactSyncEngine - Cannot start processor while another is active"); } mActiveProcessor = processor; mCurrentProgressPercent = -1; mDbChangedByProcessor = false; processor.start(); } /** * Framework function to determine when the contact sync engine next needs * to run. * * @return -1 if the engine does not need to run 0 if the engine needs to * run as soon as possible x where x > 0, the engine needs to run * when current time in milliseconds >= x */ @Override public long getNextRunTime() { if (mLastStatus != ServiceStatus.SUCCESS) { return getCurrentTimeout(); } if (isCommsResponseOutstanding()) { return 0; } if (isUiRequestOutstanding() && mActiveUiRequest == null) { return 0; } if (readyToStartServerSync()) { if (mFullSyncRequired || mServerSyncRequired || mThumbnailSyncRequired) { return 0; } else if (mFirstTimeSyncStarted && !mFirstTimeSyncComplete && mFullSyncRetryCount < FULL_SYNC_RETRIES) { mFullSyncRetryCount++; mFullSyncRequired = true; return 0; } } if (mNativeFetchSyncRequired && readyToStartFetchNativeSync()) { return 0; } if (mNativeUpdateSyncRequired && readyToStartUpdateNativeSync()) { return 0; } return getCurrentTimeout(); } /** * Called by framework when {@link #getNextRunTime()} reports that the * engine needs to run, to carry out the next task. Each task should not * take longer than a second to complete. */ @Override public void run() { if (processTimeout()) { return; } if (isUiRequestOutstanding()) { mActiveUiRequestBackup = mActiveUiRequest; if (processUiQueue()) { return; } } if (isCommsResponseOutstanding() && processCommsInQueue()) { return; } if (readyToStartServerSync()) { if (mThumbnailSyncRequired) { startThumbnailSync(); return; } if (mFullSyncRequired) { startFullSync(); return; } if (mServerSyncRequired) { startServerSync(); return; } } if (mNativeFetchSyncRequired && readyToStartFetchNativeSync()) { startFetchNativeSync(); return; } if (mNativeUpdateSyncRequired && readyToStartUpdateNativeSync()) { startUpdateNativeSync(); return; } } /** * Called by base class when a contact sync UI request has been completed. * Not currently used. */ @Override protected void onRequestComplete() { } /** * Called by base class when a timeout has been completed. If there is an * active processor the timeout event will be passed to it, otherwise the * engine will check if it needs to schedule a new sync and set the next * pending timeout. */ @Override protected void onTimeoutEvent() { if (mActiveProcessor != null) { mActiveProcessor.onTimeoutEvent(); } else { startSyncIfRequired(); setTimeoutIfRequired(); } } /** * Based on current timeout values schedules a new sync if required. */ private void startSyncIfRequired() { if (mFirstTimeSyncStarted && !mFirstTimeSyncComplete) { mFullSyncRequired = true; mFullSyncRetryCount = 0; } long currentTimeMs = System.currentTimeMillis(); if (mServerSyncTimeout != null && mServerSyncTimeout.longValue() < currentTimeMs) { mServerSyncRequired = true; mServerSyncTimeout = null; } else if (mFetchNativeSyncTimeout != null && mFetchNativeSyncTimeout.longValue() < currentTimeMs) { mNativeFetchSyncRequired = true; mFetchNativeSyncTimeout = null; } else if (mUpdateNativeSyncTimeout != null && mUpdateNativeSyncTimeout.longValue() < currentTimeMs) { mNativeUpdateSyncRequired = true; mUpdateNativeSyncTimeout = null; } } /** * Called when a response to a request or a push message is received from * the server. Push messages are processed by the engine, responses are * passed to the active processor. * * @param resp Response or push message received */ @Override protected void processCommsResponse(DecodedResponse resp) { if (processPushEvent(resp)) { return; } if (resp.mDataTypes != null && resp.mDataTypes.size() > 0) { LogUtils.logD("ContactSyncEngine.processCommsResponse: Req ID = " + resp.mReqId + ", type = " + resp.mDataTypes.get(0).getType()); } else { LogUtils.logD("ContactSyncEngine.processCommsResponse: Req ID = " + resp.mReqId + ", type = NULL"); } if (mActiveProcessor != null) { mActiveProcessor.processCommsResponse(resp); } } /** * Determines if a given response is a push message and processes in this * case TODO: we need the check for Me Profile be migrated to he new engine * * @param resp Response to check and process * @return true if the response was processed */ private boolean processPushEvent(DecodedResponse resp) { if (resp.mDataTypes == null || resp.mDataTypes.size() == 0) { return false; } BaseDataType dataType = resp.mDataTypes.get(0); if ((dataType == null) || dataType.getType() != BaseDataType.PUSH_EVENT_DATA_TYPE) { return false; } PushEvent pushEvent = (PushEvent)dataType; LogUtils.logV("Push Event Type = " + pushEvent.mMessageType); switch (pushEvent.mMessageType) { case CONTACTS_CHANGE: LogUtils .logI("ContactSyncEngine.processCommsResponse - Contacts changed push message received"); mServerSyncRequired = true; EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); // fetch // the // newest // groups mEventCallback.kickWorkerThread(); break; case SYSTEM_NOTIFICATION: LogUtils .logI("ContactSyncEngine.processCommsResponse - System notification push message received"); break; default: // do nothing. break; } return true; } /** * Called by base class to process a NOWPLUSSYNC UI request. This will be * called to process a full sync or server sync UI request. * * @param requestId ID of the request to process, only * ServiceUiRequest.NOWPLUSSYNC is currently supported. * @param data Type is determined by request ID, in case of NOWPLUSSYNC this * is a flag which determines if a full sync is required (true = * full sync, false = server sync). */ @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { switch (requestId) { case NOWPLUSSYNC: final SyncParams params = (SyncParams)data; if (params.isFull) { // delayed full sync is not supported currently, start it // immediately clearCurrentSyncAndPatchBaseEngine(); mFullSyncRetryCount = 0; startFullSync(); } else { if (params.delay <= 0) { clearCurrentSyncAndPatchBaseEngine(); if (readyToStartServerSync()) { startServerSync(); } else { mServerSyncRequired = true; } } else { startServerContactSyncTimer(params.delay); } } break; default: // do nothing. break; } } /** * Called by the run function when the {@link #mCancelSync} flag is set to * true. Cancels the active processor and completes the current UI request. */ private void cancelSync() { if (mActiveProcessor != null) { mActiveProcessor.cancel(); mActiveProcessor = null; } completeSync(ServiceStatus.USER_CANCELLED); } /** * Clears the current sync and make sure that if we cancel a previous sync, * it doesn't notify a wrong UI request. TODO: Find another way to not have * to hack the BaseEngine! */ private void clearCurrentSyncAndPatchBaseEngine() { // Cancel background sync if (mActiveProcessor != null) { // the mActiveUiRequest is already the new one so if // onCompleteUiRequest(Error) is called, // this will reset it to null even if we didn't start to process it. ServiceUiRequest newActiveUiRequest = mActiveUiRequest; mActiveUiRequest = mActiveUiRequestBackup; mActiveProcessor.cancel(); // restore the active UI request... mActiveUiRequest = newActiveUiRequest; mActiveProcessor = null; } newState(State.IDLE); } /** * Checks if a server sync can be started based on network conditions and * engine state * * @return true if a sync can be started, false otherwise. */ private boolean readyToStartServerSync() { if (!Settings.ENABLE_SERVER_CONTACT_SYNC) { return false; } if (!EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete()) { return false; } if (!mFirstTimeSyncStarted) { return false; } if (mState != State.IDLE || NetworkAgent.getAgentState() != AgentState.CONNECTED) { return false; } return true; } /** * Checks if a fetch native sync can be started based on network conditions * and engine state * * @return true if a sync can be started, false otherwise. */ private boolean readyToStartFetchNativeSync() { - if (!Settings.ENABLE_FETCH_NATIVE_CONTACTS) { + if (!mFetchNativeContacts) { return false; } if (!mFirstTimeSyncStarted) { return false; } if (mState != State.IDLE) { return false; } return true; } /** * Checks if a update native sync can be started based on network conditions * and engine state * * @return true if a sync can be started, false otherwise. */ private boolean readyToStartUpdateNativeSync() { - if (!Settings.ENABLE_UPDATE_NATIVE_CONTACTS) { + if (!mUpdateNativeContacts) { return false; } if (!mFirstTimeSyncStarted) { return false; } if (mState != State.IDLE) { return false; } return true; } /** * Starts a full sync. If the native contacts haven't yet been fetched then * a first time sync will be started, otherwise will start a normal full * sync. Full syncs are always initiated from the UI (via UI request). */ public void startFullSync() { mFailureList = ""; mDatabaseChanged = false; setFirstTimeSyncStarted(true); mServerSyncTimeout = null; mFullSyncRequired = false; if (mFirstTimeNativeSyncComplete) { LogUtils.logI("ContactSyncEngine.startFullSync - user triggered sync"); mMode = Mode.FULL_SYNC; nextTaskFullSyncNormal(); } else { LogUtils.logI("ContactSyncEngine.startFullSync - first time sync"); mMode = Mode.FULL_SYNC_FIRST_TIME; nextTaskFullSyncFirstTime(); } } /** * Starts a server sync. This will only sync contacts with the server and * will not include the me profile. Thumbnails are not fetched as part of * this sync, but will be fetched as part of a background sync afterwards. */ private void startServerSync() { mServerSyncRequired = false; mFailureList = ""; mDatabaseChanged = false; mMode = Mode.SERVER_SYNC; mServerSyncTimeout = null; setTimeoutIfRequired(); nextTaskServerSync(); } /** * Starts a background thumbnail sync */ private void startThumbnailSync() { mThumbnailSyncRequired = false; mFailureList = ""; mDatabaseChanged = false; mMode = Mode.THUMBNAIL_SYNC; nextTaskThumbnailSync(); } /** * Starts a background fetch native contacts sync */ private void startFetchNativeSync() { mNativeFetchSyncRequired = false; mFailureList = ""; mDatabaseChanged = false; mMode = Mode.FETCH_NATIVE_SYNC; mFetchNativeSyncTimeout = null; setTimeoutIfRequired(); nextTaskFetchNativeContacts(); } /** * Starts a background update native contacts sync */ private void startUpdateNativeSync() { mNativeUpdateSyncRequired = false; mFailureList = ""; mDatabaseChanged = false; mMode = Mode.UPDATE_NATIVE_SYNC; mUpdateNativeSyncTimeout = null; setTimeoutIfRequired(); nextTaskUpdateNativeContacts(); } /** * Helper function to start the fetch native contacts processor * + * @param isFirstTimeSync true if importing native contacts for the first time * @return if this type of sync is enabled in the settings, false otherwise. */ - private boolean startFetchNativeContacts() { - if (Settings.ENABLE_FETCH_NATIVE_CONTACTS) { + private boolean startFetchNativeContacts(boolean isFirstTimeSync) { + if (mFetchNativeContacts || (Settings.ENABLE_FETCH_NATIVE_CONTACTS && isFirstTimeSync)) { newState(State.FETCHING_NATIVE_CONTACTS); startProcessor(mProcessorFactory.create(ProcessorFactory.FETCH_NATIVE_CONTACTS, this, mDb, mContext, mCr)); return true; } return false; } /** * Helper function to start the update native contacts processor * * @return if this type of sync is enabled in the settings, false otherwise. */ private boolean startUpdateNativeContacts() { - if (Settings.ENABLE_UPDATE_NATIVE_CONTACTS) { + if (mUpdateNativeContacts) { newState(State.UPDATING_NATIVE_CONTACTS); startProcessor(mProcessorFactory.create(ProcessorFactory.UPDATE_NATIVE_CONTACTS, this, mDb, null, mCr)); return true; } return false; } /** * Helper function to start the download server contacts processor * * @return if this type of sync is enabled in the settings, false otherwise. */ private boolean startDownloadServerContacts() { if (Settings.ENABLE_SERVER_CONTACT_SYNC) { newState(State.FETCHING_SERVER_CONTACTS); startProcessor(mProcessorFactory.create(ProcessorFactory.DOWNLOAD_SERVER_CONTACTS, this, mDb, mContext, null)); return true; } return false; } /** * Helper function to start the upload server contacts processor * * @return if this type of sync is enabled in the settings, false otherwise. */ private boolean startUploadServerContacts() { if (Settings.ENABLE_SERVER_CONTACT_SYNC) { newState(State.UPDATING_SERVER_CONTACTS); startProcessor(mProcessorFactory.create(ProcessorFactory.UPLOAD_SERVER_CONTACTS, this, mDb, mContext, null)); return true; } return false; } /** * Helper function to start the download thumbnails processor * * @return if this type of sync is enabled in the settings, false otherwise. */ private boolean startDownloadServerThumbnails() { if (Settings.ENABLE_THUMBNAIL_SYNC) { ThumbnailHandler.getInstance().downloadContactThumbnails(); return true; } return false; } /** * Called by a processor when it has completed. Will move to the next task. * When the active contact sync has totally finished, will complete any * pending UI request. * * @param status Status of the sync from the processor, any error codes will * stop the sync. * @param failureList Contains a list of sync failure information which can * be used as a summary at the end. Otherwise should be an empty * string. * @param data Any processor specific data to pass back to the engine. Not * currently used. */ @Override public void onProcessorComplete(ServiceStatus status, String failureList, Object data) { if (mState == State.IDLE) { return; } if (mActiveProcessor != null) { mActiveProcessor.onComplete(); } mActiveProcessor = null; mFailureList += failureList; if (status != ServiceStatus.SUCCESS) { LogUtils.logE("ContactSyncEngine.onProcessorComplete - Failed during " + mState + " with error " + status); completeSync(status); return; } if (mDbChangedByProcessor) { switch (mState) { case FETCHING_NATIVE_CONTACTS: mServerSyncRequired = true; break; case FETCHING_SERVER_CONTACTS: mThumbnailSyncRequired = true; - mNativeUpdateSyncRequired = true; + if (mUpdateNativeContacts) { + mNativeUpdateSyncRequired = true; + } break; default: // Do nothing. break; } } switch (mMode) { case FULL_SYNC_FIRST_TIME: nextTaskFullSyncFirstTime(); break; case FULL_SYNC: nextTaskFullSyncNormal(); break; case SERVER_SYNC: nextTaskServerSync(); break; case FETCH_NATIVE_SYNC: nextTaskFetchNativeContacts(); break; case UPDATE_NATIVE_SYNC: nextTaskUpdateNativeContacts(); break; case THUMBNAIL_SYNC: nextTaskThumbnailSync(); break; default: LogUtils.logE("ContactSyncEngine.onProcessorComplete - Unexpected mode: " + mMode); completeSync(ServiceStatus.ERROR_SYNC_FAILED); } } /** * Moves to the next state for the full sync first time mode, and runs the * appropriate processor. Completes the UI request when the sync is complete * (if one is pending). */ private void nextTaskFullSyncFirstTime() { switch (mState) { case IDLE: - if (startFetchNativeContacts()) { + if (startFetchNativeContacts(true)) { return; } // Fall through case FETCHING_NATIVE_CONTACTS: setFirstTimeNativeSyncComplete(true); if (startUploadServerContacts()) { return; } // Fall through case UPDATING_SERVER_CONTACTS: if (startDownloadServerContacts()) { return; } // Fall through case FETCHING_SERVER_CONTACTS: mThumbnailSyncRequired = true; mLastServerSyncTime = System.currentTimeMillis(); setFirstTimeSyncComplete(true); completeSync(ServiceStatus.SUCCESS); return; default: LogUtils.logE("ContactSyncEngine.nextTaskFullSyncFirstTime - Unexpected state: " + mState); completeSync(ServiceStatus.ERROR_SYNC_FAILED); } } /** * Moves to the next state for the full sync normal mode, and runs the * appropriate processor. Completes the UI request when the sync is complete * (if one is pending). */ private void nextTaskFullSyncNormal() { switch (mState) { case IDLE: if (startDownloadServerContacts()) { return; } // Fall through case FETCHING_SERVER_CONTACTS: if (startUploadServerContacts()) { return; } // Fall through case UPDATING_SERVER_CONTACTS: // force a thumbnail sync in case nothing in the database // changed but we still have failing // thumbnails that we should retry to download mThumbnailSyncRequired = true; mLastServerSyncTime = System.currentTimeMillis(); setFirstTimeSyncComplete(true); completeSync(ServiceStatus.SUCCESS); return; default: LogUtils.logE("ContactSyncEngine.nextTaskFullSyncNormal - Unexpected state: " + mState); completeSync(ServiceStatus.ERROR_SYNC_FAILED); } } /** * Moves to the next state for the fetch native contacts mode, and runs the * appropriate processor. Completes the UI request when the sync is complete * (if one is pending). */ private void nextTaskFetchNativeContacts() { switch (mState) { case IDLE: - if (startFetchNativeContacts()) { + if (startFetchNativeContacts(false)) { return; } // Fall through case FETCHING_NATIVE_CONTACTS: if (startUploadServerContacts()) { return; } // Fall through case UPDATING_SERVER_CONTACTS: completeSync(ServiceStatus.SUCCESS); return; default: LogUtils.logE("ContactSyncEngine.nextTaskFetchNativeContacts - Unexpected state: " + mState); completeSync(ServiceStatus.ERROR_SYNC_FAILED); } } /** * Moves to the next state for the update native contacts mode, and runs the * appropriate processor. Completes the UI request when the sync is complete * (if one is pending). */ private void nextTaskUpdateNativeContacts() { switch (mState) { case IDLE: if (startUpdateNativeContacts()) { return; } completeSync(ServiceStatus.SUCCESS); return; // Fall through case UPDATING_NATIVE_CONTACTS: completeSync(ServiceStatus.SUCCESS); return; default: LogUtils.logE("ContactSyncEngine.nextTaskUpdateNativeContacts - Unexpected state: " + mState); completeSync(ServiceStatus.ERROR_SYNC_FAILED); } } /** * Moves to the next state for the server sync mode, and runs the * appropriate processor. Completes the UI request when the sync is complete * (if one is pending). */ private void nextTaskServerSync() { switch (mState) { case IDLE: if (startDownloadServerContacts()) { return; } // Fall through case FETCHING_SERVER_CONTACTS: if (startUploadServerContacts()) { return; } // Fall through case UPDATING_SERVER_CONTACTS: // force a thumbnail sync in case nothing in the database // changed but we still have failing // thumbnails that we should retry to download mThumbnailSyncRequired = true; mLastServerSyncTime = System.currentTimeMillis(); completeSync(ServiceStatus.SUCCESS); return; default: LogUtils.logE("ContactSyncEngine.nextTaskServerSync - Unexpected state: " + mState); completeSync(ServiceStatus.ERROR_SYNC_FAILED); } } /** * Moves to the next state for the thumbnail sync mode, and runs the * appropriate processor. Completes the UI request when the sync is complete * (if one is pending). */ private void nextTaskThumbnailSync() { switch (mState) { case IDLE: if (startDownloadServerThumbnails()) { return; } default: LogUtils.logE("ContactSyncEngine.nextTaskThumbnailSync - Unexpected state: " + mState); completeSync(ServiceStatus.ERROR_SYNC_FAILED); } } /** * Changes the state of the engine and informs the observers. * * @param newState The new state */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("ContactSyncEngine.newState: " + oldState + " -> " + mState); fireStateChangeEvent(mMode, oldState, mState); } /** * Called when the current mode has finished all the sync tasks. Completes * the UI request if one is pending, sends an event to the observer and a * database change event if necessary. * * @param status The overall status of the contact sync. */ private void completeSync(ServiceStatus status) { if (mState == State.IDLE) { return; } if (mDatabaseChanged) { LogUtils.logD("ContactSyncEngine.completeSync - Firing Db changed event"); mDb.fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, true); mDatabaseChanged = false; } mActiveProcessor = null; newState(State.IDLE); mMode = Mode.NONE; completeUiRequest(status, mFailureList); mCache.setSyncStatus(new SyncStatus(status)); mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UPDATE_SYNC_STATE, null); if (mFirstTimeSyncComplete) { fireSyncCompleteEvent(status); } if (ServiceStatus.SUCCESS == status) { startSyncIfRequired(); } else { setTimeout(SYNC_ERROR_WAIT_TIMEOUT); } mLastStatus = status; setTimeoutIfRequired(); } /** * Sets the current timeout to the next pending timer and kicks the engine * if necessary. */ private synchronized void setTimeoutIfRequired() { Long initTimeout = mCurrentTimeout; if (mCurrentTimeout == null || (mServerSyncTimeout != null && mServerSyncTimeout.compareTo(mCurrentTimeout) < 0)) { mCurrentTimeout = mServerSyncTimeout; } if (mCurrentTimeout == null || (mFetchNativeSyncTimeout != null && mFetchNativeSyncTimeout .compareTo(mCurrentTimeout) < 0)) { mCurrentTimeout = mFetchNativeSyncTimeout; } if (mCurrentTimeout == null || (mUpdateNativeSyncTimeout != null && mUpdateNativeSyncTimeout .compareTo(mCurrentTimeout) < 0)) { mCurrentTimeout = mUpdateNativeSyncTimeout; } if (mCurrentTimeout != null && !mCurrentTimeout.equals(initTimeout)) { mEventCallback.kickWorkerThread(); } } /** * Called by the active processor to indicate that the NowPlus database has * changed. */ @Override public void onDatabaseChanged() { mDatabaseChanged = true; mDbChangedByProcessor = true; final long currentTime = System.nanoTime(); if (mLastDbUpdateTime == null || mLastDbUpdateTime.longValue() + UI_REFRESH_WAIT_TIME_NANO < currentTime) { LogUtils.logD("ContactSyncEngine.onDatabaseChanged - Updating UI..."); mDatabaseChanged = false; mLastDbUpdateTime = currentTime; mDb.fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, true); } } /** * Used by processors to fetch this engine. The BaseEngine reference is * needed to send requests to the server. * * @return The BaseEngine reference of this engine. */ @Override public BaseEngine getEngine() { return this; } /** * Used by active processor to set a timeout. * * @param timeout Timeout value based on current time in milliseconds */ @Override public void setTimeout(long timeout) { super.setTimeout(timeout); } /** * Used by active processor to set the current progress. * * @param SyncStatus Status of the processor, must not be NULL. * @throws InvalidParameterException when SyncStatus is NULL. */ @Override public void setSyncStatus(final SyncStatus syncStatus) { if (syncStatus == null) { throw new InvalidParameterException( "ContactSyncEngine.setSyncStatus() SyncStatus cannot be NULL"); } mCache.setSyncStatus(syncStatus); mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UPDATE_SYNC_STATE, null); if (mState != State.IDLE && syncStatus.getProgress() != mCurrentProgressPercent) { mCurrentProgressPercent = syncStatus.getProgress(); LogUtils.logI("ContactSyncEngine: Task " + mState + " is " + syncStatus.getProgress() + "% complete"); fireProgressEvent(mState, syncStatus.getProgress()); } } /** * Called by active processor when issuing a request to store the request id * in the base engine class. */ @Override public void setActiveRequestId(int reqId) { setReqId(reqId); } /** * Helper function to update the database when the state of the * {@link #mFirstTimeSyncStarted} flag changes. * * @param value New value to the flag. True indicates that first time sync * has been started. The flag is never set to false again by the * engine, it will be only set to false when a remove user data * is done (and the database is deleted). * @return SUCCESS or a suitable error code if the database could not be * updated. */ private ServiceStatus setFirstTimeSyncStarted(boolean value) { if (mFirstTimeSyncStarted == value) { return ServiceStatus.SUCCESS; } PersistSettings setting = new PersistSettings(); setting.putFirstTimeSyncStarted(value); ServiceStatus status = mDb.setOption(setting); if (ServiceStatus.SUCCESS == status) { synchronized (this) { mFirstTimeSyncStarted = value; } } return status; } /** * Helper function to update the database when the state of the * {@link #mFirstTimeSyncComplete} flag changes. * * @param value New value to the flag. True indicates that first time sync * has been completed. The flag is never set to false again by * the engine, it will be only set to false when a remove user * data is done (and the database is deleted). * @return SUCCESS or a suitable error code if the database could not be * updated. */ private ServiceStatus setFirstTimeSyncComplete(boolean value) { if (mFirstTimeSyncComplete == value) { return ServiceStatus.SUCCESS; } PersistSettings setting = new PersistSettings(); setting.putFirstTimeSyncComplete(value); ServiceStatus status = mDb.setOption(setting); if (ServiceStatus.SUCCESS == status) { synchronized (this) { mFirstTimeSyncComplete = value; } } return status; } /** * Helper function to update the database when the state of the * {@link #mFirstTimeNativeSyncComplete} flag changes. * * @param value New value to the flag. True indicates that the native fetch * part of the first time sync has been completed. The flag is * never set to false again by the engine, it will be only set to * false when a remove user data is done (and the database is * deleted). * @return SUCCESS or a suitable error code if the database could not be * updated. */ private ServiceStatus setFirstTimeNativeSyncComplete(boolean value) { if (mFirstTimeSyncComplete == value) { return ServiceStatus.SUCCESS; } PersistSettings setting = new PersistSettings(); setting.putFirstTimeNativeSyncComplete(value); ServiceStatus status = mDb.setOption(setting); if (ServiceStatus.SUCCESS == status) { synchronized (this) { mFirstTimeNativeSyncComplete = value; } } return status; } /** * Called when a database change event is received from the DatabaseHelper. * Only internal database change events are processed, external change * events are generated by the contact sync engine. * * @param msg The message indicating the type of event */ private void processDbMessage(Message message) { final ServiceUiRequest event = ServiceUiRequest.getUiEvent(message.what); switch (event) { case DATABASE_CHANGED_EVENT: if (message.arg1 == DatabaseHelper.DatabaseChangeType.CONTACTS.ordinal() && message.arg2 == 0) { LogUtils.logV("ContactSyncEngine.processDbMessage - Contacts have changed"); // startMeProfileSyncTimer(); startServerContactSyncTimer(SERVER_CONTACT_SYNC_TIMEOUT_MS); startUpdateNativeContactSyncTimer(); } break; default: // Do nothing. break; } } /** * Notifies observers when a state or mode change occurs. * * @param mode Current mode * @param previousState State before the change * @param newState State after the change. */ private void fireStateChangeEvent(Mode mode, State previousState, State newState) { ArrayList<IContactSyncObserver> tempList = new ArrayList<IContactSyncObserver>(); synchronized (this) { tempList.addAll(mEventCallbackList); } for (IContactSyncObserver observer : tempList) { observer.onContactSyncStateChange(mode, previousState, newState); } if (Settings.ENABLED_DATABASE_TRACE) { // DatabaseHelper.trace(false, "State newState[" + newState + "]" + // mDb.copyDatabaseToSd("")); } } /** * Notifies observers when a contact sync complete event occurs. * * @param status SUCCESS or a suitable error code */ private void fireSyncCompleteEvent(ServiceStatus status) { ArrayList<IContactSyncObserver> tempList = new ArrayList<IContactSyncObserver>(); synchronized (this) { tempList.addAll(mEventCallbackList); } for (IContactSyncObserver observer : tempList) { observer.onSyncComplete(status); } } /** * Notifies observers when the progress value changes for the current sync. * * @param currentState Current sync task being processed * @param percent Progress of task (between 0 and 100 percent) */ private void fireProgressEvent(State currentState, int percent) { ArrayList<IContactSyncObserver> tempList = new ArrayList<IContactSyncObserver>(); synchronized (this) { tempList.addAll(mEventCallbackList); } for (IContactSyncObserver observer : tempList) { observer.onProgressEvent(currentState, percent); } } /** * Called by framework to warn the engine that a remove user data is about * to start. Sets flags and kicks the engine. */ @Override public void onReset() { synchronized (this) { mFullSyncRetryCount = 0; mState = State.IDLE; mMode = Mode.NONE; mFailureList = null; mDatabaseChanged = false; mLastDbUpdateTime = 0L; mActiveProcessor = null; mServerSyncTimeout = null; mFetchNativeSyncTimeout = null; mUpdateNativeSyncTimeout = null; mLastServerSyncTime = 0L; mFirstTimeSyncComplete = false; mFirstTimeSyncStarted = false; mFirstTimeNativeSyncComplete = false; mFullSyncRequired = false; mServerSyncRequired = false; mNativeFetchSyncRequired = false; mNativeUpdateSyncRequired = false; mThumbnailSyncRequired = false; mCurrentProgressPercent = 0; mDbChangedByProcessor = false; mActiveUiRequestBackup = null; } super.onReset(); ThumbnailHandler.getInstance().reset(); } /** * @see NativeContactsApi.ContactsObserver#onChange() */ @Override public void onChange() { LogUtils.logD("ContactSyncEngine.onChange(): changes detected on native side."); // changes detected on native side, start the timer for the // FetchNativeContacts processor. startFetchNativeContactSyncTimer(); } }
360/360-Engine-for-Android
63f78f735ad3564a2bff1b50d2dbe51bf4462118
fix broken junit tests for engine project
diff --git a/tests/src/com/vodafone360/people/tests/TestModule.java b/tests/src/com/vodafone360/people/tests/TestModule.java index ef6210a..3ea45ab 100644 --- a/tests/src/com/vodafone360/people/tests/TestModule.java +++ b/tests/src/com/vodafone360/people/tests/TestModule.java @@ -1,1077 +1,1077 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.tests; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.provider.Contacts; import android.text.format.Time; import android.util.Log; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineNativeTypes; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.database.tables.ContactDetailsTable.Field; import com.vodafone360.people.datatypes.ActivityItem; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactDetail; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.ActivityItem.Flag; import com.vodafone360.people.datatypes.ActivityItem.Type; import com.vodafone360.people.datatypes.ActivityItem.Visibility; import com.vodafone360.people.datatypes.VCardHelper.Organisation; @SuppressWarnings("deprecation") public class TestModule { private static final Random RANDOM = new Random(); private static final int TABLE_SIZE = 25; public static final int CONTACT_METHODS_KIND_EMAIL = 1; public static final int CONTACT_METHODS_KIND_ADDRESS = 2; public enum NativeNameType { NO_NAME, SINGLE_NAME, DOUBLE_NAME, FULL_NAME_NO_TITLE, FULL_NAME } public static class NativeDetail { public String mValue1; public String mValue2; public String mValue3; public boolean mIsPrimary; public Integer mId; } public static class NativeContactDetails { public Integer mId; public VCardHelper.Name mName; public String mNote; public final List<NativeDetail> mPhoneList = new ArrayList<NativeDetail>(); public final List<NativeDetail> mEmailList = new ArrayList<NativeDetail>(); public final List<NativeDetail> mAddressList = new ArrayList<NativeDetail>(); public final List<NativeDetail> mOrgList = new ArrayList<NativeDetail>(); public final List<NativeDetail> mTitleList = new ArrayList<NativeDetail>(); } public TestModule() { } public ContactDetail createDummyDetailsName() { ContactDetail detail = new ContactDetail(); VCardHelper.Name name = createDummyName(); detail.setName(name); detail.key = ContactDetail.DetailKeys.VCARD_NAME; detail.keyType = null; return detail; } private VCardHelper.Name createDummyName() { VCardHelper.Name name = new VCardHelper.Name(); switch (generateRandomInt() % 6) { case 0: name.title = "Mr"; break; case 1: name.title = "Miss"; break; case 2: name.title = "Mrs"; break; case 3: name.title = "Ms"; break; case 4: name.title = "Dr"; break; case 5: name.title = null; } name.firstname = generateRandomString(); name.surname = generateRandomString(); return name; } public ContactDetail createDummyDetailsNickname(ContactDetail name) { ContactDetail nickname = new ContactDetail(); nickname.setValue(name.getName().toString(), ContactDetail.DetailKeys.VCARD_NICKNAME, null); return nickname; } final private ContactDetail.DetailKeys[] keysList = {ContactDetail.DetailKeys.VCARD_DATE, ContactDetail.DetailKeys.PRESENCE_TEXT, ContactDetail.DetailKeys.VCARD_EMAIL, ContactDetail.DetailKeys.VCARD_PHONE, ContactDetail.DetailKeys.VCARD_BUSINESS, ContactDetail.DetailKeys.VCARD_ADDRESS, ContactDetail.DetailKeys.VCARD_URL, ContactDetail.DetailKeys.VCARD_ROLE, ContactDetail.DetailKeys.VCARD_NOTE }; public void createDummyDetailsData(ContactDetail detail) { ContactDetail.DetailKeys key = keysList[generateRandomInt() % keysList.length]; detail.key = key; detail.keyType = null; switch (key) { case PRESENCE_TEXT: detail.setValue(generateRandomString(), key, null); detail.alt=""; break; case VCARD_DATE: Time time = new Time(); time.parse("20080605"); detail.setDate(time, ContactDetail.DetailKeyTypes.BIRTHDAY); break; case VCARD_IMADDRESS: detail.setValue(generateRandomString() + "@mail.co.uk", key, null); break; case VCARD_EMAIL: detail.setEmail(generateRandomString() + "@mail.co.uk", ContactDetail.DetailKeyTypes.HOME); break; case VCARD_PHONE: detail.setTel("07967 123456", ContactDetail.DetailKeyTypes.CELL); break; case VCARD_BUSINESS: case VCARD_ADDRESS: VCardHelper.PostalAddress address = new VCardHelper.PostalAddress(); address.addressLine1 = "123 Any road"; address.addressLine2 = "Any location"; address.city = "Any City"; address.county = "Any County"; address.postCode = "M6 2AY"; address.country = "United Kingdom"; detail.setPostalAddress(address, ContactDetail.DetailKeyTypes.HOME); break; case VCARD_URL: case VCARD_INTERNET_ADDRESS: detail.setValue("www." + generateRandomString() + "anyaddress.co.uk", key, null); break; case VCARD_ROLE: detail.setValue(generateRandomString(), key, null); break; case VCARD_NOTE: { String randomString = new String(); for (int i = 0 ; i < generateRandomInt() % 10 ; i++) { randomString += generateRandomString() + " "; } detail.setValue(randomString, key, null); break; } } } public void modifyDummyDetailsData(ContactDetail detail) { switch (detail.key) { case VCARD_NAME: VCardHelper.Name name = createDummyName(); detail.setName(name); break; case PRESENCE_TEXT: detail.setValue(generateRandomString(), detail.key, null); break; case VCARD_DATE: Time time = new Time(); time.parse("20080605"); detail.setDate(time, ContactDetail.DetailKeyTypes.BIRTHDAY); break; case VCARD_IMADDRESS: detail.setValue(generateRandomString() + "@mail.co.uk", detail.key, null); break; case VCARD_EMAIL: detail.setEmail(generateRandomString() + "@mail.co.uk", ContactDetail.DetailKeyTypes.HOME); break; case VCARD_PHONE: detail.setTel("07967 123456", ContactDetail.DetailKeyTypes.CELL); break; case VCARD_BUSINESS: case VCARD_ADDRESS: VCardHelper.PostalAddress address = new VCardHelper.PostalAddress(); address.addressLine1 = "123 Any road"; address.addressLine2 = "Any location"; address.city = "Any City"; address.county = "Any County"; address.postCode = "M6 2AY"; address.country = "United Kingdom"; detail.setPostalAddress(address, ContactDetail.DetailKeyTypes.HOME); break; case VCARD_URL: case VCARD_INTERNET_ADDRESS: detail.setValue("www." + generateRandomString() + "anyaddress.co.uk", detail.key, null); break; case VCARD_ROLE: detail.setValue(generateRandomString(), detail.key, null); break; case VCARD_ORG: Organisation org = new Organisation(); org.name = generateRandomString(); detail.setOrg(org, null); break; case VCARD_TITLE: detail.setValue(generateRandomString(), detail.key, null); break; case VCARD_NOTE: { String randomString = new String(); for (int i = 0 ; i < generateRandomInt() % 10 ; i++) { randomString += generateRandomString() + " "; } detail.setValue(randomString, detail.key, null); break; } } } public void addRandomGroup(List<Long> groupList) { long[] groupChoiceList = {1,2, 860909, 860910, 860911, 860912}; for (int i = 0 ; i < 20 ; i++) { int groupIdIdx = generateRandomInt() % groupChoiceList.length; Long groupId = groupChoiceList[groupIdIdx]; boolean used = false; for (int j = 0 ; j < groupList.size() ; j++) { if (groupList.get(j).equals(groupId)) { used = true; break; } } if (!used) { groupList.add(groupId); return; } } } public Contact createDummyContactData() { Contact contact = new Contact(); //contact.localContactID = 0L; contact.synctophone = generateRandomBoolean(); contact.details.clear(); contact.aboutMe = generateRandomString(); contact.friendOfMine = ((generateRandomInt() & 1) == 0); contact.gender = generateRandomInt() & 1; if (contact.groupList == null) { contact.groupList = new ArrayList<Long>(); } for (int i = 0 ; i < (generateRandomInt() & 3) ; i++) { addRandomGroup(contact.groupList); } if (contact.sources == null) { contact.sources = new ArrayList<String>(); } for (int i = 0 ; i < (generateRandomInt() & 3) ; i++) { contact.sources.add(generateRandomString()); } ContactDetail nameDetail = createDummyDetailsName(); ContactDetail nicknameDetail = createDummyDetailsNickname(nameDetail); contact.details.add(nameDetail); contact.details.add(nicknameDetail); final int noOfDetails = (generateRandomInt() % 10); for (int i = 0 ; i < noOfDetails ; i++ ) { ContactDetail detail = new ContactDetail(); createDummyDetailsData(detail); contact.details.add(detail); } if ((generateRandomInt() & 1) == 0) { ContactDetail detail = new ContactDetail(); Organisation org = new Organisation(); org.name = generateRandomString(); detail.setOrg(org, null); contact.details.add(detail); } if ((generateRandomInt() & 1) == 0) { ContactDetail detail = new ContactDetail(); detail.setValue(generateRandomString(), ContactDetail.DetailKeys.VCARD_TITLE, null); contact.details.add(detail); } fixPreferred(contact); return contact; } public Contact createDummyNativeContactData() { Contact contact = createDummyContactData(); for (ContactDetail cd : contact.details) { cd.nativeContactId = generateRandomInt(); cd.nativeDetailId = generateRandomInt(); cd.nativeVal1 = generateRandomString(); cd.nativeVal2 = generateRandomString(); cd.nativeVal3 = generateRandomString(); } return contact; } public static boolean generateRandomBoolean() { return RANDOM.nextBoolean(); } /** * TODO: fill in the method properly * @return */ public List<ActivityItem> createFakeActivitiesList() { List<ActivityItem> activityList = new ArrayList<ActivityItem>(); for (int i = 0; i < TABLE_SIZE; i++) { ActivityItem activityItem = new ActivityItem(); /** Unique identifier for the activity. This can be empty when setting * a new activity (the id is generated on the server side) */ - activityItem.mActivityId = System.currentTimeMillis(); + activityItem.activityId = System.currentTimeMillis(); /** Timestamp representing the time of the activity. * This may not be related to creation/updated time. */ - activityItem.mTime = System.currentTimeMillis(); + activityItem.time = System.currentTimeMillis(); /** local id for db */ // activityItem.mLocalId; set by DB insertion // activityItem.mMoreInfo; //new Hashtable<ActivityItem, String> /** The parent activity for 'grouped' or aggregated activities. This must be empty * for normal activities that can be retrieved normally. Normally, a GetActivities * without filter will not yield any 'grouped' or 'child' activities. * To get activities that have a mParentActivity set, the 'children' filter must * be used with a value of the parent Activity's id.*/ // activityItem.mParentActivity; // null /** Indicates wether this activity 'groups' several child activities. When set, * there must be child activities set that refer the main activity. Normally, * a GetActivities without filter will not yield any 'grouped' or 'child' activities. * To get activities that have a parentactivity set, the 'children' filter * must be used with a value of the parent Activity's id.*/ // activityItem.mHasChildren = false; /** Defines a binary preview for the activity. The preview can be a small thumbnail * of the activity. The type of the binary data is defined into the previewmime field.*/ // keep null // activityItem.mPreview = ByteBuffer.allocate(bytes.length); // activityItem.mPreviewMime; /** Defines an http url that the client can use to retrieve preview binary data. * Can be used to embed the url into an IMG HTML tag.*/ // activityItem.mPreviewUrl /** Name of the store type for this message. This field contains information about the * originator network (local or external community activity). * By default, should be set to local*/ - activityItem.mStore = "local"; + activityItem.store = "local"; - activityItem.mTitle = generateRandomString(); + activityItem.title = generateRandomString(); - activityItem.mDescription = activityItem.mDescription + activityItem.mStore; + activityItem.description = activityItem.description + activityItem.store; /** Defines the type of the activity. */ - activityItem.mType = Type.CONTACT_FRIEND_INVITATION_SENT; + activityItem.type = Type.CONTACT_FRIEND_INVITATION_SENT; /** Defines an internal reference (if any) to the source of the activity. * The format for the uri is "module:identifier".Some examples of valid uri are: * contact:2737b322c9f6476ca152aa6cf3e5ac12 The activity is linked to some * changes on a contact identified by id=2737b322c9f6476ca152aa6cf3e5ac12. * file:virtual/flickr/2590004126 The activity is linked to some actions * on a file identified by id=virtual/flickr/2590004126. * message:9efd255359074dd9bd04cc1c8c4743e5 The activity is linked to a message * identified by id=9efd255359074dd9bd04cc1c8c4743e5 */ - activityItem.mUri = "virtual/flickr/2590004126"; + activityItem.uri = "virtual/flickr/2590004126"; //can be 0 activityItem.mActivityFlags; /** Miscellaneous flags.*/ - activityItem.mFlagList = new ArrayList<Flag>(); - activityItem.mFlagList.add(Flag.ALREADY_READ); + activityItem.flagList = new ArrayList<Flag>(); + activityItem.flagList.add(Flag.ALREADY_READ); /** Defines the contact information of the counter-parties in the activity. * This field is not mandatory, because some activity types * are not related to contacts, but required if known.. */ //keep it simple - empty activityItem.mContactList = ; - activityItem.mVisibility = new ArrayList<Visibility>(); - activityItem.mVisibility.add(Visibility.ORIGINATOR); + activityItem.visibility = new ArrayList<Visibility>(); + activityItem.visibility.add(Visibility.ORIGINATOR); //keep it 0 activityItem.mVisibilityFlags = 0; activityList.add(activityItem); } return activityList; } /** * TODO: fill in the method properly * @return */ public static ArrayList<TimelineSummaryItem> generateFakeTimeLinesList() { ArrayList<TimelineSummaryItem> timeList = new ArrayList<TimelineSummaryItem>(); ArrayList<String> uniqueContactNames = new ArrayList<String>(); ArrayList<Long> uniqueLocalContactIds = new ArrayList<Long>(); for (int i = 0; i < TABLE_SIZE; i++) { TimelineSummaryItem item = new TimelineSummaryItem(); item.mTimestamp = System.currentTimeMillis(); item.mNativeItemId = generateRandomInt(); item.mNativeItemType = TimelineNativeTypes.SmsLog.ordinal(); // the same as in fetch item.mType = Type.MESSAGE_SMS_RECEIVED; item.mNativeThreadId = generateRandomInt(); item.mContactAddress = "some local address"; item.mDescription = generateRandomString(); item.mTitle = DateFormat.getDateInstance().format(new Date (item.mTimestamp)); //item.mLocalActivityId = i; // Set on databae insert. //the below fields are originally set under condition item.mContactId = generateRandomLong(); item.mLocalContactId = generateRandomLong(); item.mUserId = generateRandomLong(); item.mContactName = generateRandomString()+ i; item.mContactNetwork = generateRandomString(); item.mIncoming = TimelineSummaryItem.Type.INCOMING; // public boolean mHasAvatar; // Name and localContactId has to be unique, if localContactId is the same // then contact isn't included in ActivitiesTable.fetchTimelineEventList if (!uniqueContactNames.contains(item.mContactName) && !uniqueLocalContactIds.contains(item.mLocalContactId)) { uniqueContactNames.add(item.mContactName); uniqueLocalContactIds.add(item.mLocalContactId); timeList.add(item); } } Log.e("UNIQUE TIMELINE NAMES:", uniqueContactNames.toString()); return timeList; } /** * TODO: fill in the method properly * @return */ public List<ActivityItem> createFakeStatusEventList() { List<ActivityItem> activityList = new ArrayList<ActivityItem>(); for (int i = 0; i < TABLE_SIZE; i++) { ActivityItem activityItem = new ActivityItem(); /** Unique identifier for the activity. This can be empty when setting * a new activity (the id is generated on the server side) */ - activityItem.mActivityId = System.currentTimeMillis(); + activityItem.activityId = System.currentTimeMillis(); /** Timestamp representing the time of the activity. * This may not be related to creation/updated time. */ - activityItem.mTime = System.currentTimeMillis(); + activityItem.time = System.currentTimeMillis(); /** local id for db */ // activityItem.mLocalId; set by DB insertion // activityItem.mMoreInfo; //new Hashtable<ActivityItem, String> /** The parent activity for 'grouped' or aggregated activities. This must be empty * for normal activities that can be retrieved normally. Normally, a GetActivities * without filter will not yield any 'grouped' or 'child' activities. * To get activities that have a mParentActivity set, the 'children' filter must * be used with a value of the parent Activity's id.*/ // activityItem.mParentActivity; // null /** Indicates wether this activity 'groups' several child activities. When set, * there must be child activities set that refer the main activity. Normally, * a GetActivities without filter will not yield any 'grouped' or 'child' activities. * To get activities that have a parentactivity set, the 'children' filter * must be used with a value of the parent Activity's id.*/ // activityItem.mHasChildren = false; /** Defines a binary preview for the activity. The preview can be a small thumbnail * of the activity. The type of the binary data is defined into the previewmime field.*/ // keep null // activityItem.mPreview = ByteBuffer.allocate(bytes.length); // activityItem.mPreviewMime; /** Defines an http url that the client can use to retrieve preview binary data. * Can be used to embed the url into an IMG HTML tag.*/ // activityItem.mPreviewUrl /** Name of the store type for this message. This field contains information about the * originator network (local or external community activity). * By default, should be set to local*/ - activityItem.mStore = "local"; + activityItem.store = "local"; - activityItem.mTitle = generateRandomString(); + activityItem.title = generateRandomString(); - activityItem.mDescription = activityItem.mDescription + activityItem.mStore; + activityItem.description = activityItem.description + activityItem.store; /** Defines the type of the activity. */ - activityItem.mType = Type.CONTACT_RECEIVED_STATUS_UPDATE; + activityItem.type = Type.CONTACT_RECEIVED_STATUS_UPDATE; /** Defines an internal reference (if any) to the source of the activity. * The format for the uri is "module:identifier".Some examples of valid uri are: * contact:2737b322c9f6476ca152aa6cf3e5ac12 The activity is linked to some * changes on a contact identified by id=2737b322c9f6476ca152aa6cf3e5ac12. * file:virtual/flickr/2590004126 The activity is linked to some actions * on a file identified by id=virtual/flickr/2590004126. * message:9efd255359074dd9bd04cc1c8c4743e5 The activity is linked to a message * identified by id=9efd255359074dd9bd04cc1c8c4743e5 */ - activityItem.mUri = "virtual/flickr/2590004126"; + activityItem.uri = "virtual/flickr/2590004126"; //can be 0 activityItem.mActivityFlags; /** Miscellaneous flags.*/ - activityItem.mFlagList = new ArrayList<Flag>(); - activityItem.mFlagList.add(Flag.STATUS); - activityItem.mActivityFlags = 0x04; + activityItem.flagList = new ArrayList<Flag>(); + activityItem.flagList.add(Flag.STATUS); + activityItem.activityFlags = 0x04; /** Defines the contact information of the counter-parties in the activity. * This field is not mandatory, because some activity types * are not related to contacts, but required if known.. */ //keep it simple - empty activityItem.mContactList = ; - activityItem.mVisibility = new ArrayList<Visibility>(); - activityItem.mVisibility.add(Visibility.ORIGINATOR); + activityItem.visibility = new ArrayList<Visibility>(); + activityItem.visibility.add(Visibility.ORIGINATOR); //keep it 0 activityItem.mVisibilityFlags = 0; activityList.add(activityItem); } return activityList; } public static int generateRandomInt() { return RANDOM.nextInt() & 0x7FFF; } public static long generateRandomLong() { return RANDOM.nextLong() & 0x7FFF; } public static String generateRandomString() { String[] stringList = {"Adult", "Aeroplane", "Air", "Aircraft Carrier", "Airforce", "Airport", "Album", "Alphabet", "Apple", "Arm", "Army", "Baby", "Baby", "Backpack", "Balloon", "Banana", "Bank", "Barbecue", "Bathroom", "Bathtub", "Bed", "Bed", "Bee", "Bible", "Bible", "Bird", "Book", "Boss", "Bottle", "Bowl", "Box", "Boy", "Brain", "Bridge", "Butterfly", "Button", "Cappuccino", "Car", "Car-race", "Carpet", "Carrot", "Cave", "Chair", "Chess Board", "Chief", "Child", "Chisel", "Chocolates", "Church", "Circle", "Circus", "Circus", "Clock", "Clown", "Coffee", "Coffee-shop", "Comet", "Compact Disc", "Compass", "Computer", "Crystal", "Cup", "Cycle", "Data Base", "Desk", "Diamond", "Dress", "Drill", "Drink", "Drum", "Dung", "Ears", "Earth", "Egg", "Electricity", "Elephant", "Eraser", "Eyes", "Family", "Fan", "Feather", "Festival", "Film", "Finger", "Fire", "Floodlight", "Flower", "Foot", "Fork", "Freeway", "Fruit", "Fungus", "Game", "Garden", "Gas", "Gate", "Gemstone", "Girl", "Gloves", "Grapes", "Guitar", "Hammer", "Hat", "Hieroglyph", "Highway", "Horoscope", "Horse", "Hose", "Ice", "Ice-cream", "Insect", "Jet fighter", "Junk", "Kaleidoscope", "Kitchen", "Knife", "Leather jacket", "Leg", "Library", "Liquid", "Magnet", "Man", "Map", "Maze", "Meat", "Meteor", "Microscope", "Milk", "Milkshake", "Mist", "Mojito", "Money $$$$", "Monster", "Mosquito", "Mouth", "Nail", "Navy", "Necklace", "Needle", "Onion", "PaintBrush", "Pants", "Parachute", "Passport", "Pebble", "Pendulum", "Pepper", "Perfume", "Pillow", "Plane", "Planet", "Pocket", "Post-office", "Potato", "Printer", "Prison", "Pyramid", "Radar", "Rainbow", "Record", "Restaurant", "Rifle", "Ring", "Robot", "Rock", "Rocket", "Roof", "Room", "Rope", "Saddle", "Salt", "Sandpaper", "Sandwich", "Satellite", "School", "Ship", "Shoes", "Shop", "Shower", "Signature", "Skeleton", "Slave", "Snail", "Software", "Solid", "Space Shuttle", "Spectrum", "Sphere", "Spice", "Spiral", "Spoon", "Sports-car", "Spot Light", "Square", "Staircase", "Star", "Stomach", "Sun", "Sunglasses", "Surveyor", "Swimming Pool", "Sword", "Table", "Tapestry", "Teeth", "Telescope", "Television", "Tennis racquet", "Thermometer", "Tiger", "Toilet", "Tongue", "Torch", "Torpedo", "Train", "Treadmill", "Triangle", "Tunnel", "Typewriter", "Umbrella", "Vacuum", "Vampire", "Videotape", "Vulture", "Water", "Weapon", "Web", "Wheelchair", "Window", "Woman", "Worm", "X-ray"}; final int val = generateRandomInt() % stringList.length; return stringList[val]; } public NativeContactDetails addNativeContact(ContentResolver cr, NativeNameType nameType, boolean withNote, int phones, int emails, int addresses, int orgs) { NativeContactDetails ncd = new NativeContactDetails(); ncd.mName = createDummyName(); ncd.mName.midname = generateRandomString(); switch (nameType) { case NO_NAME: ncd.mName.firstname = null; // Fall through case SINGLE_NAME: ncd.mName.surname = null; // Fall through case DOUBLE_NAME: ncd.mName.midname = null; // Fall through case FULL_NAME_NO_TITLE: ncd.mName.title = null; // Fall through case FULL_NAME: break; } ContentValues cv = new ContentValues(); cv.put(Contacts.People.NAME, ncd.mName.toString()); if (withNote) { String randomString = new String(); for (int i = 0 ; i < generateRandomInt() % 10 ; i++) { randomString += generateRandomString() + " "; } cv.put(Contacts.People.NOTES, randomString); ncd.mNote = randomString; } Uri peopleResult; try { peopleResult = cr.insert(Contacts.People.CONTENT_URI, cv); if (peopleResult == null) { return null; } } catch (SQLException e) { return null; } int id = (int)ContentUris.parseId(peopleResult); ncd.mId = id; for (int i = 0 ; i < phones ; i++) { NativeDetail nd = addNativePhone(cr, id, (i == 0)); if (nd == null) { return null; } ncd.mPhoneList.add(nd); } for (int i = 0 ; i < emails ; i++) { NativeDetail nd = addNativeContactMethod(cr, id, CONTACT_METHODS_KIND_EMAIL, (i==0)); if (nd == null) { return null; } ncd.mEmailList.add(nd); } for (int i = 0 ; i < addresses ; i++) { NativeDetail nd = addNativeContactMethod(cr, id, CONTACT_METHODS_KIND_ADDRESS, (i==0)); if (nd == null) { return null; } ncd.mAddressList.add(nd); } for (int i = 0 ; i < orgs ; i++) { if (!addNativeOrg(cr, id, (i==0), ncd.mOrgList, ncd.mTitleList)) { return null; } } return ncd; } public NativeDetail addNativePhone(ContentResolver cr, int id, boolean isPrimary) { ContentValues cv = new ContentValues(); String prefix = "0"; if (generateRandomInt() > 0x3FFF) { prefix = String.format("+%02d", generateRandomInt()%100); } String number = prefix + generateRandomInt() + " " + generateRandomInt(); int type = generateRandomInt() & 7; if (type == 0) { cv.put(Contacts.Phones.LABEL, generateRandomString()); } cv.put(Contacts.Phones.PERSON_ID, id); cv.put(Contacts.Phones.NUMBER, number); cv.put(Contacts.Phones.TYPE, type); cv.put(Contacts.Phones.ISPRIMARY, (isPrimary?1:0)); Uri uriPhone; try { uriPhone = cr.insert(Contacts.Phones.CONTENT_URI, cv); if (uriPhone == null) { return null; } } catch (SQLException e) { return null; } NativeDetail nd = new NativeDetail(); nd.mValue1 = number; nd.mValue2 = String.valueOf(type); nd.mIsPrimary = isPrimary; nd.mId = (int)ContentUris.parseId(uriPhone); return nd; } public NativeDetail addNativeContactMethod(ContentResolver cr, int id, int kind, boolean isPrimary) { ContentValues cv = new ContentValues(); cv.put(Contacts.ContactMethods.PERSON_ID, id); String data = null; switch (kind) { case CONTACT_METHODS_KIND_EMAIL: data = "[email protected]"; break; case CONTACT_METHODS_KIND_ADDRESS: data = generateNativeAddress(); break; default: data = generateRandomString(); break; } int type = generateRandomInt() & 3; if (type == 0) { cv.put(Contacts.ContactMethods.LABEL, generateRandomString()); } cv.put(Contacts.ContactMethods.DATA, data); cv.put(Contacts.ContactMethods.TYPE, type); cv.put(Contacts.ContactMethods.KIND, kind); cv.put(Contacts.ContactMethods.ISPRIMARY, (isPrimary?1:0)); Uri uriCm; try { uriCm = cr.insert(Contacts.ContactMethods.CONTENT_URI, cv); if (uriCm == null) { return null; } } catch (SQLException e) { return null; } NativeDetail nd = new NativeDetail(); nd.mValue1 = data; nd.mValue2 = String.valueOf(kind); nd.mValue3 = String.valueOf(type); nd.mIsPrimary = isPrimary; nd.mId = (int)ContentUris.parseId(uriCm); return nd; } public boolean addNativeOrg(ContentResolver cr, int id, boolean isPrimary, List<NativeDetail> orgList, List<NativeDetail> titleList) { ContentValues cv = new ContentValues(); String company = generateRandomString(); String title = generateRandomString(); int type = generateRandomInt() % 3; if (type == 0) { cv.put(Contacts.Organizations.LABEL, generateRandomString()); } cv.put(Contacts.Organizations.PERSON_ID, id); cv.put(Contacts.Organizations.COMPANY, company); cv.put(Contacts.Organizations.TITLE, title); cv.put(Contacts.Organizations.TYPE, type); cv.put(Contacts.Organizations.ISPRIMARY, (isPrimary?1:0)); Uri uriOrg; try { uriOrg = cr.insert(Contacts.Organizations.CONTENT_URI, cv); if (uriOrg == null) { return false; } } catch (SQLException e) { return false; } NativeDetail ndOrg = new NativeDetail(); ndOrg.mValue1 = company; ndOrg.mValue2 = null; ndOrg.mValue3 = String.valueOf(type); ndOrg.mIsPrimary = isPrimary; ndOrg.mId = (int)ContentUris.parseId(uriOrg); orgList.add(ndOrg); NativeDetail ndTitle = new NativeDetail(); ndTitle.mValue1 = title; ndTitle.mValue2 = null; ndTitle.mValue3 = null; ndTitle.mIsPrimary = false; ndTitle.mId = (int)ContentUris.parseId(uriOrg); titleList.add(ndTitle); return true; } public String generateNativeAddress() { String sep = ", "; if ((generateRandomInt() & 1) == 1) { sep = "\n"; } switch (generateRandomInt() % 5) { case 0: return "Manchester"; case 1: return "3 test road" + sep + "Manchester"; case 2: return "3 test road" + sep + "Manchester" + sep + "M28 2AL"; case 3: return "3 test road" + sep + "Manchester" + sep + "M28 2AL" + sep + "United Kingdom"; default: return "3 test road" + sep + "Manchester" + sep + "Gtr Manchester" + sep + "M28 2AL" + sep + "United Kingdom"; } } public void fixPreferred(Contact testContact) { boolean donePhone = false; boolean doneEmail = false; boolean doneAddress = false; boolean doneOrg = false; for (ContactDetail detail : testContact.details) { switch (detail.key) { case VCARD_PHONE: if (!donePhone) { donePhone = true; detail.order = ContactDetail.ORDER_PREFERRED; } else { detail.order = ContactDetail.ORDER_NORMAL; } break; case VCARD_EMAIL: if (!doneEmail) { doneEmail = true; detail.order = ContactDetail.ORDER_PREFERRED; } else { detail.order = ContactDetail.ORDER_NORMAL; } break; case VCARD_ADDRESS: if (!doneAddress) { doneAddress = true; detail.order = ContactDetail.ORDER_PREFERRED; } else { detail.order = ContactDetail.ORDER_NORMAL; } break; case VCARD_ORG: if (!doneOrg) { doneOrg = true; detail.order = ContactDetail.ORDER_PREFERRED; } else { detail.order = ContactDetail.ORDER_NORMAL; } break; } } } /*** * Compare two given contacts. * @param firstContact contact to compare * @param secondContact contact to compare * @return identical true if given contacts are identical */ public static boolean doContactsMatch(Contact firstContact, Contact secondContact) { boolean identical = doContactsFieldsMatch(firstContact, secondContact); if (firstContact.contactID != null && !firstContact.contactID.equals(secondContact.contactID)) { identical = false; } if (firstContact.sources != null && secondContact.sources != null) { if (firstContact.sources.size() != secondContact.sources.size()) { diff --git a/tests/src/com/vodafone360/people/tests/database/NowPlusActivitiesTableTest.java b/tests/src/com/vodafone360/people/tests/database/NowPlusActivitiesTableTest.java index 9926276..8e0156b 100644 --- a/tests/src/com/vodafone360/people/tests/database/NowPlusActivitiesTableTest.java +++ b/tests/src/com/vodafone360/people/tests/database/NowPlusActivitiesTableTest.java @@ -1,465 +1,465 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.tests.database; import java.util.ArrayList; import java.util.List; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import com.vodafone360.people.database.tables.ActivitiesTable; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineNativeTypes; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.ActivityContact; import com.vodafone360.people.datatypes.ActivityItem; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.tests.TestModule; import com.vodafone360.people.utils.CloseUtils; public class NowPlusActivitiesTableTest extends NowPlusTableTestCase { protected static final String LOG_TAG = "NowPlusActivitiesTableTest"; private static final long YESTERDAY_TIME_MILLIS = System.currentTimeMillis() - 24*60*60*1000; public NowPlusActivitiesTableTest() { super(); } /** * The method tests database creation */ public void testCreateTable() { Log.i(LOG_TAG, "***** testCreateTable *****"); ActivitiesTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "***** testCreateTable SUCCEEDED*****"); } /** * This method deletes the tables, and releases the MainApplication */ protected void tearDown() throws Exception { ActivitiesTable.deleteActivities(null, mTestDatabase.getWritableDatabase()); super.tearDown(); } /** * The method fetches Ids from the Empty table */ public void testFetchActivitiesIdsFromEmptyTable() { Log.i(LOG_TAG, "***** testFetchActivitiesIdsFromEmptyTable *****"); SQLiteDatabase readableDataBase = mTestDatabase.getReadableDatabase(); List<Long> actualDBIds = new ArrayList<Long>(); ActivitiesTable.fetchActivitiesIds(actualDBIds, YESTERDAY_TIME_MILLIS, readableDataBase); assertEquals("The table is not empty after it has been dropped and created again!", 0, actualDBIds.size()); Log.i(LOG_TAG, "***** SUCCEEDED testFetchActivitiesIdsFromEmptyTable *****"); } /** * The method adds activities into a table and check whether they are really present there */ public void testAddActivities() { Log.i(LOG_TAG, "***** testAddActivities *****"); SQLiteDatabase writableDataBase = mTestDatabase.getWritableDatabase(); ActivitiesTable.create(writableDataBase); List<ActivityItem> activitiesList = mTestModule.createFakeActivitiesList(); ServiceStatus status = ActivitiesTable.addActivities(activitiesList, writableDataBase); assertEquals("Activities not added to the table", ServiceStatus.SUCCESS, status); Log.i(LOG_TAG, "***** testAddActivities: activities added *****"); // check if the records are there List<Long> activitiesIds = new ArrayList<Long>(); for (ActivityItem item: activitiesList) { - activitiesIds.add(item.mActivityId); + activitiesIds.add(item.activityId); } SQLiteDatabase readableDataBase = mTestDatabase.getReadableDatabase(); List<Long> actualDBIds = new ArrayList<Long>(); status = null; status = ActivitiesTable.fetchActivitiesIds(actualDBIds, YESTERDAY_TIME_MILLIS, readableDataBase); assertEquals("Fetching activities from the table failed", ServiceStatus.SUCCESS, status); Log.i(LOG_TAG, "***** testAddActivities: activities added *****"); compareActivityIds(activitiesIds, actualDBIds); Log.i(LOG_TAG, "***** SUCCEEDED testAddActivities *****"); } /** * This method fires assertion error when the supplied List are not identical * @param ids - the initial ActivityItem ids * @param dbIds - ActivityItem ids from the database */ private void compareActivityIds(List<Long> ids, List<Long> dbIds) { assertEquals(ids.size(), dbIds.size()); final String error = "The item is absent!"; for (Long id : ids) { assertEquals(error, true, dbIds.contains(id)); } } /** * this test checks that the deleted activities are not really present in the DB */ public void testDeleteActivities() { SQLiteDatabase db = mTestDatabase.getWritableDatabase(); ActivitiesTable.create(db); /** Create dummy activities list. **/ List<ActivityItem> activitiesList = mTestModule.createFakeActivitiesList(); assertEquals("activitiesList is the wrong size", 25, activitiesList.size()); /** Add activities list to database. **/ assertEquals("ActivitiesTable.addActivities was unsuccessfull", ServiceStatus.SUCCESS, ActivitiesTable.addActivities(activitiesList, db)); assertEquals("activitiesList is the wrong size", 25, activitiesList.size()); /** Check if the records are in the database. **/ List<Long> insertedDbIds = new ArrayList<Long>(); ActivitiesTable.fetchActivitiesIds(insertedDbIds, YESTERDAY_TIME_MILLIS, db); for (ActivityItem item: activitiesList) { - assertNotNull("item.mActivityId should not be NULL", item.mActivityId); - assertNotNull("item.mLocalActivityId should not be NULL", item.mLocalActivityId); - assertNotNull("item.mTitle should not be NULL", item.mTitle); + assertNotNull("item.mActivityId should not be NULL", item.activityId); + assertNotNull("item.mLocalActivityId should not be NULL", item.localActivityId); + assertNotNull("item.mTitle should not be NULL", item.title); } /** Delete all activities regardless of flag. **/ assertEquals(ServiceStatus.SUCCESS, ActivitiesTable.deleteActivities(null, db)); /** Check that the database is now empty. **/ List<Long> actualDBIds = new ArrayList<Long>(); ActivitiesTable.fetchActivitiesIds(actualDBIds, YESTERDAY_TIME_MILLIS, db); assertEquals("Activitiess table is not empty after deletion", 0, actualDBIds.size()); } /////////////////////////////////////////////////TIMELINES//////////////////////////////////////////////// /** * This method checks that the added time line events are really present * in the table. */ @Suppress public void testAddTimelineEvents() { SQLiteDatabase database = mTestDatabase.getWritableDatabase(); ActivitiesTable.create(database); ArrayList<TimelineSummaryItem> timelineSummaryItemList = TestModule.generateFakeTimeLinesList(); assertEquals("timelineSummaryItemList has size of 25", 25, timelineSummaryItemList.size()); ActivitiesTable.addTimelineEvents(timelineSummaryItemList, false, database); assertEquals("timelineSummaryItemList has size of 25", 25, timelineSummaryItemList.size()); /** Check if the records are there. **/ Cursor cursor = null; ArrayList<TimelineSummaryItem> actualDBTimeLines = null; try { cursor = ActivitiesTable.fetchTimelineEventList( YESTERDAY_TIME_MILLIS, new TimelineNativeTypes[]{ TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog}, database); assertEquals("Cursor contains less items than expected!", timelineSummaryItemList.size(), cursor.getCount()); actualDBTimeLines = new ArrayList<TimelineSummaryItem>(); for (int i = 0; i < timelineSummaryItemList.size(); i++) { if (cursor.moveToPosition(i)) { actualDBTimeLines.add(ActivitiesTable.getTimelineData(cursor)); } } } finally { CloseUtils.close(cursor); } compareTimeLineIds(timelineSummaryItemList, actualDBTimeLines); } /** * This method fires assertion error when the supplied List are not identical * @param ids - the initial ActivityItem ids * @param dbIds - ActivityItem ids from the database */ private void compareTimeLineIds(List<TimelineSummaryItem> times, List<TimelineSummaryItem> dbTimes) { assertEquals("The lists are of different sizes [" + times.size() + "] vs [" + dbTimes.size() + "]", times.size(), dbTimes.size()); for (TimelineSummaryItem timelineSummaryItem : times) { assertEquals("The timeline item is absent! timelineSummaryItem[" + timelineSummaryItem + "] in [" + dbTimes + "]", true, dbTimes.contains(timelineSummaryItem)); } } /** * This method checks that time line events are absent in the table */ public void testFetchTimelineEventList() { Log.i(LOG_TAG, "***** testFetchTimeLineEventlist: create table *****"); SQLiteDatabase readableDataBase = mTestDatabase.getReadableDatabase(); ActivitiesTable.create(readableDataBase); Cursor c = ActivitiesTable.fetchTimelineEventList(YESTERDAY_TIME_MILLIS, new TimelineNativeTypes[]{TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }, readableDataBase); assertEquals("The cursor is not empty!", 0, c.getCount()); Log.i(LOG_TAG, "***** fetchTimeLineEventlist SUCCEEDED *****"); } /** * This method checks that status events are present in the table */ public void testFetchStatusEventList() { Log.i(LOG_TAG, "***** testFetchStatusEventList: create table *****"); SQLiteDatabase writableDataBase = mTestDatabase.getWritableDatabase(); ActivitiesTable.create(writableDataBase); List<ActivityItem> activitiesList = mTestModule.createFakeStatusEventList(); ServiceStatus status = ActivitiesTable.addActivities(activitiesList, writableDataBase); assertEquals("Activities not added to the table", ServiceStatus.SUCCESS, status); Log.i(LOG_TAG, "***** testFetchStatusEventList: activities added *****"); // check if the records are there List<Long> activitiesIds = new ArrayList<Long>(); for (ActivityItem item: activitiesList) { - activitiesIds.add(item.mActivityId); + activitiesIds.add(item.activityId); } SQLiteDatabase readableDataBase = mTestDatabase.getReadableDatabase(); List<Long> actualDBIds = new ArrayList<Long>(); Cursor c = ActivitiesTable.fetchStatusEventList(YESTERDAY_TIME_MILLIS, readableDataBase); while (c.moveToNext()) { ActivityItem ai = new ActivityItem(); ActivityContact ac = new ActivityContact(); ActivitiesTable.getQueryData(c, ai, ac); if (ac.mContactId != null) { - ai.mContactList = new ArrayList<ActivityContact>(); - ai.mContactList.add(ac); + ai.contactList = new ArrayList<ActivityContact>(); + ai.contactList.add(ac); } - actualDBIds.add(ai.mActivityId); + actualDBIds.add(ai.activityId); } c.close(); compareActivityIds(activitiesIds, actualDBIds); Log.i(LOG_TAG, "***** fetchStatusEventlist SUCCEEDED *****"); } //TODO: this method is tested in testAddTimelineEvents(), // public void testGetTimelineData() { // Log.i(LOG_TAG, "***** EXECUTING testActivitiesTableCreation *****"); // SQLiteDatabase writableDataBase = mTestDatabase.getWritableDatabase(); // ActivitiesTable.create(writableDataBase); // // SQLiteDatabase readableDataBase = mTestDatabase.getReadableDatabase(); // // ActivitiesTable.getTimelineData(c); // // fail("Not yet implemented"); // } // public void testFillUpdateData() { // // Log.i(LOG_TAG, "***** EXECUTING testActivitiesTableCreation *****"); // SQLiteDatabase readableDataBase = mTestDatabase.getReadableDatabase(); // ActivitiesTable.create(readableDataBase); // Log.i(LOG_TAG, "***** EXECUTING addTimelineEvents , not call log though *****"); // ActivitiesTable.fillUpdateData(item, contactIdx) // // fail("Not yet implemented"); //} /** * This method checks that timeline events are present in the table */ public void testFetchTimelineEventsForContact() { Log.i(LOG_TAG, "***** testFetchTimelineEventsForContact():create table *****"); SQLiteDatabase dataBase = mTestDatabase.getWritableDatabase(); ActivitiesTable.create(dataBase); Log.i(LOG_TAG, "***** testFetchLatestStatusTimestampForContact , not call log though *****"); ArrayList<TimelineSummaryItem> timeLines = TestModule.generateFakeTimeLinesList(); ActivitiesTable.addTimelineEvents(timeLines, false, dataBase); // check if the records are there SQLiteDatabase readableDataBase = mTestDatabase.getReadableDatabase(); Cursor c = ActivitiesTable.fetchTimelineEventList(YESTERDAY_TIME_MILLIS, new TimelineNativeTypes[]{TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }, readableDataBase); ArrayList<TimelineSummaryItem> actualDBTimeLines = new ArrayList<TimelineSummaryItem>(); for (int i = 0; i < timeLines.size(); i++) { if (c.moveToPosition(i)) { actualDBTimeLines.add(ActivitiesTable.getTimelineData(c)); } } c.close(); c = null; compareTimeLineIds(timeLines, actualDBTimeLines); for (TimelineSummaryItem timeLineSummary: actualDBTimeLines) { TimelineNativeTypes[] typeList = {TimelineNativeTypes.CallLog, TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog}; c = ActivitiesTable.fetchTimelineEventsForContact(YESTERDAY_TIME_MILLIS, timeLineSummary.mLocalContactId, timeLineSummary.mContactName, typeList, null, readableDataBase); assertEquals("the cursor is empty!", false, c.getCount() == 0); while (c.moveToNext()) { TimelineSummaryItem summary = ActivitiesTable.getTimelineData(c); assertEquals("the timeline is not found!", true, actualDBTimeLines.contains(summary)); } c.close(); c = null; } Log.i(LOG_TAG, "***** testFetchTimelineEventsForContact() SUCCEEDED *****"); } /** * this method checks the time stamps in the initial time line list are the same as in the database */ @Suppress public void testFetchLatestStatusTimestampForContact() { Log.i(LOG_TAG, "***** testFetchLatestStatusTimestampForContact: create table *****"); SQLiteDatabase dataBase = mTestDatabase.getWritableDatabase(); ActivitiesTable.create(dataBase); Log.i(LOG_TAG, "***** testFetchLatestStatusTimestampForContact , not call log though *****"); ArrayList<TimelineSummaryItem> timeLines = TestModule.generateFakeTimeLinesList(); ActivitiesTable.addTimelineEvents(timeLines, false, dataBase); // check if the records are there SQLiteDatabase readableDataBase = mTestDatabase.getReadableDatabase(); Cursor c = ActivitiesTable.fetchTimelineEventList(YESTERDAY_TIME_MILLIS, new TimelineNativeTypes[]{TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }, readableDataBase); ArrayList<TimelineSummaryItem> actualDBTimeLines = new ArrayList<TimelineSummaryItem>(); for (int i = 0; i < timeLines.size(); i++) { if (c.moveToPosition(i)) { actualDBTimeLines.add(ActivitiesTable.getTimelineData(c)); } } c.close(); compareTimeLineIds(timeLines, actualDBTimeLines); for (TimelineSummaryItem timeLineSummary: actualDBTimeLines) { - Long actualDBTimeStamp = ActivitiesTable.fetchLatestStatusTimestampForContact(timeLineSummary.mContactId, readableDataBase); - assertEquals("the timestamps are not equal!", timeLineSummary.mTimestamp, actualDBTimeStamp); + ActivityItem actualActivityItem = ActivitiesTable.getLatestStatusForContact(timeLineSummary.mContactId, readableDataBase); + assertEquals("the timestamps are not equal!", timeLineSummary.mTimestamp, actualActivityItem.time); } Log.i(LOG_TAG, "***** restFetchLatestStatusTimestampForContact SUCCEEDED *****"); } /** * this method checks the updated contacts are present in the database */ public void testUpdateTimelineContactNameAndId5() { Log.i(LOG_TAG, "***** testUpdateTimelineContactNameAndId5: create table *****"); SQLiteDatabase writableDataBase = mTestDatabase.getWritableDatabase(); ActivitiesTable.create(writableDataBase); Log.i(LOG_TAG, "***** testUpdateTimelineContactNameAndId5, not call log though *****"); ArrayList<TimelineSummaryItem> timeLines = TestModule.generateFakeTimeLinesList(); ActivitiesTable.addTimelineEvents(timeLines, false, writableDataBase); // check if the records are there SQLiteDatabase readableDataBase = mTestDatabase.getReadableDatabase(); Cursor c = ActivitiesTable.fetchTimelineEventList(YESTERDAY_TIME_MILLIS, new TimelineNativeTypes[]{TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }, readableDataBase); ArrayList<TimelineSummaryItem> actualDBTimeLines = new ArrayList<TimelineSummaryItem>(); while (c.moveToNext()) { actualDBTimeLines.add(ActivitiesTable.getTimelineData(c)); } compareTimeLineIds(timeLines, actualDBTimeLines); timeLines = actualDBTimeLines; final String NAME = "New"; for (TimelineSummaryItem timeLineSummary: timeLines) { ActivitiesTable.updateTimelineContactNameAndId(timeLineSummary.mContactName, timeLineSummary.mContactName += NAME, timeLineSummary.mLocalContactId, TestModule.generateRandomLong(), writableDataBase); } c.requery(); actualDBTimeLines.clear(); c.moveToFirst(); for (int i = 0, count = c.getCount(); i < count; i++, c.moveToNext()) { actualDBTimeLines.add(ActivitiesTable.getTimelineData(c)); } compareTimeLineIds(timeLines, actualDBTimeLines); Log.i(LOG_TAG, "***** testUpdateTimelineContactNameAndId5 SUCCEEDED *****"); } /** * this method checks the updated contacts are present in the database */ @Suppress public void testUpdateTimelineContactNameAndId3() { Log.i(LOG_TAG, "***** testUpdateTimelineContactNameAndId3: create table *****"); SQLiteDatabase writableDataBase = mTestDatabase.getWritableDatabase(); ActivitiesTable.create(writableDataBase); Log.i(LOG_TAG, "***** testUpdateTimelineContactNameAndId3 , not call log though *****"); ArrayList<TimelineSummaryItem> timeLines = TestModule.generateFakeTimeLinesList(); ActivitiesTable.addTimelineEvents(timeLines, false, writableDataBase); // check if the records are there SQLiteDatabase readableDataBase = mTestDatabase.getReadableDatabase(); Cursor c = ActivitiesTable.fetchTimelineEventList(YESTERDAY_TIME_MILLIS, new TimelineNativeTypes[]{TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }, readableDataBase); ArrayList<TimelineSummaryItem> actualDBTimeLines = new ArrayList<TimelineSummaryItem>(); for (int i = 0; i < timeLines.size(); i++) { if (c.moveToPosition(i)) { actualDBTimeLines.add(ActivitiesTable.getTimelineData(c)); } } compareTimeLineIds(timeLines, actualDBTimeLines); final String NAME = "New"; for (TimelineSummaryItem timeLineSummary: timeLines) { timeLineSummary.mContactName += NAME; ActivitiesTable.updateTimelineContactNameAndId(timeLineSummary.mContactName, timeLineSummary.mLocalContactId, writableDataBase); } c.requery(); actualDBTimeLines.clear(); for (int i = 0; i < timeLines.size(); i++) { if (c.moveToPosition(i)) { actualDBTimeLines.add(ActivitiesTable.getTimelineData(c)); } } compareTimeLineIds(timeLines, actualDBTimeLines); Log.i(LOG_TAG, "***** testUpdateTimelineContactNameAndId3 SUCCEEDED *****"); } } diff --git a/tests/src/com/vodafone360/people/tests/database/NowPlusContactSummaryTest.java b/tests/src/com/vodafone360/people/tests/database/NowPlusContactSummaryTest.java index 53d52c3..89bcdf5 100644 --- a/tests/src/com/vodafone360/people/tests/database/NowPlusContactSummaryTest.java +++ b/tests/src/com/vodafone360/people/tests/database/NowPlusContactSummaryTest.java @@ -1,517 +1,517 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.tests.database; import java.util.Hashtable; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.test.ApplicationTestCase; import android.test.suitebuilder.annotation.SmallTest; import android.util.Log; import com.vodafone360.people.MainApplication; import com.vodafone360.people.database.tables.ContactDetailsTable; import com.vodafone360.people.database.tables.ContactSummaryTable; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactDetail; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.User; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.tests.TestModule; /** * This class performs ContactSummaryTable tests. */ public class NowPlusContactSummaryTest extends ApplicationTestCase<MainApplication> { private static String LOG_TAG = "NowPlusContactSummaryTest"; /** * Helper module to generate test content. */ final TestModule mTestModule = new TestModule(); /** * A simple test database. */ private TestDatabase mTestDatabase; /** * Constructor. */ public NowPlusContactSummaryTest() { super(MainApplication.class); } @Override protected void setUp() throws Exception { super.setUp(); createApplication(); mTestDatabase = new TestDatabase(getContext()); } @Override protected void tearDown() throws Exception { mTestDatabase.close(); getContext().deleteDatabase(TestDatabase.DATA_BASE_NAME); // make sure to call it at the end of the method! super.tearDown(); } /** * Tests the ContactSummaryTable creation. */ @SmallTest public void testContactSummaryTableCreation() { Log.i(LOG_TAG, "***** EXECUTING testContactSummaryTableCreation *****"); Log.i(LOG_TAG, "Create ContactSummaryTable"); ContactSummaryTable.create(mTestDatabase.getWritableDatabase()); } /** * Tests adding a contact to the contact summary table. */ @SmallTest public void testAddingContactSummary() { Log.i(LOG_TAG, "***** EXECUTING testAddingContactSummary *****"); Log.i(LOG_TAG, "Create ContactSummaryTable"); ContactSummaryTable.create(mTestDatabase.getWritableDatabase()); final Contact contact = mTestModule.createDummyContactData(); contact.localContactID = new Long(10); ContactSummaryTable.addContact(contact, mTestDatabase.getWritableDatabase()); } /** * Tests fetching a contact summary. */ @SmallTest public void testFetchingContactSummary() { Log.i(LOG_TAG, "***** EXECUTING testFetchingContactSummary *****"); Log.i(LOG_TAG, "Create ContactSummaryTable"); ContactSummaryTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Add a contact to ContactSummaryTable"); final Contact contact = mTestModule.createDummyContactData(); contact.localContactID = new Long(10); contact.nativeContactId = new Integer(11); ContactSummaryTable.addContact(contact, mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Fetching a ContactSummary from ContactSummaryTable"); final ContactSummary contactSummary = new ContactSummary(); final ServiceStatus serviceStatus = ContactSummaryTable.fetchSummaryItem( contact.localContactID, contactSummary, mTestDatabase.getReadableDatabase()); assertEquals(ServiceStatus.SUCCESS, serviceStatus); compareContactWithContactSummary(contact, contactSummary); } public void testSetAllUsersOffline() { Log.i(LOG_TAG, "Create ContactSummaryTable"); ContactSummaryTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Add a contact to ContactSummaryTable"); final Contact contact = mTestModule.createDummyContactData(); contact.localContactID = new Long(10); contact.nativeContactId = new Integer(11); ContactSummaryTable.addContact(contact, mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Fetching a ContactSummary from ContactSummaryTable"); final ContactSummary contactSummary = new ContactSummary(); final ServiceStatus serviceStatus = ContactSummaryTable.fetchSummaryItem( contact.localContactID, contactSummary, mTestDatabase.getReadableDatabase()); assertEquals(ServiceStatus.SUCCESS, serviceStatus); compareContactWithContactSummary(contact, contactSummary); // create a new user Hashtable<String, String> status = new Hashtable<String, String>(); status.put("google", "online"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("pc", "online"); User user = new User("any", status); user.setLocalContactId(contactSummary.localContactID); // set him online assertEquals(ServiceStatus.SUCCESS, ContactSummaryTable.updateOnlineStatus(user)); // fetch again final ContactSummary contactSummary2 = new ContactSummary(); assertEquals(ServiceStatus.SUCCESS, ContactSummaryTable.fetchSummaryItem(user .getLocalContactId(), contactSummary2, mTestDatabase.getReadableDatabase())); // check if he's online assertEquals(OnlineStatus.ONLINE, contactSummary2.onlineStatus); // set offline assertEquals(ServiceStatus.SUCCESS, ContactSummaryTable.setOfflineStatus()); // fetch again final ContactSummary contactSummary3 = new ContactSummary(); assertEquals(ServiceStatus.SUCCESS, ContactSummaryTable.fetchSummaryItem(user .getLocalContactId(), contactSummary3, mTestDatabase.getReadableDatabase())); // check if it's offline assertEquals(OnlineStatus.OFFLINE, contactSummary3.onlineStatus); } public void testUpdateOnlineStatus() { Log.i(LOG_TAG, "***** EXECUTING testUpdateOnlineStatus() *****"); Log.i(LOG_TAG, "Create ContactSummaryTable"); ContactSummaryTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Add a contact to ContactSummaryTable"); final Contact contact = mTestModule.createDummyContactData(); contact.localContactID = new Long(10); contact.nativeContactId = new Integer(11); ContactSummaryTable.addContact(contact, mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Fetching a ContactSummary from ContactSummaryTable"); final ContactSummary contactSummary = new ContactSummary(); final ServiceStatus serviceStatus = ContactSummaryTable.fetchSummaryItem( contact.localContactID, contactSummary, mTestDatabase.getReadableDatabase()); assertEquals(ServiceStatus.SUCCESS, serviceStatus); compareContactWithContactSummary(contact, contactSummary); // create a new user Hashtable<String, String> status = new Hashtable<String, String>(); status.put("google", "online"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("pc", "online"); User user = new User("any", status); user.setLocalContactId(contactSummary.localContactID); // set him online assertEquals(ServiceStatus.SUCCESS, ContactSummaryTable.updateOnlineStatus(user)); // fetch again final ContactSummary contactSummary2 = new ContactSummary(); assertEquals(ServiceStatus.SUCCESS, ContactSummaryTable.fetchSummaryItem(user .getLocalContactId(), contactSummary2, mTestDatabase.getReadableDatabase())); // check if he's online assertEquals(OnlineStatus.ONLINE, contactSummary2.onlineStatus); } /** * Tests removing a contact summary. */ @SmallTest public void testRemovingContactSummary() { Log.i(LOG_TAG, "***** EXECUTING testRemovingContactSummary *****"); Log.i(LOG_TAG, "Create ContactSummaryTable"); ContactSummaryTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Add a contact to ContactSummaryTable"); final Contact contact = mTestModule.createDummyContactData(); contact.localContactID = new Long(10); contact.nativeContactId = new Integer(11); ContactSummaryTable.addContact(contact, mTestDatabase.getWritableDatabase()); Log .i(LOG_TAG, "Fetching a ContactSummary from ContactSummaryTable to check that it exists"); ContactSummary contactSummary = new ContactSummary(); ServiceStatus serviceStatus = ContactSummaryTable.fetchSummaryItem(contact.localContactID, contactSummary, mTestDatabase.getReadableDatabase()); assertEquals(ServiceStatus.SUCCESS, serviceStatus); Log.i(LOG_TAG, "Delete the contact from ContactSummaryTable"); serviceStatus = ContactSummaryTable.deleteContact(contact.localContactID, mTestDatabase .getWritableDatabase()); assertEquals(ServiceStatus.SUCCESS, serviceStatus); Log .i( LOG_TAG, "Try to fetching a ContactSummary from ContactSummaryTable to check that it is not possible anymore"); contactSummary = new ContactSummary(); serviceStatus = ContactSummaryTable.fetchSummaryItem(contact.localContactID, contactSummary, mTestDatabase.getReadableDatabase()); assertTrue(ServiceStatus.SUCCESS != serviceStatus); } /** * Tests modifying a contact summary. */ @SmallTest public void testModifyingingContactSummary() { Log.i(LOG_TAG, "***** EXECUTING testModifyingingContactSummary *****"); Log.i(LOG_TAG, "Create ContactSummaryTable"); ContactSummaryTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Add a contact to ContactSummaryTable"); final Contact contact = mTestModule.createDummyContactData(); contact.localContactID = new Long(10); contact.nativeContactId = new Integer(11); ContactSummaryTable.addContact(contact, mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Fetching a ContactSummary from ContactSummaryTable"); ContactSummary contactSummary = new ContactSummary(); ServiceStatus serviceStatus = ContactSummaryTable.fetchSummaryItem(contact.localContactID, contactSummary, mTestDatabase.getReadableDatabase()); assertEquals(ServiceStatus.SUCCESS, serviceStatus); compareContactWithContactSummary(contact, contactSummary); Log.i(LOG_TAG, "Modify a contact"); final Contact contact2 = copyContact(contact); contact2.synctophone = !contact.synctophone; serviceStatus = ContactSummaryTable.modifyContact(contact2, mTestDatabase .getWritableDatabase()); assertEquals(ServiceStatus.SUCCESS, serviceStatus); Log.i(LOG_TAG, "Fetching a ContactSummary from ContactSummaryTable"); contactSummary = new ContactSummary(); serviceStatus = ContactSummaryTable.fetchSummaryItem(contact.localContactID, contactSummary, mTestDatabase.getReadableDatabase()); assertEquals(ServiceStatus.SUCCESS, serviceStatus); // by doing so, we should get back to the original if it was correctly // modified contactSummary.synctophone = !contactSummary.synctophone; compareContactWithContactSummary(contact, contactSummary); } /** * Tests adding a contact detail to an existing contact. */ @SmallTest public void testAddingContactDetails() { Log.i(LOG_TAG, "***** EXECUTING testAddingContactDetails *****"); Log.i(LOG_TAG, "Create ContactSummaryTable"); ContactSummaryTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Create also a ContactDetailsTable"); ContactDetailsTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Add a contact to ContactSummaryTable"); final Contact contact = mTestModule.createDummyContactData(); contact.localContactID = new Long(10); contact.nativeContactId = new Integer(11); ContactSummaryTable.addContact(contact, mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Add a contact detail to the previous contact"); final ContactDetail contactDetail = new ContactDetail(); contactDetail.localContactID = contact.localContactID; contactDetail.setEmail("[email protected]", ContactDetail.DetailKeyTypes.HOME); - assertTrue(ContactSummaryTable.updateNameAndStatus(contact, mTestDatabase + assertTrue(ContactSummaryTable.updateContactDisplayName(contact, mTestDatabase .getWritableDatabase()) == ServiceStatus.SUCCESS); } /** * Tests modifying a contact detail of an existing contact. */ @SmallTest public void testModifyingContactDetails() { Log.i(LOG_TAG, "***** EXECUTING testModifyingContactDetails *****"); Log.i(LOG_TAG, "Create ContactSummaryTable"); ContactSummaryTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Create also a ContactDetailsTable"); ContactDetailsTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Add a contact to ContactSummaryTable"); final Contact contact = new Contact(); contact.localContactID = new Long(10); contact.nativeContactId = new Integer(11); ServiceStatus serviceStatus = ContactSummaryTable.addContact(contact, mTestDatabase .getWritableDatabase()); assertEquals(ServiceStatus.SUCCESS, serviceStatus); Log.i(LOG_TAG, "Add a contact detail to the previous contact"); ContactDetail contactDetail = new ContactDetail(); contactDetail.localContactID = contact.localContactID; contactDetail.setEmail("[email protected]", ContactDetail.DetailKeyTypes.HOME); - assertTrue(ContactSummaryTable.updateNameAndStatus(contact, mTestDatabase + assertTrue(ContactSummaryTable.updateContactDisplayName(contact, mTestDatabase .getWritableDatabase()) == ServiceStatus.SUCCESS); Log.i(LOG_TAG, "Modify a contact detail to the previous contact"); contactDetail = new ContactDetail(); contactDetail.localContactID = contact.localContactID; contactDetail.setEmail("[email protected]", ContactDetail.DetailKeyTypes.HOME); - assertTrue(ContactSummaryTable.updateNameAndStatus(contact, mTestDatabase + assertTrue(ContactSummaryTable.updateContactDisplayName(contact, mTestDatabase .getWritableDatabase()) == ServiceStatus.SUCCESS); } /** * Tests deleting a contact detail of an existing contact. */ @SmallTest public void testDeletingContactDetails() { Log.i(LOG_TAG, "***** EXECUTING testDeletingContactDetails *****"); Log.i(LOG_TAG, "Create ContactSummaryTable"); ContactSummaryTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Create also a ContactDetailsTable"); ContactDetailsTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Add a contact to ContactSummaryTable"); final Contact contact = new Contact(); contact.localContactID = new Long(10); contact.nativeContactId = new Integer(11); ServiceStatus serviceStatus = ContactSummaryTable.addContact(contact, mTestDatabase .getWritableDatabase()); assertEquals(ServiceStatus.SUCCESS, serviceStatus); Log.i(LOG_TAG, "Add a contact detail to the previous contact"); ContactDetail contactDetail = new ContactDetail(); contactDetail.localContactID = contact.localContactID; contactDetail.setEmail("[email protected]", ContactDetail.DetailKeyTypes.HOME); - assertTrue(ContactSummaryTable.updateNameAndStatus(contact, mTestDatabase + assertTrue(ContactSummaryTable.updateContactDisplayName(contact, mTestDatabase .getWritableDatabase()) == ServiceStatus.SUCCESS); Log.i(LOG_TAG, "Delete a contact detail from the previous contact"); - assertTrue(ContactSummaryTable.updateNameAndStatus(contact, mTestDatabase + assertTrue(ContactSummaryTable.updateContactDisplayName(contact, mTestDatabase .getWritableDatabase()) == ServiceStatus.SUCCESS); } /** * Tests fetching native contact IDs. */ @SmallTest public void testFetchingNativeContactIDs() { Log.i(LOG_TAG, "***** EXECUTING testFetchingNativeContactIDs *****"); Log.i(LOG_TAG, "Create ContactSummaryTable"); ContactSummaryTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "Add a contacts to ContactSummaryTable"); ServiceStatus serviceStatus; for (int i = 0; i < 100; i++) { final Contact contact = mTestModule.createDummyContactData(); contact.localContactID = new Long(i); contact.nativeContactId = new Integer(i + 5); serviceStatus = ContactSummaryTable.addContact(contact, mTestDatabase .getWritableDatabase()); assertEquals(ServiceStatus.SUCCESS, serviceStatus); } Log.i(LOG_TAG, "Fetching native IDs"); final java.util.ArrayList<Integer> nativeIDsList = new java.util.ArrayList<Integer>(); ContactSummaryTable.fetchNativeContactIdList(nativeIDsList, mTestDatabase .getReadableDatabase()); Log.i(LOG_TAG, "Check the native IDs"); int currentNativeID = 5; for (Integer id : nativeIDsList) { assertEquals(currentNativeID++, id.intValue()); } } // ////////////////////////////// // HELPER CLASSES AND METHODS // // ////////////////////////////// /** * A simple test database. */ private static class TestDatabase extends SQLiteOpenHelper { public final static String DATA_BASE_NAME = "TEST_DB"; public TestDatabase(Context context) { super(context, DATA_BASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } } /** * Compares a Contact summary with its original contact. * * @param contact the original contact * @param contactSummary the contact summary */ private void compareContactWithContactSummary(Contact contact, ContactSummary contactSummary) { assertNotNull(contact); assertNotNull(contactSummary); assertEquals(contact.friendOfMine.booleanValue(), contactSummary.friendOfMine); assertEquals(contact.synctophone.booleanValue(), contactSummary.synctophone); assertEquals(contact.localContactID, contactSummary.localContactID); assertEquals(contact.nativeContactId, contactSummary.nativeContactId); } /** * Creates a "light" copy of a Contact. * * @param contact the contact to copy * @return the copy of the provided contact */ private Contact copyContact(Contact contact) { final Contact newContact = new Contact(); // using Copy() but seems deprecated, may need to be changed later // newContact.Copy(contact); newContact.friendOfMine = contact.friendOfMine; newContact.synctophone = contact.synctophone; newContact.localContactID = contact.localContactID; newContact.nativeContactId = contact.nativeContactId; return newContact; } } diff --git a/tests/src/com/vodafone360/people/tests/database/NowPlusDBHelperActivitiesTest.java b/tests/src/com/vodafone360/people/tests/database/NowPlusDBHelperActivitiesTest.java index 3c67837..a49c05b 100644 --- a/tests/src/com/vodafone360/people/tests/database/NowPlusDBHelperActivitiesTest.java +++ b/tests/src/com/vodafone360/people/tests/database/NowPlusDBHelperActivitiesTest.java @@ -1,242 +1,242 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.tests.database; import java.util.ArrayList; import java.util.List; import android.database.Cursor; import android.test.ApplicationTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import com.vodafone360.people.MainApplication; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ActivitiesTable; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineNativeTypes; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.ActivityItem; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.tests.TestModule; public class NowPlusDBHelperActivitiesTest extends ApplicationTestCase<MainApplication> { private static final String LOG_TAG = "NowPlusDBHelperActivitiesTest"; private static final int WAIT_EVENT_TIMEOUT_MS = 30000; private static final long YESTERDAY_TIME_MILLIS = System.currentTimeMillis() - 24*60*60*1000; private MainApplication mApplication = null; private DatabaseHelper mDatabase = null; private DbTestUtility mTestUtility; private TestModule mTestModule = new TestModule(); public NowPlusDBHelperActivitiesTest() { super(MainApplication.class); } protected void setUp() throws Exception { super.setUp(); initialise(); } protected void tearDown() throws Exception { shutdown(); super.tearDown(); } private boolean initialise() { mTestUtility = new DbTestUtility(getContext()); createApplication(); mApplication = getApplication(); if (mApplication == null){ Log.e(LOG_TAG, "Unable to create main application"); return false; } mDatabase = mApplication.getDatabase(); if (mDatabase.getReadableDatabase() == null) { return false; } mTestUtility.startEventWatcher(mDatabase); Log.i(LOG_TAG, "Initialised test environment and load database"); return true; } private void shutdown() { mTestUtility.stopEventWatcher(); } @MediumTest public void testRemoveAllRecords() { Log.i(LOG_TAG, "***** EXECUTING testRemoveAllRecords *****"); Log.i(LOG_TAG, "testRemoveAllRecords checks for te DB event coming as result of records removal"); mDatabase.removeUserData(); ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK); assertEquals(ServiceStatus.SUCCESS, status); Log.i(LOG_TAG, "********************************"); Log.i(LOG_TAG, "testRemoveAllRecords has completed successfully"); Log.i(LOG_TAG, "********************************"); Log.i(LOG_TAG, ""); } @MediumTest public void testAddActivity() { mDatabase.removeUserData(); ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK); assertEquals(ServiceStatus.SUCCESS, status); Log.i(LOG_TAG, "***** EXECUTING testAddActivity *****"); List<ActivityItem> activityList = mTestModule.createFakeActivitiesList(); // ServiceStatus status = mDatabase.addActivities(activityList); status = null; status = mDatabase.addActivities(activityList); assertEquals(ServiceStatus.SUCCESS, status); Log.i(LOG_TAG, "********************************"); Log.i(LOG_TAG, "testAddActivity has completed successfully"); Log.i(LOG_TAG, "********************************"); Log.i(LOG_TAG, ""); } @MediumTest public void testFetchActivityIds() { mDatabase.removeUserData(); ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK); assertEquals(ServiceStatus.SUCCESS, status); Log.i(LOG_TAG, "***** EXECUTING testFetchActivityIds *****"); List<ActivityItem> activityList = mTestModule.createFakeActivitiesList(); status = null; status = mDatabase.addActivities(activityList); assertEquals(ServiceStatus.SUCCESS, status); List<Long> idsList = new ArrayList<Long>(); for (ActivityItem activity:activityList) { - idsList.add(activity.mActivityId); + idsList.add(activity.activityId); } status = null; List<Long> dbIdsList = new ArrayList<Long>(); status = mDatabase.fetchActivitiesIds(dbIdsList, YESTERDAY_TIME_MILLIS); assertEquals(ServiceStatus.SUCCESS, status); compareActivityIds(idsList, dbIdsList); status = mDatabase.fetchActivitiesIds(dbIdsList, YESTERDAY_TIME_MILLIS); assertEquals(ServiceStatus.SUCCESS, status); status = mDatabase.deleteActivities(null); assertEquals(ServiceStatus.SUCCESS, status); List<Long> fetchedDBIdsList = new ArrayList<Long>(); status = mDatabase.fetchActivitiesIds(fetchedDBIdsList, YESTERDAY_TIME_MILLIS); assertEquals(ServiceStatus.SUCCESS, status); assertEquals(0, fetchedDBIdsList.size()); Log.i(LOG_TAG, "********************************"); Log.i(LOG_TAG, "testFetchActivityIds has completed successfully"); Log.i(LOG_TAG, "********************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress public void testTimelineEvents() { mDatabase.removeUserData(); ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK); assertEquals(ServiceStatus.SUCCESS, status); Log.i(LOG_TAG, "***** EXECUTING testTimelineEvents *****"); ArrayList<TimelineSummaryItem> syncItemList = TestModule.generateFakeTimeLinesList(); status = mDatabase.addTimelineEvents(syncItemList, true); assertEquals(ServiceStatus.SUCCESS, status); Cursor c = mDatabase .fetchTimelineEvents(YESTERDAY_TIME_MILLIS, new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog, TimelineNativeTypes.CallLog }); ArrayList<TimelineSummaryItem> actualDBTimeLines = new ArrayList<TimelineSummaryItem>(); while (c.moveToNext()) { actualDBTimeLines.add(ActivitiesTable.getTimelineData(c)); } c.close(); c = null; assertEquals(syncItemList.size(), actualDBTimeLines.size()); for (TimelineSummaryItem actualItem : actualDBTimeLines) { for (TimelineSummaryItem syncedItem : syncItemList) { if (actualItem.mTimestamp == syncedItem.mTimestamp) { assertEquals(actualItem.mContactName, syncedItem.mContactName); } } } Log.i(LOG_TAG, "********************************"); Log.i(LOG_TAG, "testTimelineEvents has completed successfully"); Log.i(LOG_TAG, "********************************"); Log.i(LOG_TAG, ""); } /** * This method fires assertion error when the supplied List are not identical * @param ids - the initial ActivityItem ids * @param dbIds - ActivityItem ids from the database */ private void compareActivityIds(List<Long> ids, List<Long> dbIds) { assertEquals(ids.size(), dbIds.size()); final String error = "The item is absent!"; for (Long id : ids) { assertEquals(error, true, dbIds.contains(id)); } } } diff --git a/tests/src/com/vodafone360/people/tests/engine/ActivitiesEngineTest.java b/tests/src/com/vodafone360/people/tests/engine/ActivitiesEngineTest.java index 5790c33..efab921 100644 --- a/tests/src/com/vodafone360/people/tests/engine/ActivitiesEngineTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/ActivitiesEngineTest.java @@ -1,503 +1,503 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.tests.engine; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import android.app.Instrumentation; import android.content.ContentValues; import android.net.Uri; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import com.vodafone360.people.MainApplication; import com.vodafone360.people.datatypes.ActivityContact; import com.vodafone360.people.datatypes.ActivityItem; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.activities.ActivitiesEngine; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.io.ResponseQueue; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.tests.TestModule; public class ActivitiesEngineTest extends InstrumentationTestCase implements IEngineTestFrameworkObserver { /** * States for test harness */ enum ActivityTestState { IDLE, ON_CREATE, ON_DESTROY, GET_ACTIVITIES_SUCCESS, GET_ACTIVITIES_SERVER_ERR, GET_ACTIVITIES_UNEXPECTED_RESPONSE, GET_POPULATED_ACTIVITIES, SET_STATUS, ON_SYNC_COMPLETE, GET_NEXT_RUNTIME, HANDLE_PUSH_MSG, GET_TIMELINE_EVENT_FROM_SERVER } private static final String LOG_TAG = "ActivitiesEngineTest"; EngineTestFramework mEngineTester = null; ActivitiesEngine mEng = null; ActivityTestState mState = ActivityTestState.IDLE; MainApplication mApplication = null; TestModule mTestModule = new TestModule(); @Override protected void setUp() throws Exception { super.setUp(); mApplication = (MainApplication)Instrumentation.newApplication(MainApplication.class, getInstrumentation().getTargetContext()); mApplication.onCreate(); // EngineManager.createEngineManager(getInstrumentation().getTargetContext(), // null); mEngineTester = new EngineTestFramework(this); mEng = new ActivitiesEngine(getInstrumentation().getTargetContext(), mEngineTester, mApplication.getDatabase()); mEngineTester.setEngine(mEng); mState = ActivityTestState.IDLE; } @Override protected void tearDown() throws Exception { // stop our dummy thread? mEngineTester.stopEventThread(); mEngineTester = null; mEng = null; // call at the end!!! super.tearDown(); } @MediumTest public void testOnCreate() { boolean testPass = true; mState = ActivityTestState.ON_CREATE; NetworkAgent.setAgentState(NetworkAgent.AgentState.DISCONNECTED); try { mEng.onCreate(); } catch (Exception e) { testPass = false; } NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { mEng.onCreate(); } catch (Exception e) { testPass = false; } if (!testPass) { Log.e(LOG_TAG, "**** testUpdates (FAILED) ****\n"); } assertTrue("testOnCreate() failed", testPass); Log.i(LOG_TAG, "**** testOnCreate (SUCCESS) ****\n"); } @MediumTest public void testOnDestroy() { boolean testPass = true; mState = ActivityTestState.ON_DESTROY; NetworkAgent.setAgentState(NetworkAgent.AgentState.DISCONNECTED); try { mEng.onDestroy(); } catch (Exception e) { testPass = false; } NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { mEng.onDestroy(); } catch (Exception e) { testPass = false; } assertTrue("testOnDestroy() failed", testPass); Log.i(LOG_TAG, "**** testOnDestroy (SUCCESS) ****\n"); } @MediumTest @Suppress // Takes too long. public void testGetActivitiesGoodNoMeProfile() { boolean testPass = true; mState = ActivityTestState.GET_ACTIVITIES_SUCCESS; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); mEng.addStatusesSyncRequest(); assertEquals("Expected SUCCESS, not timeout", ServiceStatus.SUCCESS, mEngineTester.waitForEvent()); Object data = mEngineTester.data(); assertTrue(data == null); assertTrue("testGetActivities() failed", testPass); Log.i(LOG_TAG, "**** testGetActivities (SUCCESS) ****\n"); } @MediumTest @Suppress // Takes too long. public void testGetActivitiesGood() { boolean testPass = true; mState = ActivityTestState.GET_ACTIVITIES_SUCCESS; // re-test with valid Me profile Contact meProfile = mTestModule.createDummyContactData(); assertEquals("Could not access db", ServiceStatus.SUCCESS, SyncMeDbUtils.setMeProfile(mApplication.getDatabase(),meProfile)); mEng.addStatusesSyncRequest(); assertEquals("Expected SUCCESS, not timeout", ServiceStatus.SUCCESS, mEngineTester.waitForEvent()); Object data = mEngineTester.data(); assertTrue(data == null); assertTrue("testGetActivities() failed", testPass); Log.i(LOG_TAG, "**** testGetActivities (SUCCESS) ****\n"); } @MediumTest @Suppress // Takes too long. public void testGetActivitiesServerErr() { boolean testPass = true; mState = ActivityTestState.GET_ACTIVITIES_SERVER_ERR; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); mEng.addStatusesSyncRequest(); ServiceStatus status = mEngineTester.waitForEvent(); if (status == ServiceStatus.SUCCESS) { throw (new RuntimeException("Did not expect SUCCESS")); } Object data = mEngineTester.data(); assertTrue(data == null); assertTrue("testGetActivitiesServerErr() failed", testPass); Log.i(LOG_TAG, "**** testGetActivitiesServerErr (SUCCESS) ****\n"); } @MediumTest @Suppress // Takes too long. public void testGetActivitiesUnexpectedResponse() { boolean testPass = true; mState = ActivityTestState.GET_ACTIVITIES_UNEXPECTED_RESPONSE; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); mEng.addStatusesSyncRequest(); assertEquals("Expected ERROR_COMMS, not timeout", ServiceStatus.ERROR_COMMS, mEngineTester.waitForEvent()); Object data = mEngineTester.data(); assertTrue(data == null); assertTrue("testGetActivitiesUnexpectedResponse() failed", testPass); Log.i(LOG_TAG, "**** testGetActivitiesUnexpectedResponse (SUCCESS) ****\n"); } /* * @MediumTest public void testSetStatus(){ boolean testPass = true; mState * = ActivityTestState.SET_STATUS; List<ActivityItem> actList = new * ArrayList<ActivityItem>(); ActivityItem actItem = createActivityItem(); * actList.add(actItem); * NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); * mEng.addUiSetStatusRequest(actList); ServiceStatus status = * mEngineTester.waitForEvent(); if(status != ServiceStatus.SUCCESS){ * throw(new RuntimeException("Expected SUCCESS")); } * assertTrue("testSetStatus() failed", testPass); Log.i(LOG_TAG, * "**** testSetStatus (SUCCESS) ****\n"); } */ @MediumTest public void testOnSyncComplete() { boolean testPass = true; mState = ActivityTestState.ON_SYNC_COMPLETE; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { mEng.onSyncComplete(ServiceStatus.SUCCESS); } catch (Exception e) { testPass = false; } assertTrue("testOnSyncComplete() failed", testPass); Log.i(LOG_TAG, "**** testOnSyncComplete (SUCCESS) ****\n"); } @MediumTest public void testGetNextRuntime() { boolean testPass = true; mState = ActivityTestState.GET_NEXT_RUNTIME; long runtime = mEng.getNextRunTime(); if (runtime != -1) { testPass = false; } assertTrue("testGetNextRuntime() failed", testPass); Log.i(LOG_TAG, "**** testGetNextRuntime (SUCCESS) ****\n"); } @Suppress @MediumTest public void testPushMessage() { boolean testPass = true; mState = ActivityTestState.GET_ACTIVITIES_SUCCESS; // create test Push msg and put it is response Q PushEvent evt = new PushEvent(); evt.mMessageType = PushMessageTypes.STATUS_ACTIVITY_CHANGE; List<BaseDataType> data = new ArrayList<BaseDataType>(); data.add(evt); NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); ResponseQueue.getInstance().addToResponseQueue(new DecodedResponse(0, data, mEng.engineId(), DecodedResponse.ResponseType.PUSH_MESSAGE.ordinal())); mEng.onCommsInMessage(); // see if anything happens assertEquals("Expected SUCCESS, not timeout", ServiceStatus.SUCCESS, mEngineTester.waitForEvent()); Object retdata = mEngineTester.data(); assertTrue(retdata == null); assertTrue("testPushMessage() failed", testPass); Log.i(LOG_TAG, "**** testPushMessage (SUCCESS) ****\n"); } /* * @MediumTest public void testGetTimelineEvent(){ boolean testPass = true; * mState = ActivityTestState.GET_TIMELINE_EVENT_FROM_SERVER; Contact * meProfile = mTestModule.createDummyContactData(); ServiceStatus status = * mApplication.getDatabase().setMeProfile(meProfile); if(status != * ServiceStatus.SUCCESS){ throw(new * RuntimeException("Could not access db")); } * mEng.addUiGetActivitiesRequest(); status = mEngineTester.waitForEvent(); * if(status != ServiceStatus.SUCCESS){ throw(new * RuntimeException("Expected SUCCESS")); } Object data = * mEngineTester.data(); assertTrue(data==null); * mEng.addUiGetActivitiesRequest(); status = mEngineTester.waitForEvent(); * if(status != ServiceStatus.SUCCESS){ throw(new * RuntimeException("Expected SUCCESS")); } data = mEngineTester.data(); * assertTrue(data==null); assertTrue("testPushMessage() failed", testPass); * Log.i(LOG_TAG, "**** testGetTimelineEvent (SUCCESS) ****\n"); } */ @MediumTest @Suppress // Takes too long. public void testMessageLog() { final String ADDRESS = "address"; // final String PERSON = "person"; final String DATE = "date"; final String READ = "read"; final String STATUS = "status"; final String TYPE = "type"; final String BODY = "body"; ContentValues values = new ContentValues(); values.put(ADDRESS, "+61408219690"); values.put(DATE, "1630000000000"); values.put(READ, 1); values.put(STATUS, -1); values.put(TYPE, 2); values.put(BODY, "SMS inserting test"); /* Uri inserted = */mApplication.getContentResolver().insert(Uri.parse("content://sms"), values); mState = ActivityTestState.GET_ACTIVITIES_SUCCESS; // re-test with valid Me profile Contact meProfile = mTestModule.createDummyContactData(); assertEquals("Could not access db", ServiceStatus.SUCCESS, SyncMeDbUtils.setMeProfile(mApplication.getDatabase(),meProfile)); mEng.addStatusesSyncRequest(); assertEquals("Expected SUCCESS, not timeout", ServiceStatus.SUCCESS, mEngineTester.waitForEvent()); Object data = mEngineTester.data(); assertTrue(data == null); values.put(DATE, "1650000000000"); /* inserted = */mApplication.getContentResolver() .insert(Uri.parse("content://mms"), values); mEng.addStatusesSyncRequest(); assertEquals("Could not access db", ServiceStatus.SUCCESS, mEngineTester.waitForEvent()); Log.i(LOG_TAG, "**** testGetActivities (SUCCESS) ****\n"); } @Suppress public void testPopulatedActivities() { boolean testPass = true; mState = ActivityTestState.GET_POPULATED_ACTIVITIES; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); assertEquals("Expected SUCCESS, not timeout", ServiceStatus.SUCCESS, mEngineTester.waitForEvent()); assertTrue("testPopulatedActivities() failed", testPass); Log.i(LOG_TAG, "**** testPopulatedActivities (SUCCESS) ****\n"); } @Override public void reportBackToEngine(int reqId, EngineId engine) { Log.d("TAG", "IdentityEngineTest.reportBackToEngine"); ResponseQueue respQueue = ResponseQueue.getInstance(); List<BaseDataType> data = new ArrayList<BaseDataType>(); switch (mState) { case IDLE: break; case ON_CREATE: case ON_DESTROY: break; case GET_ACTIVITIES_SUCCESS: ActivityItem item = new ActivityItem(); data.add(item); respQueue.addToResponseQueue(new DecodedResponse(reqId, data, engine, DecodedResponse.ResponseType.GET_ACTIVITY_RESPONSE.ordinal())); mEng.onCommsInMessage(); break; case GET_TIMELINE_EVENT_FROM_SERVER: ActivityItem item2 = new ActivityItem(); ActivityContact act = new ActivityContact(); act.mName = "Bill Fleege"; act.mLocalContactId = new Long(8); List<ActivityContact> clist = new ArrayList<ActivityContact>(); clist.add(act); - item2.mContactList = clist; - item2.mActivityFlags = 2; - item2.mType = ActivityItem.Type.CONTACT_JOINED; - item2.mTime = System.currentTimeMillis(); + item2.contactList = clist; + item2.activityFlags = 2; + item2.type = ActivityItem.Type.CONTACT_JOINED; + item2.time = System.currentTimeMillis(); data.add(item2); respQueue.addToResponseQueue(new DecodedResponse(reqId, data, engine, DecodedResponse.ResponseType.GET_ACTIVITY_RESPONSE.ordinal())); mEng.onCommsInMessage(); break; case GET_POPULATED_ACTIVITIES: ActivityItem item3 = new ActivityItem(); ActivityContact act2 = new ActivityContact(); act2.mName = "Bill Fleege"; act2.mLocalContactId = new Long(8); List<ActivityContact> clist2 = new ArrayList<ActivityContact>(); clist2.add(act2); - item3.mContactList = clist2; - item3.mActivityFlags = 2; - item3.mType = ActivityItem.Type.CONTACT_JOINED; - item3.mTime = System.currentTimeMillis(); - item3.mTitle = "bills new status"; - item3.mDescription = "a description"; + item3.contactList = clist2; + item3.activityFlags = 2; + item3.type = ActivityItem.Type.CONTACT_JOINED; + item3.time = System.currentTimeMillis(); + item3.title = "bills new status"; + item3.description = "a description"; data.add(item3); ActivityItem item4 = new ActivityItem(); - item4.mContactList = clist2; - item4.mActivityFlags = 5; - item4.mType = ActivityItem.Type.CONTACT_JOINED; - item4.mTime = System.currentTimeMillis(); - item4.mTitle = "bills new status"; - item4.mDescription = "a description"; - item4.mActivityId = new Long(23); - item4.mHasChildren = false; - item4.mUri = "uri"; - item4.mParentActivity = new Long(0); - item4.mPreview = ByteBuffer.allocate(46); - item4.mPreview.position(0); - item4.mPreview.rewind(); + item4.contactList = clist2; + item4.activityFlags = 5; + item4.type = ActivityItem.Type.CONTACT_JOINED; + item4.time = System.currentTimeMillis(); + item4.title = "bills new status"; + item4.description = "a description"; + item4.activityId = new Long(23); + item4.hasChildren = false; + item4.uri = "uri"; + item4.parentActivity = new Long(0); + item4.preview = ByteBuffer.allocate(46); + item4.preview.position(0); + item4.preview.rewind(); for (int i = 0; i < 23; i++) { - item4.mPreview.putChar((char)i); + item4.preview.putChar((char)i); } - item4.mPreviewMime = "jepg"; - item4.mPreviewUrl = "storeurl"; - item4.mStore = "google"; - item4.mVisibilityFlags = 0; + item4.previewMime = "jepg"; + item4.previewUrl = "storeurl"; + item4.store = "google"; + item4.visibilityFlags = 0; data.add(item4); respQueue.addToResponseQueue(new DecodedResponse(reqId, data, engine, DecodedResponse.ResponseType.GET_ACTIVITY_RESPONSE.ordinal())); mEng.onCommsInMessage(); break; case GET_ACTIVITIES_SERVER_ERR: ServerError err = new ServerError("Catastrophe"); err.errorDescription = "Fail"; data.add(err); respQueue.addToResponseQueue(new DecodedResponse(reqId, data, engine, DecodedResponse.ResponseType.SERVER_ERROR.ordinal())); mEng.onCommsInMessage(); break; case GET_ACTIVITIES_UNEXPECTED_RESPONSE: StatusMsg msg = new StatusMsg(); msg.mCode = "ok"; msg.mDryRun = false; msg.mStatus = true; data.add(msg); respQueue.addToResponseQueue(new DecodedResponse(reqId, data, engine, DecodedResponse.ResponseType.LOGIN_RESPONSE.ordinal())); mEng.onCommsInMessage(); break; case SET_STATUS: Identity id3 = new Identity(); data.add(id3); respQueue.addToResponseQueue(new DecodedResponse(reqId, data, engine, DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal())); mEng.onCommsInMessage(); break; case ON_SYNC_COMPLETE: ServerError err2 = new ServerError("Catastrophe"); err2.errorDescription = "Fail"; data.add(err2); respQueue.addToResponseQueue(new DecodedResponse(reqId, data, engine, DecodedResponse.ResponseType.SERVER_ERROR.ordinal())); mEng.onCommsInMessage(); break; case GET_NEXT_RUNTIME: break; default: } } @Override public void onEngineException(Exception exp) { // TODO Auto-generated method stub } } diff --git a/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeImporterTest.java b/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeImporterTest.java index 82b5f43..b6a847a 100644 --- a/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeImporterTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeImporterTest.java @@ -1,1126 +1,1125 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.tests.engine.contactsync; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Hashtable; +import junit.framework.TestCase; import android.util.Log; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.engine.contactsync.ContactChange; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.engine.contactsync.NativeImporter; import com.vodafone360.people.engine.contactsync.PeopleContactsApi; import com.vodafone360.people.engine.contactsync.NativeContactsApi.Account; import com.vodafone360.people.utils.VersionUtils; -import junit.framework.TestCase; - public class NativeImporterTest extends TestCase { /** * 360 client account type. */ protected static final int PEOPLE_ACCOUNT_TYPE = 1; /** * Google account type. */ protected static final int GOOGLE_ACCOUNT_TYPE = 2; /** * Vendor specific type. */ protected static final int PHONE_ACCOUNT_TYPE = 3; /** * Account type for 360 People in the Native Accounts. * MUST be a copy of type in 'res/xml/authenticator.xml' */ protected static final String PEOPLE_ACCOUNT_TYPE_STRING = "com.vodafone360.people.android.account"; /** * Google account, there can be more than one of these */ protected static final String GOOGLE_ACCOUNT_TYPE_STRING = "com.google"; /* * A third party account type. */ private final static String THIRD_PARTY_ACCOUNT_TYPE_STRING = "com.thirdparty"; /** * The internal max operation count of the NativeImporter. * @see NativeImporter#MAX_CONTACTS_OPERATION_COUNT */ - private final static int NATIVE_IMPORTER_MAX_OPERATION_COUNT = (Integer)getField("MAX_CONTACTS_OPERATION_COUNT", com.vodafone360.people.engine.contactsync.NativeImporter.class); + private final static float NATIVE_IMPORTER_MAX_OPERATION_COUNT = (Float)getField("CONTACTS_PER_TICK_START", com.vodafone360.people.engine.contactsync.NativeImporter.class); /** * A count of operations below the maximum. * @see NativeImporter#MAX_CONTACTS_OPERATION_COUNT */ - private final static int NATIVE_CONTACTS_COUNT_BELOW_MAX_OPERATION_COUNT = NATIVE_IMPORTER_MAX_OPERATION_COUNT / 2; + private final static float NATIVE_CONTACTS_COUNT_BELOW_MAX_OPERATION_COUNT = NATIVE_IMPORTER_MAX_OPERATION_COUNT / 2; /** * A count of operations above the maximum. * @see NativeImporter#MAX_CONTACTS_OPERATION_COUNT */ - private final static int NATIVE_CONTACTS_COUNT_OVER_MAX_OPERATION_COUNT = (NATIVE_IMPORTER_MAX_OPERATION_COUNT * 5) + (NATIVE_IMPORTER_MAX_OPERATION_COUNT / 2); + private final static float NATIVE_CONTACTS_COUNT_OVER_MAX_OPERATION_COUNT = (NATIVE_IMPORTER_MAX_OPERATION_COUNT * 5) + (NATIVE_IMPORTER_MAX_OPERATION_COUNT / 2); /** * A test Gmail account. */ public final static Account GMAIL_ACCOUNT_1 = new Account("[email protected]", GOOGLE_ACCOUNT_TYPE_STRING); /** * A test Gmail account. */ public final static Account GMAIL_ACCOUNT_2 = new Account("[email protected]", GOOGLE_ACCOUNT_TYPE_STRING); /** * A test People account. */ public final static Account PEOPLE_ACCOUNT = new Account("mypeoplelogin", PEOPLE_ACCOUNT_TYPE_STRING); /** * A test third party account. */ public final static Account THIRD_PARTY_ACCOUNT = new Account("mythirdpartylogin", THIRD_PARTY_ACCOUNT_TYPE_STRING); /** * Tests that the number of ticks needed to perform the native import is as expected when the count of contacts * is below MAX_CONTACTS_OPERATION_COUNT. */ public void testRequiredTicksForBelowMaxOperationCountImport() { final NativeContactsApiMockup nativeMockup = new NativeContactsApiMockup(); final PeopleContactsApiMockup peopleMockup = new PeopleContactsApiMockup(null); performNativeImport(nativeMockup, peopleMockup, NATIVE_CONTACTS_COUNT_BELOW_MAX_OPERATION_COUNT); } /** * Tests that the number of ticks needed to perform the native import is as expected when the count of contacts * is over MAX_CONTACTS_OPERATION_COUNT. */ public void testRequiredTicksForOverMaxOperationCountImport() { final NativeContactsApiMockup nativeMockup = new NativeContactsApiMockup(); final PeopleContactsApiMockup peopleMockup = new PeopleContactsApiMockup(null); performNativeImport(nativeMockup, peopleMockup, NATIVE_CONTACTS_COUNT_OVER_MAX_OPERATION_COUNT); } /** * Tests multiple imports from native with only new contacts. */ public void testMultipleImportsFromNativeWithNewContacts() { final NativeContactsApiMockup nativeMockup = new NativeContactsApiMockup(); final PeopleContactsApiMockup peopleMockup = new PeopleContactsApiMockup(null); // add new contacts on native side feedNativeContactsApi(nativeMockup, 15, null); long[] nativeIds = nativeMockup.getContactIds(null); assertEquals(15, nativeIds.length); // import the new contacts runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); // add new contacts on native side feedNativeContactsApi(nativeMockup, 15, null); nativeIds = nativeMockup.getContactIds(null); assertEquals(30, nativeIds.length); // import the new contacts runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); // add new contacts on native side feedNativeContactsApi(nativeMockup, 15, null); nativeIds = nativeMockup.getContactIds(null); assertEquals(45, nativeIds.length); // import the new contacts runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); } /** * Tests multiple imports from native with deleted contacts. */ public void testMultipleImportsFromNativeWithDeletedContacts() { final NativeContactsApiMockup nativeMockup = new NativeContactsApiMockup(); final PeopleContactsApiMockup peopleMockup = new PeopleContactsApiMockup(null); // add new contacts on native side feedNativeContactsApi(nativeMockup, 15, null); long[] nativeIds = nativeMockup.getContactIds(null); assertEquals(15, nativeIds.length); // import the new contacts runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); // delete some contacts on native side nativeMockup.removeContact(1); nativeMockup.removeContact(8); nativeMockup.removeContact(14); nativeIds = nativeMockup.getContactIds(null); assertEquals(12, nativeIds.length); // sync with people side runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); } /** * Tests multiple imports from native with an updated contact via added details. */ public void testMultipleImportsFromNativeWithUpdatedContact_addedDetails() { final NativeContactsApiMockup nativeMockup = new NativeContactsApiMockup(); final PeopleContactsApiMockup peopleMockup = new PeopleContactsApiMockup(null); // add new contacts on native side feedNativeContactsApi(nativeMockup, 20, null); long[] nativeIds = nativeMockup.getContactIds(null); assertEquals(20, nativeIds.length); // import the new contacts runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); // pick an existing contact and add details final ContactChange[] contact = nativeMockup.getContact(10); nativeMockup.setContact(10, addDetails(nativeMockup, contact)); // import the new contacts runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); } /** * Tests multiple imports from native with an updated contact via deleted details. */ public void testMultipleImportsFromNativeWithUpdatedContact_deletedDetails() { final NativeContactsApiMockup nativeMockup = new NativeContactsApiMockup(); final PeopleContactsApiMockup peopleMockup = new PeopleContactsApiMockup(null); // add new contacts on native side feedNativeContactsApi(nativeMockup, 20, null); long[] nativeIds = nativeMockup.getContactIds(null); assertEquals(20, nativeIds.length); // import the new contacts runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); // pick an existing contact and delete details final ContactChange[] originalContact = nativeMockup.getContact(10); nativeMockup.setContact(10, addDetails(nativeMockup, originalContact)); // import the new contacts runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); // remove the added details by setting the contact back to its previous state nativeMockup.setContact(10, originalContact); // import the new contacts runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); } /** * Tests multiple imports from native with an updated contact via updated details. */ public void testMultipleImportsFromNativeWithUpdatedContact_updatedDetails() { final NativeContactsApiMockup nativeMockup = new NativeContactsApiMockup(); final PeopleContactsApiMockup peopleMockup = new PeopleContactsApiMockup(null); // add new contacts on native side feedNativeContactsApi(nativeMockup, 20, null); long[] nativeIds = nativeMockup.getContactIds(null); assertEquals(20, nativeIds.length); // import the new contacts runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); // pick an existing contact final ContactChange[] originalContact = nativeMockup.getContact(10); // modify its details for (int i = 0; i < originalContact.length; i++) { final ContactChange originalChange = originalContact[i]; originalContact[i] = alterContactChangeValue(originalChange, originalChange.getValue()+"x9x"); } nativeMockup.setContact(10, originalContact); // import the new contacts runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); } /** * Tests that the correct accounts are used during the first time import and later on. * * Here there are no Google accounts at all so the import shall be performed from the * "null" account on both Android platforms (1.X and 2.X). */ public void testAccounts_firstTimeImport_noGoogleAccounts() { final NativeContactsApiMockup nativeMockup = new NativeContactsApiMockup(); final PeopleContactsApiMockup peopleMockup = new PeopleContactsApiMockup2(null); // feed contacts on native side feedNativeContactsApi(nativeMockup, 20, null); final long[] thirdPartyIds = nativeMockup.getContactIds(null); assertEquals(20, thirdPartyIds.length); // import the new contacts runNativeImporterFirstTimeImport(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); } /** * Tests that the correct accounts are used during the first time import and later on. * * -On Android 1.X platform: it is expected that the import is always performed from the "null" account (default) * -On Android 2.X platform: it is expected that the import is first performed from all the Google accounts or * the "null" account if no Google account are set */ public void testAccounts_firstTimeImport_2GoogleAccounts() { final NativeContactsApiMockup nativeMockup = new NativeContactsApiMockup(); final PeopleContactsApiMockup peopleMockup = new PeopleContactsApiMockup2(null); final boolean is2XPlatform = VersionUtils.is2XPlatform(); if (is2XPlatform) { // add contact in 2 Google accounts nativeMockup.feedAccount(GMAIL_ACCOUNT_1); feedNativeContactsApi(nativeMockup, 20, GMAIL_ACCOUNT_1); nativeMockup.feedAccount(GMAIL_ACCOUNT_2); feedNativeContactsApi(nativeMockup, 20, GMAIL_ACCOUNT_2); // add extra contacts in the third party account (they shall be ignored by the importer) nativeMockup.feedAccount(THIRD_PARTY_ACCOUNT); feedNativeContactsApi(nativeMockup, 20, THIRD_PARTY_ACCOUNT); // add extra contacts in the People account (they shall be ignored by the importer) nativeMockup.feedAccount(PEOPLE_ACCOUNT); feedNativeContactsApi(nativeMockup, 20, PEOPLE_ACCOUNT); final long[] thirdPartyIds = nativeMockup.getContactIds(THIRD_PARTY_ACCOUNT); assertEquals(20, thirdPartyIds.length); final long[] gmail1Ids = nativeMockup.getContactIds(GMAIL_ACCOUNT_1); assertEquals(20, gmail1Ids.length); final long[] gmail2Ids = nativeMockup.getContactIds(GMAIL_ACCOUNT_2); assertEquals(20, gmail2Ids.length); final long[] peopleIds = nativeMockup.getContactIds(PEOPLE_ACCOUNT); assertEquals(20, peopleIds.length); // import the new contacts runNativeImporterFirstTimeImport(nativeMockup, peopleMockup); // check that only the Google contacts have been imported final Account[] accounts = new Account[2]; accounts[0] = GMAIL_ACCOUNT_1; accounts[1] = GMAIL_ACCOUNT_2; assertTrue(compareNativeAndPeopleContactsList(nativeMockup, accounts, peopleMockup)); } else { // this test does not apply to Android 1.X so it just passes } } /** * Tests that the correct account for the next imports (i.e. not the first time import) * is used depending on the Android platform. * * -On Android 1.X: the import shall be done from the "null" account * -On Android 2.X: the import shall be done from the People account */ public void testAccounts_nextTimeImport() { final NativeContactsApiMockup nativeMockup = new NativeContactsApiMockup(); final PeopleContactsApiMockup peopleMockup = new PeopleContactsApiMockup(null); final boolean is2XPlatform = VersionUtils.is2XPlatform(); // add new contacts on native side if (is2XPlatform) { // in the People account for Android 2.X nativeMockup.feedAccount(PEOPLE_ACCOUNT); feedNativeContactsApi(nativeMockup, 20, PEOPLE_ACCOUNT); } else { // in the "null" account for Android 1.X feedNativeContactsApi(nativeMockup, 20, null); long[] nativeIds = nativeMockup.getContactIds(null); assertEquals(20, nativeIds.length); } // import the new contacts runNativeImporter(nativeMockup, peopleMockup); // compare contacts on both sides assertTrue(compareNativeAndPeopleContactsList(nativeMockup, null, peopleMockup)); } /** * Performs a native import and checks that the needed ticks are as expected. * * @param ncam the NativeContactsApiMockup instance * @param pcam the PeopleContactsApiMockup instance * @param contactsCount the number of native contacts to setup and import */ - private void performNativeImport(NativeContactsApiMockup ncam, PeopleContactsApiMockup pcam, int contactsCount) { + private void performNativeImport(NativeContactsApiMockup ncam, PeopleContactsApiMockup pcam, float contactsCount) { final NativeImporter nativeImporter = new NativeImporter(pcam, ncam, false); - final int requiredTicks = 1 + (contactsCount / NATIVE_IMPORTER_MAX_OPERATION_COUNT) + (contactsCount % NATIVE_IMPORTER_MAX_OPERATION_COUNT > 0 ? 1 : 0); + final float requiredTicks = 1 + (contactsCount / NATIVE_IMPORTER_MAX_OPERATION_COUNT) + (contactsCount % NATIVE_IMPORTER_MAX_OPERATION_COUNT > 0 ? 1 : 0); // feed the native side feedNativeContactsApi(ncam, contactsCount, null); final long[] nativeIds = ncam.getContactIds(null); assertEquals(contactsCount, nativeIds.length); // setup the people client side long[] peopleIds = pcam.getNativeContactsIds(); assertNull(peopleIds); for (int i = 0; i < requiredTicks; i++) { // check the importer state assertEquals(NativeImporter.RESULT_UNDEFINED, nativeImporter.getResult()); assertTrue(!nativeImporter.isDone()); // perform an import tick nativeImporter.tick(); } // check the importer state, it shall have finished the import assertEquals(NativeImporter.RESULT_OK, nativeImporter.getResult()); assertTrue(nativeImporter.isDone()); // check that all the native contacts are on the people client side peopleIds = pcam.getNativeContactsIds(); assertEquals(contactsCount, peopleIds.length); for (int i = 0; i < peopleIds.length; i++) { final ContactChange[] peopleContact = pcam.getContact(peopleIds[i]); final ContactChange[] nativeContact = pcam.getContact(nativeIds[i]); assertTrue(ContactChangeHelper.areChangeListsEqual(peopleContact, nativeContact, false)); } } /** * Runs the NativeImporter until it finishes synchronizing. * * @param ncam the NativeContactsApiMockup instance * @param pcam the PeopleContactsApiMockup instance */ private void runNativeImporter(NativeContactsApiMockup ncam, PeopleContactsApiMockup pcam) { final NativeImporter nativeImporter = new NativeImporter(pcam, ncam, false); while (!nativeImporter.isDone()) { // run the NativeImporter until the import from native is over nativeImporter.tick(); } } /** * Runs the NativeImporter for a first time import until it finishes synchronizing. * * @param ncam the NativeContactsApiMockup instance * @param pcam the PeopleContactsApiMockup instance */ private void runNativeImporterFirstTimeImport(NativeContactsApiMockup ncam, PeopleContactsApiMockup pcam) { final NativeImporter nativeImporter = new NativeImporter(pcam, ncam, true); while (!nativeImporter.isDone()) { // run the NativeImporter until the import from native is over nativeImporter.tick(); } } /** * Compares the contacts stored on native and people side. * * @param ncam the handle to the NativeContactsApiMockup instance * @param pcam the handle to the PeopleContactsApiMockup instance * @return true if both sides contains exactly the same contacts, false otherwise */ public static boolean compareNativeAndPeopleContactsList(NativeContactsApiMockup ncam, Account[] accounts, PeopleContactsApiMockup pcam) { long[] nativeIds = null; long[] peopleIds = pcam.getNativeContactsIds(); // get the native ids if (accounts != null) { // get the ids for all the provided accounts and merge them into one array long[][] nativeIdsPerAccount = null; int totalNativeIds = 0; nativeIdsPerAccount = new long[accounts.length][]; for (int i = 0; i < nativeIdsPerAccount.length; i++) { nativeIdsPerAccount[i] = ncam.getContactIds(accounts[i]); totalNativeIds += nativeIdsPerAccount[i].length; } nativeIds = new long[totalNativeIds]; int index = 0; for (int i = 0; i < nativeIdsPerAccount.length; i++) { System.arraycopy(nativeIdsPerAccount[i], 0, nativeIds, index, nativeIdsPerAccount[i].length); index += nativeIdsPerAccount[i].length; } Arrays.sort(nativeIds); } else { // get all the ids nativeIds = ncam.getContactIds(null); } // compare contacts from both sides if (nativeIds == null && peopleIds == null) { // both sides are empty return true; } else if (nativeIds == null || peopleIds == null) { return false; } else { if (nativeIds.length != peopleIds.length) { return false; } else { for (int i = 0; i < nativeIds.length; i++) { if (nativeIds[i] != peopleIds[i]) { return false; } final ContactChange[] nativeContact = ncam.getContact(nativeIds[i]); final ContactChange[] peopleContact = pcam.getContact(peopleIds[i]); if (nativeContact == null && peopleContact == null) { continue; } else if (nativeContact == null || peopleContact == null) { return false; } else { if (!ContactChangeHelper.areChangeListsEqual(nativeContact, peopleContact, false)) { return false; } } } return true; } } } /** * Feeds contacts to the native side. * * @param ncam the handle to the NativeContactsApiMockup instance * @param contactsCount the number of contacts to add * @param account the account where to add the contact */ - private void feedNativeContactsApi(NativeContactsApiMockup ncam, int contactsCount, Account account) { + private void feedNativeContactsApi(NativeContactsApiMockup ncam, float contactsCount, Account account) { for (int i = 0; i < contactsCount; i++) { final ContactChange[] contact = ContactChangeHelper.randomContact(ContactChange.INVALID_ID, ContactChange.INVALID_ID, ContactChange.INVALID_ID); ncam.addContact(account, contact); } } /** * Adds details to the provided contact. * * @param contact * @return */ private ContactChange[] addDetails(NativeContactsApiMockup ncam, ContactChange[] contact) { long nativeId = contact[0].getNabContactId(); int index = contact.length; // create the new Contact ContactChange[] newContact = new ContactChange[contact.length + 2]; // copy original info into it System.arraycopy(contact, 0, newContact, 0, contact.length); // add extra details newContact[index] = new ContactChange(ContactChange.KEY_VCARD_EMAIL, "[email protected]", ContactChange.FLAG_WORK); newContact[index].setNabContactId(nativeId); newContact[index].setNabDetailId(ncam.getAndIncNabDetailId()); index++; newContact[index] = new ContactChange(ContactChange.KEY_VCARD_PHONE, "+9912345678", ContactChange.FLAG_WORK); newContact[index].setNabContactId(nativeId); newContact[index].setNabDetailId(ncam.getAndIncNabDetailId()); index++; return newContact; } /** * Mocks up the PeopleContactsApi. */ public static class PeopleContactsApiMockup extends PeopleContactsApi { protected Hashtable<Long, ContactChange[]> mPeopleContacts = new Hashtable<Long, ContactChange[]>(); protected int mLocalContactId = 1; protected int mLocalDetailId = 1; public PeopleContactsApiMockup(DatabaseHelper dbh) { super(null); } public int getAndIncLocalDetailId() { return mLocalDetailId++; } @Override public long[] getNativeContactsIds() { if (mPeopleContacts.size() > 0) { final Enumeration<ContactChange[]> e = mPeopleContacts.elements(); final long[] ids = new long[mPeopleContacts.size()]; int idIndex = 0; while (e.hasMoreElements()) { final ContactChange[] contact = e.nextElement(); ids[idIndex++] = contact[0].getNabContactId(); } Arrays.sort(ids); return ids; } else { return null; } } @Override public boolean addNativeContact(ContactChange[] contact) { // set the local ids for (int i = 0; i < contact.length; i++) { contact[i].setInternalContactId(mLocalContactId); contact[i].setInternalDetailId(mLocalDetailId++); } mLocalContactId++; // add the contact via its native id !!! mPeopleContacts.put(contact[0].getNabContactId(), contact); return true; } @Override public boolean deleteNativeContact(long nativeId, boolean syncToNative) { if (mPeopleContacts.containsKey(nativeId)) { mPeopleContacts.remove(nativeId); } return false; } @Override public ContactChange[] getContact(long nativeId) { // return a copy, the NativeImporter may mess with it final ContactChange[] original = mPeopleContacts.get(nativeId); ContactChange[] copy = null; copy = new ContactChange[original.length]; for (int i = 0; i < original.length; i++) { copy[i] = copyContactChange(original[i]); } return copy; } @Override public void updateNativeContact(ContactChange[] contact) { // get the original contact final ContactChange[] originalContact = getContact(contact[0].getNabContactId()); final ArrayList<ContactChange> contactArrayList = new ArrayList<ContactChange>(); // put it in an ArrayList so we can easily manipulate it for (int i = 0; i < originalContact.length; i++) { contactArrayList.add(originalContact[i]); } // apply the updates for (int i = 0; i < contact.length; i++) { final ContactChange change = copyContactChange(contact[i]); final int type = change.getType(); switch(type) { case ContactChange.TYPE_ADD_DETAIL: change.setInternalDetailId(mLocalDetailId++); change.setType(ContactChange.TYPE_UNKNOWN); contactArrayList.add(change); break; case ContactChange.TYPE_DELETE_DETAIL: case ContactChange.TYPE_UPDATE_DETAIL: for (int j = 0; j < contactArrayList.size(); j++) { final ContactChange changeInList = contactArrayList.get(j); if (changeInList.getNabDetailId() == change.getNabDetailId()) { if (type == ContactChange.TYPE_DELETE_DETAIL) { contactArrayList.remove(j); } else { change.setType(ContactChange.TYPE_UNKNOWN); contactArrayList.set(j, change); } break; } } break; } } // set the updated contact back final ContactChange[] newContactChanges = new ContactChange[contactArrayList.size()]; contactArrayList.toArray(newContactChanges); mPeopleContacts.put(newContactChanges[0].getNabContactId(), newContactChanges); } } /** * Mocks up the NativeContactsApi. */ public static class NativeContactsApiMockup extends NativeContactsApi { /** * A Hashtable of contacts where the key is the contact id. */ private Hashtable<Long, ContactChange[]> mNativeContacts = new Hashtable<Long, ContactChange[]>(); /** * An Hashtable of accounts associated to an array of contact ids. */ private Hashtable<Account, ArrayList<Long>> mAccounts = new Hashtable<Account, ArrayList<Long>>(); /** * The counter used to generate new contact ids. */ private int mNabId = 1; /** * The counter used to generate new detail ids. */ private int mNabDetailId = 1; public int getAndIncNabDetailId() { return mNabDetailId++; } @Override public ContactChange[] getContact(long nabContactId) { // return a copy, the NativeImporter may mess with it final ContactChange[] original = mNativeContacts.get(nabContactId); ContactChange[] copy = null; if (original != null) { copy = new ContactChange[original.length]; for (int i = 0; i < original.length; i++) { copy[i] = copyContactChange(original[i]); } } return copy; } @Override public long[] getContactIds(Account account) { if (account == null) { // return all the ids if (mNativeContacts.size() > 0) { final Enumeration<ContactChange[]> e = mNativeContacts.elements(); final long[] ids = new long[mNativeContacts.size()]; int idIndex = 0; while (e.hasMoreElements()) { final ContactChange[] contact = e.nextElement(); ids[idIndex++] = contact[0].getNabContactId(); } Arrays.sort(ids); return ids; } else { return null; } } else { // return the ids depending on the account final ArrayList<Long> idsArray = mAccounts.get(account); if (idsArray != null) { final long[] ids = new long[idsArray.size()]; for (int i = 0; i < ids.length; i++) { ids[i] = idsArray.get(i); } Arrays.sort(ids); return ids; } } return null; } /** * */ public void feedAccount(Account account) { mAccounts.put(account, new ArrayList<Long>()); } /** * * @param nativeId * @param newContactChange */ public void setContact(long nativeId, ContactChange[] newContactChange) { mNativeContacts.put(nativeId, newContactChange); } @Override public ContactChange[] addContact(Account account, ContactChange[] ccList) { // set the native ids for (int i = 0; i < ccList.length; i++) { ccList[i].setNabContactId(mNabId); ccList[i].setNabDetailId(mNabDetailId++); } mNabId++; mNativeContacts.put(ccList[0].getNabContactId(), ccList); if (account != null) { // add the contact id in the account as well final ArrayList<Long> ids = mAccounts.get(account); ids.add(ccList[0].getNabContactId()); } // we have to return an array of native ids ContactChange[] copy = null; copy = new ContactChange[ccList.length + 1]; copy[0] = copyContactChange(ccList[0]); for (int i = 0; i < ccList.length; i++) { copy[i+1] = copyContactChange(ccList[i]); } return copy; } @Override public boolean addPeopleAccount(String username) { // TODO Auto-generated method stub return false; } @Override public Account[] getAccounts() { if (mAccounts.size() == 0) { return null; } else { int index = 0; Account[] accounts = new Account[mAccounts.size()]; Enumeration<Account> enumeration = mAccounts.keys(); while (enumeration.hasMoreElements()) { accounts[index++] = enumeration.nextElement(); } return accounts; } } @Override public Account[] getAccountsByType(int type) { switch (type){ case GOOGLE_ACCOUNT_TYPE: return filterAccountsByType(getAccounts(), GOOGLE_ACCOUNT_TYPE_STRING); case PEOPLE_ACCOUNT_TYPE: return filterAccountsByType(getAccounts(), PEOPLE_ACCOUNT_TYPE_STRING); default: return null; } } @Override protected void initialize() { // TODO Auto-generated method stub } @Override public boolean isPeopleAccountCreated() { // TODO Auto-generated method stub return false; } @Override public void registerObserver(ContactsObserver observer) { // TODO Auto-generated method stub } @Override public void removeContact(long nabContactId) { final Account[] accounts = getAccounts(); if (accounts != null) { for (int i = 0; i < accounts.length; i++) { final ArrayList<Long> ids = mAccounts.get(accounts[i]); ids.remove(nabContactId); } } mNativeContacts.remove(nabContactId); } @Override public void removePeopleAccount() { // TODO Auto-generated method stub } @Override public void unregisterObserver() { // TODO Auto-generated method stub } @Override public ContactChange[] updateContact(ContactChange[] ccList) { // get the original contact final ContactChange[] originalContact = getContact(ccList[0].getNabContactId()); final ArrayList<ContactChange> contactArrayList = new ArrayList<ContactChange>(); // put it in an ArrayList so we can easily manipulate it for (int i = 0; i < originalContact.length; i++) { contactArrayList.add(originalContact[i]); } final ContactChange[] returnedChanges = new ContactChange[ccList.length]; // apply the updates for (int i = 0; i < ccList.length; i++) { final ContactChange change = copyContactChange(ccList[i]); final int type = change.getType(); switch(type) { case ContactChange.TYPE_ADD_DETAIL: returnedChanges[i] = copyContactChange(ccList[i]); returnedChanges[i].setNabDetailId(mNabDetailId); returnedChanges[i].setType(ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); change.setInternalDetailId(mNabDetailId++); change.setType(ContactChange.TYPE_UNKNOWN); contactArrayList.add(change); break; case ContactChange.TYPE_DELETE_DETAIL: case ContactChange.TYPE_UPDATE_DETAIL: for (int j = 0; j < contactArrayList.size(); j++) { final ContactChange changeInList = contactArrayList.get(j); if (changeInList.getNabDetailId() == change.getNabDetailId()) { if (type == ContactChange.TYPE_DELETE_DETAIL) { contactArrayList.remove(j); } else { change.setType(ContactChange.TYPE_UNKNOWN); contactArrayList.set(j, change); } break; } } returnedChanges[i] = null; break; } } // set the updated contact back final ContactChange[] newContactChanges = new ContactChange[contactArrayList.size()]; contactArrayList.toArray(newContactChanges); mNativeContacts.put(newContactChanges[0].getNabContactId(), newContactChanges); return ccList; } @Override public boolean isKeySupported(int key) { return true; } } /** * A second version of PeopleContactsApiMockup only used for testing accounts. * * Note: it is a modified version of PeopleContactsApiMockup which adds a trick * on the id used to store the contact in order to easily test the account features * without writing a more sophisticated mockup of PeopleContactsApi. */ public class PeopleContactsApiMockup2 extends PeopleContactsApiMockup { public PeopleContactsApiMockup2(DatabaseHelper dbh) { super(null); } @Override public long[] getNativeContactsIds() { if (mPeopleContacts.size() > 0) { final Enumeration<ContactChange[]> e = mPeopleContacts.elements(); final long[] ids = new long[mPeopleContacts.size()]; int idIndex = 0; while (e.hasMoreElements()) { final ContactChange[] contact = e.nextElement(); ids[idIndex++] = contact[0].getInternalContactId(); } Arrays.sort(ids);
360/360-Engine-for-Android
72c65031a74b108ea26696cb4188675964b5a59e
Editing name of contact was buggy, fixed
diff --git a/src/com/vodafone360/people/database/tables/ContactSummaryTable.java b/src/com/vodafone360/people/database/tables/ContactSummaryTable.java index 63dbe75..6a78ac4 100644 --- a/src/com/vodafone360/people/database/tables/ContactSummaryTable.java +++ b/src/com/vodafone360/people/database/tables/ContactSummaryTable.java @@ -649,684 +649,685 @@ public abstract class ContactSummaryTable { return false; case VCARD_ROLE: case VCARD_TITLE: break; default: return true; } break; case VCARD_ORG: // AA:will be updating everything, except for EMAIL and ORG, // when preferred details needs to be considered first switch (currentDetail.key) { case VCARD_EMAIL: return false; case VCARD_ORG: break; default: return true; } break; case VCARD_EMAIL: // AA:will be updating everything, except for EMAIL, when // preferred details needs to be considered first switch (currentDetail.key) { case VCARD_EMAIL: break; default: return true; } break; default: return false; } if (currentDetail.order == null) { return true; } if (newDetail.order != null && newDetail.order.compareTo(currentDetail.order) < 0) { return true; } return false; } /** * Fetches a list of native contact IDs from the summary table (in ascending * order) * * @param summaryList A list that will be populated by this function * @param readableDb Readable SQLite database * @return true if successful, false otherwise */ public static boolean fetchNativeContactIdList(List<Integer> summaryList, SQLiteDatabase readableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(false, "ContactSummeryTable.fetchNativeContactIdList()"); } summaryList.clear(); Cursor c = null; try { c = readableDb.rawQuery("SELECT " + Field.NATIVEID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVEID + " IS NOT NULL" + " ORDER BY " + Field.NATIVEID, null); while (c.moveToNext()) { if (!c.isNull(0)) { summaryList.add(c.getInt(0)); } } return true; } catch (SQLException e) { return false; } finally { CloseUtils.close(c); c = null; } } /** * Modifies the avatar loaded flag for a particular contact * * @param localContactID The primary key ID of the contact * @param value Can be one of the following values: * <ul> * <li>true - The avatar has been loaded</li> * <li>false - There contact has an avatar but it has not yet * been loaded</li> * <li>null - The contact does not have an avatar</li> * </ul> * @param writeableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus modifyPictureLoadedFlag(Long localContactId, Boolean value, SQLiteDatabase writeableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(true, "ContactSummeryTable.modifyPictureLoadedFlag() localContactId[" + localContactId + "] value[" + value + "]"); } try { ContentValues cv = new ContentValues(); cv.put(Field.PICTURELOADED.toString(), value); String[] args = { String.format("%d", localContactId) }; if (writeableDb.update(TABLE_NAME, cv, Field.LOCALCONTACTID + "=?", args) <= 0) { LogUtils.logE("ContactSummeryTable.modifyPictureLoadedFlag() " + "Unable to modify picture loaded flag"); return ServiceStatus.ERROR_NOT_FOUND; } } catch (SQLException e) { LogUtils.logE("ContactSummeryTable.modifyPictureLoadedFlag() " + "SQLException - Unable to modify picture loaded flag", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } /** * Get a group constraint for SQL query depending on the group type. * * @param groupFilterId the group id * @return a String containing the corresponding group constraint */ private static String getGroupConstraint(Long groupFilterId) { if ((groupFilterId != null) && (groupFilterId == GroupsTable.GROUP_PHONEBOOK)) { return " WHERE " + ContactSummaryTable.Field.SYNCTOPHONE + "=" + "1"; } if ((groupFilterId != null) && (groupFilterId == GroupsTable.GROUP_CONNECTED_FRIENDS)) { return " WHERE " + ContactSummaryTable.Field.FRIENDOFMINE + "=" + "1"; } if ((groupFilterId != null) && (groupFilterId == GroupsTable.GROUP_ONLINE)) { String inClause = getOnlineWhereClause(); return " WHERE " + ContactSummaryTable.Field.LOCALCONTACTID + " IN " + (inClause == null? "()": inClause); } return " INNER JOIN " + ContactGroupsTable.TABLE_NAME + " WHERE " + ContactSummaryTable.TABLE_NAME + "." + ContactSummaryTable.Field.LOCALCONTACTID + "=" + ContactGroupsTable.TABLE_NAME + "." + ContactGroupsTable.Field.LOCALCONTACTID + " AND " + ContactGroupsTable.Field.ZYBGROUPID + "=" + groupFilterId; } /** * Fetches a contact list cursor for a given filter and search constraint * * @param groupFilterId The server group ID or null to fetch all groups * @param constraint A search string or null to fetch without constraint * @param meProfileId The current me profile Id which should be excluded * from the returned list. * @param readableDb Readable SQLite database * @return The cursor or null if an error occurred * @see #getQueryData(Cursor) */ public static Cursor openContactSummaryCursor(Long groupFilterId, CharSequence constraint, Long meProfileId, SQLiteDatabase readableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(false, "ContactSummeryTable.fetchContactList() " + "groupFilterId[" + groupFilterId + "] constraint[" + constraint + "]" + " meProfileId[" + meProfileId + "]"); } try { if (meProfileId == null) { // Ensure that when the profile is not available the function // doesn't fail // Since "Field <> null" always returns false meProfileId = -1L; } if (groupFilterId == null) { if (constraint == null) { // Fetch all contacts return openContactSummaryCursor(groupFilterId, meProfileId, readableDb); } else { return openContactSummaryCursor(constraint, meProfileId, readableDb); } } else { // filtering by group id if (constraint == null) { return openContactSummaryCursor(groupFilterId, meProfileId, readableDb); } else { // filter by both group and constraint final String dbSafeConstraint = DatabaseUtils.sqlEscapeString("%" + constraint + "%"); return readableDb.rawQuery("SELECT " + ContactSummaryTable.getFullQueryList() + " FROM " + ContactSummaryTable.TABLE_NAME + getGroupConstraint(groupFilterId) + " AND " + ContactSummaryTable.Field.DISPLAYNAME + " LIKE " + dbSafeConstraint + " AND " + ContactSummaryTable.TABLE_NAME + "." + ContactSummaryTable.Field.LOCALCONTACTID + "<>" + meProfileId + " ORDER BY LOWER(" + ContactSummaryTable.Field.DISPLAYNAME + ")", null); } } } catch (SQLException e) { LogUtils.logE("ContactSummeryTable.fetchContactList() " + "SQLException - Unable to fetch filtered summary cursor", e); return null; } } /** * Fetches a contact list cursor for a given filter * * @param groupFilterId The server group ID or null to fetch all groups * @param meProfileId The current me profile Id which should be excluded * from the returned list. * @param readableDb Readable SQLite database * @return The cursor or null if an error occurred * @see #getQueryData(Cursor) */ private static Cursor openContactSummaryCursor(Long groupFilterId, Long meProfileId, SQLiteDatabase readableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(false, "ContactSummeryTable.fetchContactList() groupFilterId[" + groupFilterId + "] meProfileId[" + meProfileId + "]"); } try { if (groupFilterId == null) { // Fetch all contacts return readableDb.rawQuery(getOrderedQueryStringSql(ContactSummaryTable.TABLE_NAME + "." + ContactSummaryTable.Field.LOCALCONTACTID + "<>" + meProfileId), null); } return readableDb.rawQuery("SELECT " + ContactSummaryTable.getFullQueryList() + " FROM " + ContactSummaryTable.TABLE_NAME + getGroupConstraint(groupFilterId) + " AND " + ContactSummaryTable.TABLE_NAME + "." + ContactSummaryTable.Field.LOCALCONTACTID + "!=" + meProfileId + " ORDER BY LOWER(" + ContactSummaryTable.Field.DISPLAYNAME + ")", null); } catch (SQLException e) { LogUtils.logE("ContactSummeryTable.fetchContactList() " + "SQLException - Unable to fetch filtered summary cursor", e); return null; } } /** * Fetches a contact list cursor for a given search constraint * * @param constraint A search string or null to fetch without constraint * @param meProfileId The current me profile Id which should be excluded * from the returned list. * @param readableDb Readable SQLite database * @return The cursor or null if an error occurred * @see #getQueryData(Cursor) */ private static Cursor openContactSummaryCursor(CharSequence constraint, Long meProfileId, SQLiteDatabase readableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(false, "ContactSummeryTable.fetchContactList() constraint[" + constraint + "] meProfileId[" + meProfileId + "]"); } try { if (constraint == null) { // Fetch all contacts return readableDb.rawQuery(getOrderedQueryStringSql(), null); } final String dbSafeConstraint = DatabaseUtils.sqlEscapeString("%" + constraint + "%"); return readableDb.rawQuery("SELECT " + ContactSummaryTable.getFullQueryList() + " FROM " + ContactSummaryTable.TABLE_NAME + " WHERE " + ContactSummaryTable.Field.DISPLAYNAME + " LIKE " + dbSafeConstraint + " AND " + ContactSummaryTable.TABLE_NAME + "." + ContactSummaryTable.Field.LOCALCONTACTID + "!=" + meProfileId + " ORDER BY LOWER(" + ContactSummaryTable.Field.DISPLAYNAME + ")", null); } catch (SQLException e) { LogUtils.logE("ContactSummeryTable.fetchContactList() " + "SQLException - Unable to fetch filtered summary cursor", e); return null; } } /** * Fetches the current alternative field type for a contact This value * determines how the alternative detail is currently being used for the * record. * * @param localContactID The primary key ID of the contact * @param readableDb Readable SQLite database * @return The alternative field type or null if a database error occurred */ /* * private static AltFieldType fetchAltFieldType(long localContactId, * SQLiteDatabase readableDb) { if (Settings.ENABLED_DATABASE_TRACE) { * DatabaseHelper.trace(false, * "ContactSummeryTable.FetchAltFieldType() localContactId[" + * localContactId + "]"); } Cursor c = null; try { c = * readableDb.rawQuery("SELECT " + Field.ALTFIELDTYPE + " FROM " + * ContactSummaryTable.TABLE_NAME + " WHERE " + Field.LOCALCONTACTID + "=" + * localContactId, null); AltFieldType type = AltFieldType.UNUSED; if * (c.moveToFirst() && !c.isNull(0)) { int val = c.getInt(0); if (val < * AltFieldType.values().length) { type = AltFieldType.values()[val]; } } * return type; } catch (SQLException e) { * LogUtils.logE("ContactSummeryTable.fetchContactList() " + * "SQLException - Unable to fetch alt field type", e); return null; } * finally { CloseUtils.close(c); c = null; } } */ /** * Fetches an SQLite statement object which can be used to merge the native * information from one contact to another. * * @param writableDb Writable SQLite database * @return The SQL statement, or null if a compile error occurred * @see #mergeContact(ContactIdInfo, SQLiteStatement) */ public static SQLiteStatement mergeContactStatement(SQLiteDatabase writableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(true, "ContactSummeryTable.mergeContact()"); } try { return writableDb.compileStatement(UPDATE_NATIVE_ID_BY_LOCAL_CONTACT_ID); } catch (SQLException e) { LogUtils.logE("ContactSummaryTable.mergeContactStatement() compile error:\n", e); return null; } } /** * Copies the contact native information from one contact to another * * @param info Copies the {@link ContactIdInfo#nativeId} value to the * contact with local ID {@link ContactIdInfo#mergedLocalId}. * @param statement The statement returned by * {@link #mergeContactStatement(SQLiteDatabase)}. * @return SUCCESS or a suitable error code * @see #mergeContactStatement(SQLiteDatabase) */ public static ServiceStatus mergeContact(ContactIdInfo info, SQLiteStatement statement) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(true, "ContactSummeryTable.mergeContact()"); } if (statement == null) { return ServiceStatus.ERROR_DATABASE_CORRUPT; } try { statement.bindLong(1, info.nativeId); statement.bindLong(2, info.mergedLocalId); statement.execute(); return ServiceStatus.SUCCESS; } catch (SQLException e) { LogUtils.logE("ContactSummeryTable.mergeContact() " + "SQLException - Unable to merge contact summary native info:\n", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } /** * TODO: be careful * * @param user * @param writableDb * @return */ public synchronized static ServiceStatus updateOnlineStatus(User user) { sPresenceMap.put(user.getLocalContactId(), user.isOnline()); return ServiceStatus.SUCCESS; } /** * This method sets users offline except for provided local contact ids. * @param userIds - ArrayList of integer user ids, if null - all user will be removed from the presence hash. * @param writableDb - database. */ public synchronized static void setUsersOffline(ArrayList<Long> userIds) { Iterator<Long> itr = sPresenceMap.keySet().iterator(); Long localId = null; while(itr.hasNext()) { localId = itr.next(); if (userIds == null || !userIds.contains(localId)) { itr.remove(); } } } /** * @param user * @param writableDb * @return */ public synchronized static ServiceStatus setOfflineStatus() { // If any contact is not present within the presenceMap, then its status // is considered as OFFLINE. This is taken care in the getPresence API. if (sPresenceMap != null) { sPresenceMap.clear(); } return ServiceStatus.SUCCESS; } /** * @param localContactIdOfMe * @param writableDb * @return */ public synchronized static ServiceStatus setOfflineStatusExceptForMe(long localContactIdOfMe) { // If any contact is not present within the presenceMap, then its status // is considered as OFFLINE. This is taken care in the getPresence API. if (sPresenceMap != null) { sPresenceMap.clear(); sPresenceMap.put(localContactIdOfMe, OnlineStatus.OFFLINE.ordinal()); } return ServiceStatus.SUCCESS; } /** * Updates the native IDs for a list of contacts. * * @param contactIdList A list of ContactIdInfo objects. For each object, * the local ID must match a local contact ID in the table. The * Native ID will be used for the update. Other fields are * unused. * @param writeableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus syncSetNativeIds(List<ContactIdInfo> contactIdList, SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "ContactSummaryTable.syncSetNativeIds()"); if (contactIdList.size() == 0) { return ServiceStatus.SUCCESS; } final SQLiteStatement statement1 = writableDb.compileStatement("UPDATE " + TABLE_NAME + " SET " + Field.NATIVEID + "=? WHERE " + Field.LOCALCONTACTID + "=?"); for (int i = 0; i < contactIdList.size(); i++) { final ContactIdInfo info = contactIdList.get(i); try { writableDb.beginTransaction(); if (info.nativeId == null) { statement1.bindNull(1); } else { statement1.bindLong(1, info.nativeId); } statement1.bindLong(2, info.localId); statement1.execute(); writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ContactSummaryTable.syncSetNativeIds() " + "SQLException - Unable to update contact native Ids", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } return ServiceStatus.SUCCESS; } private static boolean isEmpty(String string) { if (string == null) return true; if (string.trim().length() == 0) return true; return false; } /** * Updates the summary for a contact Replaces the complex logic of updating * the summary with a new contactdetail. Instead the method gets a whole * contact after it has been modified and builds the summary infos. * * @param contact A Contact object that has been modified * @param writeableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus updateContactDisplayName(Contact contact, SQLiteDatabase writableDb) { // These two Arrays contains the order in which the details are queried. // First valid (not empty or unknown) detail is taken ContactDetail.DetailKeys prefferredNameDetails[] = { ContactDetail.DetailKeys.VCARD_NAME, ContactDetail.DetailKeys.VCARD_ORG, ContactDetail.DetailKeys.VCARD_EMAIL, ContactDetail.DetailKeys.VCARD_PHONE }; ContactDetail name = null; // Query the details for the name field for (ContactDetail.DetailKeys key : prefferredNameDetails) { if ((name = contact.getContactDetail(key)) != null) { // Some contacts have only email but the name detail!=null // (gmail for example) if (key == ContactDetail.DetailKeys.VCARD_NAME && name.getName() == null) continue; if (key != ContactDetail.DetailKeys.VCARD_NAME && isEmpty(name.getValue())) continue; break; } } // Build the name String nameString = name != null ? name.getValue() : null; if (nameString == null) nameString = ContactDetail.UNKNOWN_NAME; if (name != null && name.key == ContactDetail.DetailKeys.VCARD_NAME) nameString = name.getName().toString(); // Start updating the table SQLiteStatement statement = null; try { final StringBuffer updateQuery = StringBufferPool.getStringBuffer(SQLKeys.UPDATE); updateQuery.append(TABLE_NAME).append(SQLKeys.SET).append(Field.DISPLAYNAME). append("=? WHERE ").append(Field.LOCALCONTACTID).append("=?"); statement = writableDb.compileStatement(StringBufferPool.toStringThenRelease(updateQuery)); writableDb.beginTransaction(); statement.bindString(1, nameString); + statement.bindLong(2, contact.localContactID); statement.execute(); writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ContactSummaryTable.updateNameAndStatus() " + "SQLException - Unable to update contact native Ids", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); if (statement != null) { statement.close(); statement = null; } } return ServiceStatus.SUCCESS; } /** * LocalId = ? */ private final static String SQL_STRING_LOCAL_ID_EQUAL_QUESTION_MARK = Field.LOCALCONTACTID + " = ?"; /** * * @param localContactId * @param writableDb * @return */ public static boolean setNativeContactId(long localContactId, long nativeContactId, SQLiteDatabase writableDb) { final ContentValues values = new ContentValues(); values.put(Field.NATIVEID.toString(), nativeContactId); try { if (writableDb.update(TABLE_NAME, values, SQL_STRING_LOCAL_ID_EQUAL_QUESTION_MARK, new String[] { Long.toString(localContactId) }) == 1) { return true; } } catch (Exception e) { LogUtils.logE("ContactsTable.setNativeContactId() Exception - " + e); } return false; } /** * Clears the Presence Map table. This needs to be called whenever the ContactSummaryTable is cleared * or recreated. */ private synchronized static void clearPresenceMap() { sPresenceMap.clear(); } /** * Fetches the presence of the contact with localContactID * * @param localContactID * @return the presence status of the contact */ public synchronized static OnlineStatus getPresence(Long localContactID) { OnlineStatus onlineStatus = OnlineStatus.OFFLINE; Integer val = sPresenceMap.get(localContactID); if (val != null) { if (val < ContactSummary.OnlineStatus.values().length) { onlineStatus = ContactSummary.OnlineStatus.values()[val]; } } return onlineStatus; } /** * This API should be called whenever a contact is added. The presenceMap should be consistent * with the ContactSummaryTable. Hence the default status of OFFLINE is set for every contact added * @param localContactID */ private synchronized static void addToPresenceMap(Long localContactID) { sPresenceMap.put(localContactID, OnlineStatus.OFFLINE.ordinal()); } /** * This API should be called whenever a contact is deleted from teh ContactSUmmaryTable. This API * removes the presence information for the given contact * @param localContactId */ private synchronized static void deleteFromPresenceMap(Long localContactId) { sPresenceMap.remove(localContactId); } /** * This API creates the string to be used in the IN clause when getting the list of all * online contacts. * @return The list of contacts in the proper format for the IN list */ private synchronized static String getOnlineWhereClause() { Set<Entry<Long, Integer>> set = sPresenceMap.entrySet(); Iterator<Entry<Long, Integer>> i = set.iterator(); String inClause = "("; boolean isFirst = true; while (i.hasNext()) { Entry<Long, Integer> me = (Entry<Long, Integer>) i.next(); Integer value = me.getValue(); if (value != null && (value == OnlineStatus.ONLINE.ordinal() || value == OnlineStatus.IDLE .ordinal())) { if (isFirst == false) { inClause = inClause.concat(","); } else { isFirst = false; } inClause = inClause.concat(String.valueOf(me.getKey())); } } if (isFirst == true) { inClause = null; } else { inClause = inClause.concat(")"); } return inClause; } /** * Fetches the formattedName for the corresponding localContactId. * * @param localContactId The primary key ID of the contact to find * @param readableDb Readable SQLite database * @return String formattedName or NULL on error */ public static String fetchFormattedNamefromLocalContactId( final long localContactId, final SQLiteDatabase readableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(false, "ContactSummaryTable.fetchFormattedNamefromLocalContactId" + " localContactId[" + localContactId + "]"); } Cursor c1 = null; String formattedName = null; try { String query = "SELECT " + Field.DISPLAYNAME + " FROM " + TABLE_NAME + " WHERE " + Field.LOCALCONTACTID + "=" + localContactId; c1 = readableDb.rawQuery(query, null); if (c1 != null && c1.getCount() > 0) { c1.moveToFirst(); formattedName = c1.getString(0); } return formattedName; } catch (SQLiteException e) { LogUtils .logE( "fetchFormattedNamefromLocalContactId() " + "Exception - Unable to fetch contact summary", e); return formattedName; } finally { CloseUtils.close(c1); c1 = null; } } }
360/360-Engine-for-Android
59aca84cd232c0d88d01084e6d42cb36cc349337
Increased number of items we store in the activities table to 400, max age is now 20 days.
diff --git a/src/com/vodafone360/people/database/tables/ActivitiesTable.java b/src/com/vodafone360/people/database/tables/ActivitiesTable.java index 68b3081..81a9614 100644 --- a/src/com/vodafone360/people/database/tables/ActivitiesTable.java +++ b/src/com/vodafone360/people/database/tables/ActivitiesTable.java @@ -1,1919 +1,1920 @@ -/* - * CDDL HEADER START - * - * The contents of this file are subject to the terms of the Common Development - * and Distribution License (the "License"). - * You may not use this file except in compliance with the License. - * - * You can obtain a copy of the license at - * src/com/vodafone360/people/VODAFONE.LICENSE.txt or - * http://github.com/360/360-Engine-for-Android - * See the License for the specific language governing permissions and - * limitations under the License. - * - * When distributing Covered Code, include this CDDL HEADER in each file and - * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. - * If applicable, add the following below this CDDL HEADER, with the fields - * enclosed by brackets "[]" replaced with your own identifying information: - * Portions Copyright [yyyy] [name of copyright owner] - * - * CDDL HEADER END - * - * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. - * Use is subject to license terms. - */ - -package com.vodafone360.people.database.tables; - -import java.util.ArrayList; -import java.util.List; - -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.database.DatabaseUtils; -import android.database.SQLException; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteException; -import android.database.sqlite.SQLiteStatement; -import android.net.Uri; -import android.provider.CallLog.Calls; -import android.telephony.PhoneNumberUtils; - -import com.vodafone360.people.Settings; -import com.vodafone360.people.database.DatabaseHelper; -import com.vodafone360.people.database.SQLKeys; -import com.vodafone360.people.database.utils.SqlUtils; -import com.vodafone360.people.datatypes.ActivityContact; -import com.vodafone360.people.datatypes.ActivityItem; -import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; -import com.vodafone360.people.service.ServiceStatus; -import com.vodafone360.people.utils.CloseUtils; -import com.vodafone360.people.utils.LogUtils; -import com.vodafone360.people.utils.StringBufferPool; - -/** - * Contains all the functionality related to the activities database table. This - * class is never instantiated hence all methods must be static. - * - * @version %I%, %G% - */ -public abstract class ActivitiesTable { - /*** - * The name of the table as it appears in the database. - */ - private static final String TABLE_NAME = "Activities"; - - private static final String TABLE_INDEX_NAME = "ActivitiesIndex"; - - /** Database cleanup will delete any activity older than X days. **/ - private static final int CLEANUP_MAX_AGE_DAYS = 10; - - /** Database cleanup will delete older activities after the first X. **/ - private static final int CLEANUP_MAX_QUANTITY = 200; - - /*** - * An enumeration of all the field names in the database. - */ - public static enum Field { - /** Local timeline id. **/ - LOCAL_ACTIVITY_ID("LocalId"), - /** Activity ID. **/ - ACTIVITY_ID("activityid"), - /** Timestamp. */ - TIMESTAMP("time"), - /** Type of the event. **/ - TYPE("type"), - /** URI. */ - URI("uri"), - /** Title for timelines . **/ - TITLE("title"), - /** Contents of timelines/statuses. **/ - DESCRIPTION("description"), - /** Preview URL. **/ - PREVIEW_URL("previewurl"), - /** Store. **/ - STORE("store"), - /** Type of the event: status, chat messages, phone call or SMS/MMS. **/ - FLAG("flag"), - /** Parent Activity. **/ - PARENT_ACTIVITY("parentactivity"), - /** Has children. **/ - HAS_CHILDREN("haschildren"), - /** Visibility. **/ - VISIBILITY("visibility"), - /** More info. **/ - MORE_INFO("moreinfo"), - /** Contact ID. **/ - CONTACT_ID("contactid"), - /** User ID. **/ - USER_ID("userid"), - /** Contact name or the alternative. **/ - CONTACT_NAME("contactname"), - /** Other contact's localContactId. **/ - LOCAL_CONTACT_ID("contactlocalid"), - /** @see SocialNetwork. **/ - CONTACT_NETWORK("contactnetwork"), - /** Contact address. **/ - CONTACT_ADDRESS("contactaddress"), - /** Contact avatar URL. **/ - CONTACT_AVATAR_URL("contactavatarurl"), - /** Native item type. **/ - NATIVE_ITEM_TYPE("nativeitemtype"), - /** Native item ID. **/ - NATIVE_ITEM_ID("nativeitemid"), - /** Latest contact status. **/ - LATEST_CONTACT_STATUS("latestcontactstatus"), - /** Native thread ID. **/ - NATIVE_THREAD_ID("nativethreadid"), - /** For chat messages: if this message is incoming. **/ - INCOMING("incoming"); - - /** Name of the field as it appears in the database. **/ - private final String mField; - - /** - * Constructor. - * - * @param field - The name of the field (see list above) - */ - private Field(final String field) { - mField = field; - } - - /** - * @return the name of the field as it appears in the database. - */ - public String toString() { - return mField; - } - - } - - /** - * An enumeration of supported timeline types. - */ - public static enum TimelineNativeTypes { - /** Call log type. **/ - CallLog, - /** SMS log type. **/ - SmsLog, - /** MMS log type. **/ - MmsLog, - /** Chat log type. **/ - ChatLog - } - - /** - * This class encapsulates a timeline activity item. - */ - public static class TimelineSummaryItem { - - /*** - * Enum of Timeline types. - */ - public enum Type { - /** Incoming type. **/ - INCOMING, - /** Outgoing type. **/ - OUTGOING, - /** Unsent type. **/ - UNSENT, - /** Unknown type (do not use). **/ - UNKNOWN - } - - /*** - * Get the Type from a given Integer value. - - * @param input Integer.ordinal value of the Type - * @return Relevant Type or UNKNOWN if the Integer is not known. - */ - public static Type getType(final int input) { - if (input < 0 || input > Type.UNKNOWN.ordinal()) { - return Type.UNKNOWN; - } else { - return Type.values()[input]; - } - } - - /** Maps to the local activity ID (primary key). **/ - private Long mLocalActivityId; - /** Maps to the activity timestamp in the table. **/ - public Long mTimestamp; - /** Maps to the contact name in the table. **/ - public String mContactName; - /** Set to true if there is an avatar URL stored in the table. **/ - private boolean mHasAvatar; - /** Maps to type in the table. **/ - public ActivityItem.Type mType; - /** Maps to local contact id in the table. **/ - public Long mLocalContactId; - /** Maps to contact network stored in the table. **/ - public String mContactNetwork; - /** Maps to title stored in the table. **/ - public String mTitle; - /** Maps to description stored in the table. **/ - public String mDescription; - /** - * Maps to native item type in the table Can be an ordinal from the - * {@link ActivitiesTable#TimelineNativeTypes}. - */ - public Integer mNativeItemType; - /** - * Key linking to the call-log or message-log item in the native - * database. - */ - public Integer mNativeItemId; - /** Server contact ID. **/ - public Long mContactId; - /** User ID from the server. **/ - public Long mUserId; - /** Thread ID from the native database (for messages). **/ - public Integer mNativeThreadId; - /** Contact address (phone number or email address). **/ - public String mContactAddress; - /** Messages can be incoming and outgoing. **/ - public Type mIncoming; - - /** - * Returns a string describing the timeline summary item. - * - * @return String describing the timeline summary item. - */ - @Override - public final String toString() { - final StringBuilder sb = - new StringBuilder("TimeLineSummaryItem [mLocalActivityId["); - sb.append(mLocalActivityId); - sb.append("], mTimestamp["); sb.append(mTimestamp); - sb.append("], mContactName["); sb.append(mContactName); - sb.append("], mHasAvatar["); sb.append(mHasAvatar); - sb.append("], mType["); sb.append(mType); - sb.append("], mLocalContactId["); sb.append(mLocalContactId); - sb.append("], mContactNetwork["); sb.append(mContactNetwork); - sb.append("], mTitle["); sb.append(mTitle); - sb.append("], mDescription["); sb.append(mDescription); - sb.append("], mNativeItemType["); sb.append(mNativeItemType); - sb.append("], mNativeItemId["); sb.append(mNativeItemId); - sb.append("], mContactId["); sb.append(mContactId); - sb.append("], mUserId["); sb.append(mUserId); - sb.append("], mNativeThreadId["); sb.append(mNativeThreadId); - sb.append("], mContactAddress["); sb.append(mContactAddress); - sb.append("], mIncoming["); sb.append(mIncoming); - sb.append("]]");; - return sb.toString(); - } - - @Override - public final boolean equals(final Object object) { - if (TimelineSummaryItem.class != object.getClass()) { - return false; - } - TimelineSummaryItem item = (TimelineSummaryItem) object; - return mLocalActivityId.equals(item.mLocalActivityId) - && mTimestamp.equals(item.mTimestamp) - && mContactName.equals(item.mContactName) - && mHasAvatar == item.mHasAvatar - && mType.equals(item.mType) - && mLocalContactId.equals(item.mLocalContactId) - && mContactNetwork.equals(item.mContactNetwork) - && mTitle.equals(item.mTitle) - && mDescription.equals(item.mDescription) - && mNativeItemType.equals(item.mNativeItemType) - && mNativeItemId.equals(item.mNativeItemId) - && mContactId.equals(item.mContactId) - && mUserId.equals(item.mUserId) - && mNativeThreadId.equals(item.mNativeThreadId) - && mContactAddress.equals(item.mContactAddress) - && mIncoming.equals(item.mIncoming); - } - }; - - /** Number of milliseconds in a day. **/ - private static final int NUMBER_OF_MS_IN_A_DAY = 24 * 60 * 60 * 1000; - /** Number of milliseconds in a second. **/ - private static final int NUMBER_OF_MS_IN_A_SECOND = 1000; - - /*** - * Private constructor to prevent instantiation. - */ - private ActivitiesTable() { - // Do nothing. - } - - /** - * Create Activities Table. - * - * @param writeableDb A writable SQLite database. - */ - public static void create(final SQLiteDatabase writeableDb) { - DatabaseHelper.trace(true, "DatabaseHelper.create()"); - writeableDb.execSQL("CREATE TABLE " + TABLE_NAME + " (" - + Field.LOCAL_ACTIVITY_ID - + " INTEGER PRIMARY KEY AUTOINCREMENT, " - + Field.ACTIVITY_ID + " LONG, " - + Field.TIMESTAMP + " LONG, " - + Field.TYPE + " TEXT, " - + Field.URI + " TEXT, " - + Field.TITLE + " TEXT, " - + Field.DESCRIPTION + " TEXT, " - + Field.PREVIEW_URL + " TEXT, " - + Field.STORE + " TEXT, " - + Field.FLAG + " INTEGER, " - + Field.PARENT_ACTIVITY + " LONG, " - + Field.HAS_CHILDREN + " INTEGER, " - + Field.VISIBILITY + " INTEGER, " - + Field.MORE_INFO + " TEXT, " - + Field.CONTACT_ID + " LONG, " - + Field.USER_ID + " LONG, " - + Field.CONTACT_NAME + " TEXT, " - + Field.LOCAL_CONTACT_ID + " LONG, " - + Field.CONTACT_NETWORK + " TEXT, " - + Field.CONTACT_ADDRESS + " TEXT, " - + Field.CONTACT_AVATAR_URL + " TEXT, " - + Field.LATEST_CONTACT_STATUS + " INTEGER, " - + Field.NATIVE_ITEM_TYPE + " INTEGER, " - + Field.NATIVE_ITEM_ID + " INTEGER, " - + Field.NATIVE_THREAD_ID + " INTEGER, " - + Field.INCOMING + " INTEGER);"); - - writeableDb.execSQL("CREATE INDEX " + TABLE_INDEX_NAME + " ON " + TABLE_NAME + " ( " + Field.TIMESTAMP + " )"); - } - - /** - * Fetches a comma separated list of table fields which can be used in an - * SQL SELECT statement as the query projection. One of the - * {@link #getQueryData} methods can used to fetch data from the cursor. - * - * @return SQL string - */ - private static String getFullQueryList() { - DatabaseHelper.trace(false, "DatabaseHelper.getFullQueryList()"); - - final StringBuffer fullQuery = StringBufferPool.getStringBuffer(); - fullQuery.append(Field.LOCAL_ACTIVITY_ID).append(SqlUtils.COMMA). - append(Field.ACTIVITY_ID).append(SqlUtils.COMMA). - append(Field.TIMESTAMP).append(SqlUtils.COMMA). - append(Field.TYPE).append(SqlUtils.COMMA). - append(Field.URI).append(SqlUtils.COMMA). - append(Field.TITLE).append(SqlUtils.COMMA). - append(Field.DESCRIPTION).append(SqlUtils.COMMA). - append(Field.PREVIEW_URL).append(SqlUtils.COMMA). - append(Field.STORE).append(SqlUtils.COMMA). - append(Field.FLAG).append(SqlUtils.COMMA). - append(Field.PARENT_ACTIVITY).append(SqlUtils.COMMA). - append(Field.HAS_CHILDREN).append(SqlUtils.COMMA). - append(Field.VISIBILITY).append(SqlUtils.COMMA). - append(Field.MORE_INFO).append(SqlUtils.COMMA). - append(Field.CONTACT_ID).append(SqlUtils.COMMA). - append(Field.USER_ID).append(SqlUtils.COMMA). - append(Field.CONTACT_NAME).append(SqlUtils.COMMA). - append(Field.LOCAL_CONTACT_ID).append(SqlUtils.COMMA). - append(Field.CONTACT_NETWORK).append(SqlUtils.COMMA). - append(Field.CONTACT_ADDRESS).append(SqlUtils.COMMA). - append(Field.CONTACT_AVATAR_URL).append(SqlUtils.COMMA). - append(Field.INCOMING); - - return StringBufferPool.toStringThenRelease(fullQuery); - } - - /** - * Fetches activities information from a cursor at the current position. The - * {@link #getFullQueryList()} method should be used to make the query. - * - * @param cursor The cursor returned by the query - * @param activityItem An empty activity object that will be filled with the - * result - * @param activityContact An empty activity contact object that will be - * filled - */ - public static void getQueryData(final Cursor cursor, - final ActivityItem activityItem, - final ActivityContact activityContact) { - DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); - - /** Populate ActivityItem. **/ - activityItem.localActivityId = - SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); - activityItem.activityId = - SqlUtils.setLong(cursor, Field.ACTIVITY_ID.toString(), null); - activityItem.time = - SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); - activityItem.type = - SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); - activityItem.uri = SqlUtils.setString(cursor, Field.URI.toString()); - activityItem.title = - SqlUtils.setString(cursor, Field.TITLE.toString()); - activityItem.description = - SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); - activityItem.previewUrl = - SqlUtils.setString(cursor, Field.PREVIEW_URL.toString()); - activityItem.store = - SqlUtils.setString(cursor, Field.STORE.toString()); - activityItem.activityFlags = - SqlUtils.setInt(cursor, Field.FLAG.toString(), null); - activityItem.parentActivity = - SqlUtils.setLong(cursor, Field.PARENT_ACTIVITY.toString(), null); - activityItem.hasChildren = - SqlUtils.setBoolean(cursor, Field.HAS_CHILDREN.toString(), - activityItem.hasChildren); - activityItem.visibilityFlags = - SqlUtils.setInt(cursor, Field.VISIBILITY.toString(), null); - // TODO: Field MORE_INFO is not used, consider deleting. - - /** Populate ActivityContact. **/ - getQueryData(cursor, activityContact); - } - - /** - * Fetches activities information from a cursor at the current position. The - * {@link #getFullQueryList()} method should be used to make the query. - * - * @param cursor The cursor returned by the query. - * @param activityContact An empty activity contact object that will be - * filled - */ - public static void getQueryData(final Cursor cursor, - final ActivityContact activityContact) { - DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); - - /** Populate ActivityContact. **/ - activityContact.mContactId = - SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); - activityContact.mUserId = - SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); - activityContact.mName = - SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); - activityContact.mLocalContactId = - SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); - activityContact.mNetwork = - SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); - activityContact.mAddress = - SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); - activityContact.mAvatarUrl = - SqlUtils.setString(cursor, Field.CONTACT_AVATAR_URL.toString()); - } - - /*** - * Provides a ContentValues object that can be used to update the table. - * - * @param item The source activity item - * @param contactIdx The index of the contact to use for the update, or null - * to exclude contact specific information. - * @return ContentValues for use in an SQL update or insert. - * @note Items that are NULL will be not modified in the database. - */ - private static ContentValues fillUpdateData(final ActivityItem item, - final Integer contactIdx) { - DatabaseHelper.trace(false, "DatabaseHelper.fillUpdateData()"); - ContentValues activityItemValues = new ContentValues(); - ActivityContact ac = null; - if (contactIdx != null) { - ac = item.contactList.get(contactIdx); - } - - activityItemValues.put(Field.ACTIVITY_ID.toString(), item.activityId); - activityItemValues.put(Field.TIMESTAMP.toString(), item.time); - if (item.type != null) { - activityItemValues.put(Field.TYPE.toString(), - item.type.getTypeCode()); - } - if (item.uri != null) { - activityItemValues.put(Field.URI.toString(), item.uri); - } - /** TODO: Not sure if we need this. **/ - // activityItemValues.put(Field.INCOMING.toString(), false); - - activityItemValues.put(Field.TITLE.toString(), item.title); - activityItemValues.put(Field.DESCRIPTION.toString(), item.description); - if (item.previewUrl != null) { - activityItemValues.put(Field.PREVIEW_URL.toString(), - item.previewUrl); - } - if (item.store != null) { - activityItemValues.put(Field.STORE.toString(), item.store); - } - if (item.activityFlags != null) { - activityItemValues.put(Field.FLAG.toString(), item.activityFlags); - } - if (item.parentActivity != null) { - activityItemValues.put(Field.PARENT_ACTIVITY.toString(), - item.parentActivity); - } - if (item.hasChildren != null) { - activityItemValues.put(Field.HAS_CHILDREN.toString(), - item.hasChildren); - } - if (item.visibilityFlags != null) { - activityItemValues.put(Field.VISIBILITY.toString(), - item.visibilityFlags); - } - if (ac != null) { - activityItemValues.put(Field.CONTACT_ID.toString(), ac.mContactId); - activityItemValues.put(Field.USER_ID.toString(), ac.mUserId); - activityItemValues.put(Field.CONTACT_NAME.toString(), ac.mName); - activityItemValues.put(Field.LOCAL_CONTACT_ID.toString(), - ac.mLocalContactId); - if (ac.mNetwork != null) { - activityItemValues.put(Field.CONTACT_NETWORK.toString(), - ac.mNetwork); - } - if (ac.mAddress != null) { - activityItemValues.put(Field.CONTACT_ADDRESS.toString(), - ac.mAddress); - } - if (ac.mAvatarUrl != null) { - activityItemValues.put(Field.CONTACT_AVATAR_URL.toString(), - ac.mAvatarUrl); - } - } - - return activityItemValues; - } - - /** - * Fetches a list of status items from the given time stamp. - * - * @param timeStamp Time stamp in milliseconds - * @param readableDb Readable SQLite database - * @return A cursor (use one of the {@link #getQueryData} methods to read - * the data) - */ - public static Cursor fetchStatusEventList(final long timeStamp, - final SQLiteDatabase readableDb) { - DatabaseHelper.trace(false, "DatabaseHelper.fetchStatusEventList()"); - return readableDb.rawQuery("SELECT " + getFullQueryList() + " FROM " - + TABLE_NAME + " WHERE (" - + Field.FLAG + " & " + ActivityItem.STATUS_ITEM - + ") AND " + Field.TIMESTAMP + " > " + timeStamp - + " ORDER BY " + Field.TIMESTAMP + " DESC", null); - } - - /** - * Returns a list of activity IDs already synced, in reverse chronological - * order Fetches from the given timestamp. - * - * @param actIdList An empty list which will be filled with the result - * @param timeStamp The time stamp to start the fetch - * @param readableDb Readable SQLite database - * @return SUCCESS or a suitable error code - */ - public static ServiceStatus fetchActivitiesIds(final List<Long> actIdList, - final Long timeStamp, final SQLiteDatabase readableDb) { - DatabaseHelper.trace(false, "DatabaseHelper.fetchActivitiesIds()"); - Cursor cursor = null; - try { - long queryTimeStamp; - if (timeStamp != null) { - queryTimeStamp = timeStamp; - } else { - queryTimeStamp = 0; - } - - cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID - + " FROM " + TABLE_NAME + " WHERE " - + Field.TIMESTAMP + " >= " + queryTimeStamp - + " ORDER BY " + Field.TIMESTAMP + " DESC", null); - while (cursor.moveToNext()) { - actIdList.add(cursor.getLong(0)); - } - - } catch (SQLiteException e) { - LogUtils.logE("ActivitiesTable.fetchActivitiesIds()" - + "Unable to fetch group list", e); - return ServiceStatus.ERROR_DATABASE_CORRUPT; - - } finally { - CloseUtils.close(cursor); - } - return ServiceStatus.SUCCESS; - } - - /** - * Adds a list of activities to table. The activities added will be grouped - * in the database, based on local contact Id, name or contact address (see - * {@link #removeContactGroup(Long, String, Long, int, - * TimelineNativeTypes[], SQLiteDatabase)} - * for more information on how the grouping works. - * - * @param actList The list of activities - * @param writableDb Writable SQLite database - * @return SUCCESS or a suitable error code - */ - public static ServiceStatus addActivities(final List<ActivityItem> actList, - final SQLiteDatabase writableDb) { - DatabaseHelper.trace(true, "DatabaseHelper.addActivities()"); - SQLiteStatement statement = - ContactsTable.fetchLocalFromServerIdStatement(writableDb); - - for (ActivityItem activity : actList) { - try { - writableDb.beginTransaction(); - - if (activity.contactList != null) { - int clistSize = activity.contactList.size(); - for (int i = 0; i < clistSize; i++) { - final ActivityContact activityContact = activity.contactList.get(i); - activityContact.mLocalContactId = - ContactsTable.fetchLocalFromServerId( - activityContact.mContactId, - statement); - - int latestStatusVal = removeContactGroup( - activityContact.mLocalContactId, - activityContact.mName, activity.time, - activity.activityFlags, null, writableDb); - - ContentValues cv = fillUpdateData(activity, i); - cv.put(Field.LATEST_CONTACT_STATUS.toString(), - latestStatusVal); - activity.localActivityId = - writableDb.insertOrThrow(TABLE_NAME, null, cv); - } - } else { - activity.localActivityId = writableDb.insertOrThrow( - TABLE_NAME, null, fillUpdateData(activity, null)); - } - if (activity.localActivityId < 0) { - LogUtils.logE("ActivitiesTable.addActivities() " - + "Unable to add activity"); - return ServiceStatus.ERROR_DATABASE_CORRUPT; - } - writableDb.setTransactionSuccessful(); - } catch (SQLException e) { - LogUtils.logE("ActivitiesTable.addActivities() " - + "Unable to add activity", e); - return ServiceStatus.ERROR_DATABASE_CORRUPT; - } finally { - writableDb.endTransaction(); - } - } - if(statement != null) { - statement.close(); - statement = null; - } - - return ServiceStatus.SUCCESS; - } - - /** - * Deletes all activities from the table. - * - * @param flag Can be a bitmap of: - * <ul> - * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> - * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> - * <li>{@link ActivityItem#ALREADY_READ} - Items that have been - * read</li> - * <li>NULL - to delete all activities</li> - * </ul> - * @param writableDb Writable SQLite database - * @return SUCCESS or a suitable error code - */ - public static ServiceStatus deleteActivities(final Integer flag, - final SQLiteDatabase writableDb) { - DatabaseHelper.trace(true, "DatabaseHelper.deleteActivities()"); - try { - String whereClause = null; - if (flag != null) { - whereClause = Field.FLAG + "&" + flag; - } - if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { - LogUtils.logE("ActivitiesTable.deleteActivities() " - + "Unable to delete activities"); - return ServiceStatus.ERROR_DATABASE_CORRUPT; - } - } catch (SQLException e) { - LogUtils.logE("ActivitiesTable.deleteActivities() " - + "Unable to delete activities", e); - return ServiceStatus.ERROR_DATABASE_CORRUPT; - } - return ServiceStatus.SUCCESS; - } - - public static ServiceStatus fetchNativeIdsFromLocalContactId(List<Integer > nativeItemIdList, final long localContactId, final SQLiteDatabase readableDb) { - DatabaseHelper.trace(false, "DatabaseHelper.fetchNativeIdsFromLocalContactId()"); - Cursor cursor = null; - try { - cursor = readableDb.rawQuery("SELECT " + Field.NATIVE_ITEM_ID - + " FROM " + TABLE_NAME + " WHERE " - + Field.LOCAL_CONTACT_ID + " = " + localContactId, null); - while (cursor.moveToNext()) { - nativeItemIdList.add(cursor.getInt(0)); - } - - } catch (SQLiteException e) { - LogUtils.logE("ActivitiesTable.fetchNativeIdsFromLocalContactId()" - + "Unable to fetch list of NativeIds from localcontactId", e); - return ServiceStatus.ERROR_DATABASE_CORRUPT; - - } finally { - CloseUtils.close(cursor); - } - return ServiceStatus.SUCCESS; - } - - /** - * Deletes specified timeline activity from the table. - * - * @param Context - * @param timelineItem TimelineSummaryItem to be deleted - * @param writableDb Writable SQLite database - * @param readableDb Readable SQLite database - * @return SUCCESS or a suitable error code - */ - public static ServiceStatus deleteTimelineActivity(final Context context, final TimelineSummaryItem timelineItem, - final SQLiteDatabase writableDb, final SQLiteDatabase readableDb) { - DatabaseHelper.trace(true, "DatabaseHelper.deleteTimelineActivity()"); - try { - List<Integer > nativeItemIdList = new ArrayList<Integer>() ; - - //Delete from Native Database - if(timelineItem.mNativeThreadId != null) { - //Sms Native Database - final Uri smsUri = Uri.parse("content://sms"); - context.getContentResolver().delete(smsUri , "thread_id=" + timelineItem.mNativeThreadId, null); - - //Mms Native Database - final Uri mmsUri = Uri.parse("content://mms"); - context.getContentResolver().delete(mmsUri, "thread_id=" + timelineItem.mNativeThreadId, null); - } else { // For CallLogs - if(timelineItem.mLocalContactId != null) { - fetchNativeIdsFromLocalContactId(nativeItemIdList, timelineItem.mLocalContactId, readableDb); - if(nativeItemIdList.size() > 0) { - //CallLog Native Database - for(Integer nativeItemId : nativeItemIdList) { - context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + nativeItemId, null); - } - } - } else { - if(timelineItem.mContactAddress != null) { - context.getContentResolver().delete(Calls.CONTENT_URI, Calls.NUMBER + "=" + timelineItem.mContactAddress, null); - } - } - } - - String whereClause = null; - - //Delete from People Client database - if(timelineItem.mLocalContactId != null) { - if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs - whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " - + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " - + Field.NATIVE_THREAD_ID + " IS NULL;"; - } else { //Delete Sms/MmsLogs - whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " - + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " - + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; - } - } else if(timelineItem.mContactAddress != null) { - if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs - whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " - + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " - + Field.NATIVE_THREAD_ID + " IS NULL;"; - } else { //Delete Sms/MmsLogs - whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " - + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " - + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; - } - } - - if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { - LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " - + "Unable to delete specified activity"); - return ServiceStatus.ERROR_DATABASE_CORRUPT; - } - } catch (SQLException e) { - LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " - + "Unable to delete specified activity", e); - return ServiceStatus.ERROR_DATABASE_CORRUPT; - } - return ServiceStatus.SUCCESS; - } - - /** - * Deletes all the timeline activities for a particular contact from the table. - * - * @param Context - * @param timelineItem TimelineSummaryItem to be deleted - * @param writableDb Writable SQLite database - * @param readableDb Readable SQLite database - * @return SUCCESS or a suitable error code - */ - public static ServiceStatus deleteTimelineActivities(Context context, - TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, - SQLiteDatabase readableDb) { - DatabaseHelper.trace(false, "DatabaseHelper.deleteTimelineActivities()"); - Cursor cursor = null; - try { - TimelineNativeTypes[] typeList = null; - TimelineSummaryItem timelineItem = null; - - //For CallLog Timeline - typeList = new TimelineNativeTypes[] { - TimelineNativeTypes.CallLog - }; - cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, - latestTimelineItem.mContactName, typeList, null, readableDb); - - if(cursor != null && cursor.getCount() > 0) { - cursor.moveToFirst(); - timelineItem = getTimelineData(cursor); - if(timelineItem != null) { - deleteTimelineActivity(context, timelineItem, writableDb, readableDb); - } - } - - //For SmsLog/MmsLog Timeline - typeList = new TimelineNativeTypes[] { - TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog - }; - cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, - latestTimelineItem.mContactName, typeList, null, readableDb); - - if(cursor != null && cursor.getCount() > 0) { - cursor.moveToFirst(); - timelineItem = getTimelineData(cursor); - if(timelineItem != null) { - deleteTimelineActivity(context, timelineItem, writableDb, readableDb); - } - } - - //For ChatLog Timeline - typeList = new TimelineNativeTypes[] { - TimelineNativeTypes.ChatLog - }; - cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, - latestTimelineItem.mContactName, typeList, null, readableDb); - - if(cursor != null && cursor.getCount() > 0) { - cursor.moveToFirst(); - timelineItem = getTimelineData(cursor); - if(timelineItem != null) { - deleteTimelineActivity(context, timelineItem, writableDb, readableDb); - } - } - } catch (SQLException e) { - LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " - + "Unable to delete timeline activities", e); - return ServiceStatus.ERROR_DATABASE_CORRUPT; - } finally { - if(cursor != null) { - CloseUtils.close(cursor); - } - } - - return ServiceStatus.SUCCESS; - } - - /** - * Fetches timeline events grouped by local contact ID, name or contact - * address. Events returned will be in reverse-chronological order. If a - * native type list is provided the result will be filtered by the list. - * - * @param minTimeStamp Only timeline events from this date will be returned - * @param nativeTypes A list of native types to filter the result, or null - * to return all. - * @param readableDb Readable SQLite database - * @return A cursor containing the result. The - * {@link #getTimelineData(Cursor)} method should be used for - * reading the cursor. - */ - public static Cursor fetchTimelineEventList(final Long minTimeStamp, - final TimelineNativeTypes[] nativeTypes, - final SQLiteDatabase readableDb) { - DatabaseHelper.trace(false, "DatabaseHelper.fetchTimelineEventList() " - + "minTimeStamp[" + minTimeStamp + "]"); - try { - int andVal = 1; - String typesQuery = " AND "; - if (nativeTypes != null) { - typesQuery += DatabaseHelper.createWhereClauseFromList( - Field.NATIVE_ITEM_TYPE.toString(), nativeTypes, "OR"); - typesQuery += " AND "; - andVal = 2; - } - - String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," - + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," - + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," - + Field.TITLE + "," + Field.DESCRIPTION + "," - + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," - + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," - + Field.CONTACT_ID + "," + Field.USER_ID + "," - + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," - + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" - + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" - + typesQuery + Field.TIMESTAMP + " > " + minTimeStamp - + " AND (" - + Field.LATEST_CONTACT_STATUS + " & " + andVal - + ") ORDER BY " + Field.TIMESTAMP + " DESC"; - return readableDb.rawQuery(query, null); - } catch (SQLiteException e) { - LogUtils.logE("ActivitiesTable.fetchLastUpdateTime() " - + "Unable to fetch timeline event list", e); - return null; - } - } - - /** - * Adds a list of timeline events to the database. Each event is grouped by - * contact and grouped by contact + native type. - * - * @param itemList List of timeline events - * @param isCallLog true to group all activities with call logs, false to - * group with messaging - * @param writableDb Writable SQLite database - * @return SUCCESS or a suitable error - */ - public static ServiceStatus addTimelineEvents( - final ArrayList<TimelineSummaryItem> itemList, - final boolean isCallLog, final SQLiteDatabase writableDb) { - DatabaseHelper.trace(true, "DatabaseHelper.addTimelineEvents()"); - TimelineNativeTypes[] activityTypes; - if (isCallLog) { - activityTypes = new TimelineNativeTypes[] { - TimelineNativeTypes.CallLog - }; - } else { - activityTypes = new TimelineNativeTypes[] { - TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog - }; - } - - for (TimelineSummaryItem item : itemList) { - try { - writableDb.beginTransaction(); - - if (findNativeActivity(item, writableDb)) { - continue; - } - int latestStatusVal = 0; - if (item.mContactName != null || item.mLocalContactId != null) { - latestStatusVal |= removeContactGroup(item.mLocalContactId, - item.mContactName, item.mTimestamp, - ActivityItem.TIMELINE_ITEM, null, writableDb); - latestStatusVal |= removeContactGroup(item.mLocalContactId, - item.mContactName, item.mTimestamp, - ActivityItem.TIMELINE_ITEM, activityTypes, - writableDb); - } - ContentValues values = new ContentValues(); - values.put(Field.CONTACT_NAME.toString(), item.mContactName); - values.put(Field.CONTACT_ID.toString(), item.mContactId); - values.put(Field.USER_ID.toString(), item.mUserId); - values.put(Field.LOCAL_CONTACT_ID.toString(), - item.mLocalContactId); - values.put(Field.CONTACT_NETWORK.toString(), - item.mContactNetwork); - values.put(Field.DESCRIPTION.toString(), item.mDescription); - values.put(Field.TITLE.toString(), item.mTitle); - values.put(Field.CONTACT_ADDRESS.toString(), - item.mContactAddress); - values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM); - values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); - values.put(Field.NATIVE_ITEM_TYPE.toString(), - item.mNativeItemType); - values.put(Field.TIMESTAMP.toString(), item.mTimestamp); - if (item.mType != null) { - values.put(Field.TYPE.toString(), - item.mType.getTypeCode()); - } - values.put(Field.LATEST_CONTACT_STATUS.toString(), - latestStatusVal); - values.put(Field.NATIVE_THREAD_ID.toString(), - item.mNativeThreadId); - if (item.mIncoming != null) { - values.put(Field.INCOMING.toString(), - item.mIncoming.ordinal()); - } - - item.mLocalActivityId = - writableDb.insert(TABLE_NAME, null, values); - if (item.mLocalActivityId < 0) { - LogUtils.logE("ActivitiesTable.addTimelineEvents() " - + "ERROR_DATABASE_CORRUPT - Unable to add " - + "timeline list to database"); - return ServiceStatus.ERROR_DATABASE_CORRUPT; - } - - writableDb.setTransactionSuccessful(); - } catch (SQLException e) { - LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " - + "Unable to add timeline list to database", e); - return ServiceStatus.ERROR_DATABASE_CORRUPT; - } finally { - writableDb.endTransaction(); - } - } - - return ServiceStatus.SUCCESS; - } - - - /** - * The method returns the ROW_ID i.e. the INTEGER PRIMARY KEY AUTOINCREMENT - * field value for the inserted row, i.e. LOCAL_ID. - * - * @param item TimelineSummaryItem. - * @param read - TRUE if the chat message is outgoing or gets into the - * timeline history view for a contact with LocalContactId. - * @param writableDb Writable SQLite database. - * @return LocalContactID or -1 if the row was not inserted. - */ - public static long addChatTimelineEvent(final TimelineSummaryItem item, - final boolean read, final SQLiteDatabase writableDb) { - DatabaseHelper.trace(true, "DatabaseHelper.addChatTimelineEvent()"); - - try { - - writableDb.beginTransaction(); - - int latestStatusVal = 0; - if (item.mContactName != null || item.mLocalContactId != null) { - latestStatusVal |= removeContactGroup(item.mLocalContactId, - item.mContactName, item.mTimestamp, - ActivityItem.TIMELINE_ITEM, null, writableDb); - latestStatusVal |= removeContactGroup(item.mLocalContactId, - item.mContactName, item.mTimestamp, - ActivityItem.TIMELINE_ITEM, new TimelineNativeTypes[] { - TimelineNativeTypes.ChatLog - }, writableDb); - } - ContentValues values = new ContentValues(); - values.put(Field.CONTACT_NAME.toString(), item.mContactName); - values.put(Field.CONTACT_ID.toString(), item.mContactId); - values.put(Field.USER_ID.toString(), item.mUserId); - values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); - values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); - values.put(Field.DESCRIPTION.toString(), item.mDescription); - /** Chat message body. **/ - values.put(Field.TITLE.toString(), item.mTitle); - values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); - if (read) { - values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM - | ActivityItem.ALREADY_READ); - } else { - values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM - | 0); - } - values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); - values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); - values.put(Field.TIMESTAMP.toString(), item.mTimestamp); - if (item.mType != null) { - values.put(Field.TYPE.toString(), item.mType.getTypeCode()); - } - - values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); - values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); - /** Conversation ID for chat message. **/ - // values.put(Field.URI.toString(), item.conversationId); - // 0 for incoming, 1 for outgoing - if (item.mIncoming != null) { - values.put(Field.INCOMING.toString(), - item.mIncoming.ordinal()); - } - - final long itemId = writableDb.insert(TABLE_NAME, null, values); - if (itemId < 0) { - LogUtils.logE("ActivitiesTable.addTimelineEvents() - " - + "Unable to add timeline list to database, index<0:" - + itemId); - return -1; - } - writableDb.setTransactionSuccessful(); - return itemId; - - } catch (SQLException e) { - LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " - + "Unable to add timeline list to database", e); - return -1; - - } finally { - writableDb.endTransaction(); - } - } - - /** - * Clears the grouping of an activity in the database, if the given activity - * is newer. This is so that only the latest activity is returned for a - * particular group. Each activity is associated with two groups: - * <ol> - * <li>All group - Grouped by contact only</li> - * <li>Native group - Grouped by contact and native type (call log or - * messaging)</li> - * </ol> - * The group to be removed is determined by the activityTypes parameter. - * Grouping must also work for timeline events that are not associated with - * a contact. The following fields are used to do identify a contact for the - * grouping (in order of priority): - * <ol> - * <li>localContactId - If it not null</li> - * <li>name - If this is a valid telephone number, the match will be done to - * ensure that the same phone number written in different ways will be - * included in the group. See {@link #fetchNameWhereClause(Long, String)} - * for more information.</li> - * </ol> - * - * @param localContactId Local contact Id or NULL if the activity is not - * associated with a contact. - * @param name Name of contact or contact address (telephone number, email, - * etc). - * @param newUpdateTime The time that the given activity has occurred - * @param flag Bitmap of types including: - * <ul> - * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> - * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> - * <li>{@link ActivityItem#ALREADY_READ} - Items that have been - * read</li> - * </ul> - * @param activityTypes A list of native types to include in the grouping. - * Currently, only two groups are supported (see above). If this - * parameter is null the contact will be added to the - * "all group", otherwise the contact is added to the native - * group. - * @param writableDb Writable SQLite database - * @return The latest contact status value which should be added to the - * current activities grouping. - */ - private static int removeContactGroup(final Long localContactId, - final String name, final Long newUpdateTime, final int flag, - final TimelineNativeTypes[] activityTypes, - final SQLiteDatabase writableDb) { - String whereClause = ""; - int andVal = 1; - if (activityTypes != null) { - whereClause = DatabaseHelper.createWhereClauseFromList( - Field.NATIVE_ITEM_TYPE.toString(), activityTypes, "OR"); - whereClause += " AND "; - andVal = 2; - } - - String nameWhereClause = fetchNameWhereClause(localContactId, name); - - if (nameWhereClause == null) { - return 0; - } - whereClause += nameWhereClause; - Long prevTime = null; - Long prevLocalId = null; - Integer prevLatestContactStatus = null; - Cursor cursor = null; - try { - cursor = writableDb.rawQuery("SELECT " + Field.TIMESTAMP + "," - + Field.LOCAL_ACTIVITY_ID + "," - + Field.LATEST_CONTACT_STATUS + " FROM " + TABLE_NAME - + " WHERE " + whereClause - + " AND " - + "(" + Field.LATEST_CONTACT_STATUS + " & " + andVal - + ") AND (" - + Field.FLAG + "&" + flag - + ") ORDER BY " + Field.TIMESTAMP + " DESC", null); - if (cursor.moveToFirst()) { - prevTime = cursor.getLong(0); - prevLocalId = cursor.getLong(1); - prevLatestContactStatus = cursor.getInt(2); - } - } catch (SQLException e) { - return 0; - - } finally { - CloseUtils.close(cursor); - } - if (prevTime != null && newUpdateTime != null) { - if (newUpdateTime >= prevTime) { - ContentValues cv = new ContentValues(); - cv.put(Field.LATEST_CONTACT_STATUS.toString(), - prevLatestContactStatus & (~andVal)); - if (writableDb.update(TABLE_NAME, cv, Field.LOCAL_ACTIVITY_ID - + "=" + prevLocalId, null) <= 0) { - LogUtils.logE("ActivitiesTable.addTimelineEvents() " - + "Unable to update timeline as the latest"); - return 0; - } - return andVal; - } else { - return 0; - } - } - return andVal; - } - - /** - * Checks if an activity exists in the database. - * - * @param item The native SMS item to check against our client activities DB table. - * - * @return true if the activity was found, false otherwise - * - */ - private static boolean findNativeActivity(TimelineSummaryItem item, final SQLiteDatabase readableDb) { - DatabaseHelper.trace(false, "DatabaseHelper.findNativeActivity()"); - Cursor cursor = null; - boolean result = false; - try { - final String[] args = { - Integer.toString(item.mNativeItemId), Integer.toString(item.mNativeItemType), Long.toString(item.mTimestamp) - }; - cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + - " WHERE " + Field.NATIVE_ITEM_ID + "=? AND " + Field.NATIVE_ITEM_TYPE + "=?" + - " AND " + Field.TIMESTAMP + "=?", args); - if (cursor.moveToFirst()) { - result = true; - } - } finally { - CloseUtils.close(cursor); - } - return result; - } - - /** - * Returns a string which can be added to the where clause in an SQL query - * on the activities table, to filter the result for a specific contact or - * name. The clause will prioritise in the following way: - * <ol> - * <li>Use localContactId - If it not null</li> - * <li>Use name - If this is a valid telephone number, the match will be - * done to ensure that the same phone number written in different ways will - * be included in the group. - * </ol> - * - * @param localContactId The local contact ID, or null if the contact does - * not exist in the People database. - * @param name A string containing the name, or a telephone number/email - * identifying the contact. - * @return The where clause string - */ - private static String fetchNameWhereClause(final Long localContactId, - final String name) { - DatabaseHelper.trace(false, "DatabaseHelper.fetchNameWhereClause()"); - if (localContactId != null) { - return Field.LOCAL_CONTACT_ID + "=" + localContactId; - } - - if (name == null) { - return null; - } - final String searchName = DatabaseUtils.sqlEscapeString(name); - if (PhoneNumberUtils.isWellFormedSmsAddress(name)) { - return "(PHONE_NUMBERS_EQUAL(" + Field.CONTACT_NAME + "," - + searchName + ") OR "+ Field.CONTACT_NAME + "=" - + searchName+")"; - } else { - return Field.CONTACT_NAME + "=" + searchName; - } - } - - - /** - * Returns the timeline summary data from the current location of the given - * cursor. The cursor can be obtained using - * {@link #fetchTimelineEventList(Long, TimelineNativeTypes[], - * SQLiteDatabase)} or - * {@link #fetchTimelineEventsForContact(Long, Long, String, - * TimelineNativeTypes[], SQLiteDatabase)}. - * - * @param cursor Cursor in the required position. - * @return A filled out TimelineSummaryItem object - */ - public static TimelineSummaryItem getTimelineData(final Cursor cursor) { - DatabaseHelper.trace(false, "DatabaseHelper.getTimelineData()"); - TimelineSummaryItem item = new TimelineSummaryItem(); - item.mLocalActivityId = - SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); - item.mTimestamp = - SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); - item.mContactName = - SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); - if (!cursor.isNull( - cursor.getColumnIndex(Field.CONTACT_AVATAR_URL.toString()))) { - item.mHasAvatar = true; - } - item.mLocalContactId = - SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); - item.mTitle = SqlUtils.setString(cursor, Field.TITLE.toString()); - item.mDescription = - SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); - item.mContactNetwork = - SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); - item.mNativeItemType = - SqlUtils.setInt(cursor, Field.NATIVE_ITEM_TYPE.toString(), null); - item.mNativeItemId = - SqlUtils.setInt(cursor, Field.NATIVE_ITEM_ID.toString(), null); - item.mType = - SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); - item.mContactId = - SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); - item.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); - item.mNativeThreadId = - SqlUtils.setInt(cursor, Field.NATIVE_THREAD_ID.toString(), null); - item.mContactAddress = - SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); - item.mIncoming = SqlUtils.setTimelineSummaryItemType(cursor, - Field.INCOMING.toString()); - return item; - } - - /** - * Fetches timeline events for a specific contact identified by local - * contact ID, name or address. Events returned will be in - * reverse-chronological order. If a native type list is provided the result - * will be filtered by the list. - * - * @param timeStamp Only events from this time will be returned - * @param localContactId The local contact ID if the contact is in the - * People database, or null. - * @param name The name or address of the contact (required if local contact - * ID is NULL). - * @param nativeTypes A list of required native types to filter the result, - * or null to return all timeline events for the contact. - * @param readableDb Readable SQLite database - * @param networkName The name of the network the contacts belongs to - * (required in order to provide appropriate chat messages - * filtering) If the parameter is null messages from all networks - * will be returned. The values are the - * SocialNetwork.VODAFONE.toString(), - * SocialNetwork.GOOGLE.toString(), or - * SocialNetwork.MICROSOFT.toString() results. - * @return The cursor that can be read using - * {@link #getTimelineData(Cursor)}. - */ - public static Cursor fetchTimelineEventsForContact(final Long timeStamp, - final Long localContactId, final String name, - final TimelineNativeTypes[] nativeTypes, final String networkName, - final SQLiteDatabase readableDb) { - DatabaseHelper.trace(false, "DatabaseHelper." - + "fetchTimelineEventsForContact()"); - try { - String typesQuery = " AND "; - if (nativeTypes.length > 0) { - StringBuffer typesQueryBuffer = new StringBuffer(); - typesQueryBuffer.append(" AND ("); - for (int i = 0; i < nativeTypes.length; i++) { - final TimelineNativeTypes type = nativeTypes[i]; - typesQueryBuffer.append(Field.NATIVE_ITEM_TYPE - + "=" + type.ordinal()); - if (i < nativeTypes.length - 1) { - typesQueryBuffer.append(" OR "); - } - } - typesQueryBuffer.append(") AND "); - typesQuery = typesQueryBuffer.toString(); - } - - /** Filter by account. **/ - String networkQuery = ""; - String queryNetworkName = networkName; - if (queryNetworkName != null) { - if (queryNetworkName.equals(SocialNetwork.PC.toString()) - || queryNetworkName.equals( - SocialNetwork.MOBILE.toString())) { - queryNetworkName = SocialNetwork.VODAFONE.toString(); - } - networkQuery = Field.CONTACT_NETWORK + "='" + queryNetworkName - + "' AND "; - } - - String whereAppend; - if (localContactId == null) { - whereAppend = Field.LOCAL_CONTACT_ID + " IS NULL AND " - + fetchNameWhereClause(localContactId, name); - if (whereAppend == null) { - return null; - } - } else { - whereAppend = Field.LOCAL_CONTACT_ID + "=" + localContactId; - } - String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," - + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," - + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," - + Field.TITLE + "," + Field.DESCRIPTION + "," - + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," - + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," - + Field.CONTACT_ID + "," + Field.USER_ID + "," - + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," - + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" - + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" - + typesQuery + networkQuery + whereAppend - + " ORDER BY " + Field.TIMESTAMP + " ASC"; - return readableDb.rawQuery(query, null); - } catch (SQLiteException e) { - LogUtils.logE("ActivitiesTable.fetchTimelineEventsForContact() " - + "Unable to fetch timeline event for contact list", e); - return null; - } - } - - /** - * Mark the chat timeline events for a given contact as read. - * - * @param localContactId Local contact ID. - * @param networkName Name of the SNS. - * @param writableDb Writable SQLite reference. - * @return Number of rows affected by database update. - */ - public static int markChatTimelineEventsForContactAsRead( - final Long localContactId, final String networkName, - final SQLiteDatabase writableDb) { - DatabaseHelper.trace(false, "DatabaseHelper." - + "fetchTimelineEventsForContact()"); - ContentValues values = new ContentValues(); - values.put(Field.FLAG.toString(), - ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); - - String networkQuery = ""; - if (networkName != null) { - networkQuery = " AND (" + Field.CONTACT_NETWORK + "='" - + networkName + "')"; - } - - final String where = Field.LOCAL_CONTACT_ID + "=" + localContactId - + " AND " + Field.NATIVE_ITEM_TYPE + "=" - + TimelineNativeTypes.ChatLog.ordinal() + " AND (" - /** - * If the network is null, set all messages as read for this - * contact. - */ - + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")" - + networkQuery; - - return writableDb.update(TABLE_NAME, values, where, null); - } - - /** - * Returns the latest status event for a contact with the given local contact id. - * - * @param local contact id Server contact ID. - * @param readableDb Readable SQLite database. - * @return The ActivityItem representing the latest status event for given local contact id, - * or null if nothing was found. - */ - public static ActivityItem getLatestStatusForContact(final long localContactId, - final SQLiteDatabase readableDb) { - DatabaseHelper.trace(false, "DatabaseHelper getLatestStatusForContact"); - Cursor cursor = null; - try { - StringBuffer query = StringBufferPool.getStringBuffer(SQLKeys.SELECT); - query.append(getFullQueryList()).append(SQLKeys.FROM).append(TABLE_NAME).append(SQLKeys.WHERE). - append(Field.FLAG).append('&').append(ActivityItem.STATUS_ITEM).append(SQLKeys.AND). - append(Field.LOCAL_CONTACT_ID).append('=').append(localContactId). - append(" ORDER BY ").append(Field.TIMESTAMP).append(" DESC"); - - cursor = readableDb.rawQuery(StringBufferPool.toStringThenRelease(query), null); - if (cursor.moveToFirst()) { - final ActivityItem activityItem = new ActivityItem(); - final ActivityContact activityContact = new ActivityContact(); - ActivitiesTable.getQueryData(cursor, activityItem, activityContact); - return activityItem; - } - } finally { - CloseUtils.close(cursor); - cursor = null; - } - return null; - } - - /** - * Updates timeline when a new contact is added to the People database. - * Updates all timeline events that are not associated with a contact and - * have a phone number that matches the oldName parameter. - * - * @param oldName The telephone number (since is the name of an activity - * that is not associated with a contact) - * @param newName The new name - * @param newLocalContactId The local Contact Id for the added contact. - * @param newContactId The server Contact Id for the added contact (or null - * if the contact has not yet been synced). - * @param witeableDb Writable SQLite database - */ - public static void updateTimelineContactNameAndId(final String oldName, - final String newName, final Long newLocalContactId, - final Long newContactId, final SQLiteDatabase witeableDb) { - DatabaseHelper.trace(false, "DatabaseHelper." - + "updateTimelineContactNameAndId()"); - - try { - ContentValues values = new ContentValues(); - if (newName != null) { - values.put(Field.CONTACT_NAME.toString(), newName); - } else { - LogUtils.logE("updateTimelineContactNameAndId() " - + "newName should never be null"); - } - if (newLocalContactId != null) { - values.put(Field.LOCAL_CONTACT_ID.toString(), - newLocalContactId); - } else { - LogUtils.logE("updateTimelineContactNameAndId() " - + "newLocalContactId should never be null"); - } - if (newContactId != null) { - values.put(Field.CONTACT_ID.toString(), newContactId); - } else { - /** - * newContactId will be null if adding a contact from the UI. - */ - LogUtils.logI("updateTimelineContactNameAndId() " - + "newContactId is null"); - /** - * We haven't got server Contact it, it means it haven't been - * synced yet. - */ - } - - String name = ""; - if (oldName != null) { - name = oldName; - LogUtils.logW("ActivitiesTable." - + "updateTimelineContactNameAndId() oldName is NULL"); - } - String[] args = { - "2", name - }; - - String whereClause = Field.LOCAL_CONTACT_ID + " IS NULL AND " - + Field.FLAG + "=? AND PHONE_NUMBERS_EQUAL(" - + Field.CONTACT_ADDRESS + ",?)"; - witeableDb.update(TABLE_NAME, values, whereClause, args); - - } catch (SQLException e) { - LogUtils.logE("ActivitiesTable.updateTimelineContactNameAndId() " - + "Unable update table", e); - throw e; - } - } - - /** - * Updates the timeline when a contact name is modified in the database. - * - * @param newName The new name. - * @param localContactId Local contact Id which was modified. - * @param witeableDb Writable SQLite database - */ - public static void updateTimelineContactNameAndId(final String newName, - final Long localContactId, final SQLiteDatabase witeableDb) { - DatabaseHelper.trace(false, "DatabaseHelper." - + "updateTimelineContactNameAndId()"); - if (newName == null || localContactId == null) { - LogUtils.logE("updateTimelineContactNameAndId() newName or " - + "localContactId == null newName(" + newName - + ") localContactId(" + localContactId + ")"); - return; - } - - try { - ContentValues values = new ContentValues(); - Long cId = ContactsTable.fetchServerId(localContactId, witeableDb); - values.put(Field.CONTACT_NAME.toString(), newName); - if (cId != null) { - values.put(Field.CONTACT_ID.toString(), cId); - } - String[] args = { - localContactId.toString() - }; - String whereClause = Field.LOCAL_CONTACT_ID + "=?"; - witeableDb.update(TABLE_NAME, values, whereClause, args); - - } catch (SQLException e) { - LogUtils.logE("ActivitiesTable.updateTimelineContactNameAndId()" - + " Unable update table", e); - } - } - - /** - * Updates the timeline entries in the activities table to remove deleted - * contact info. - * - * @param localContactId - the contact id that has been deleted - * @param writeableDb - reference to the database - */ - public static void removeTimelineContactData(final Long localContactId, - final SQLiteDatabase writeableDb) { - DatabaseHelper.trace(false, "DatabaseHelper." - + "removeTimelineContactData()"); - if (localContactId == null) { - LogUtils.logE("removeTimelineContactData() localContactId == null " - + "localContactId(" + localContactId + ")"); - return; - } - try { - //Remove all the Chat Entries - removeChatTimelineForContact(localContactId, writeableDb); - - String[] args = { - localContactId.toString() - }; - String query = "UPDATE " - + TABLE_NAME - + " SET " - + Field.LOCAL_CONTACT_ID + "=NULL, " - + Field.CONTACT_ID + "=NULL, " + Field.CONTACT_NAME + "=" - + Field.CONTACT_ADDRESS + " WHERE " - + Field.LOCAL_CONTACT_ID + "=? AND (" - + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")"; - writeableDb.execSQL(query, args); - } catch (SQLException e) { - LogUtils.logE("ActivitiesTable.removeTimelineContactData() Unable " - + "to update table: \n", e); - } - } - - /** - * Removes all the items from the chat timeline for the given contact. - * - * @param localContactId Given contact ID. - * @param writeableDb Writable SQLite database. - */ - private static void removeChatTimelineForContact( - final Long localContactId, final SQLiteDatabase writeableDb) { - DatabaseHelper.trace(false, "DatabaseHelper." - + "removeChatTimelineForContact()"); - if (localContactId == null || (localContactId == -1)) { - LogUtils.logE("removeChatTimelineForContact() localContactId == " - + "null " + "localContactId(" + localContactId + ")"); - return; - } - final String query = Field.LOCAL_CONTACT_ID + "=" + localContactId - + " AND (" + Field.NATIVE_ITEM_TYPE + "=" - + TimelineNativeTypes.ChatLog.ordinal() + ")"; - try { - writeableDb.delete(TABLE_NAME, query, null); - } catch (SQLException e) { - LogUtils.logE("ActivitiesTable.removeChatTimelineForContact() " - + "Unable to update table", e); - } - } - - /** - * Removes items from the chat timeline that are not for the given contact. - * - * @param localContactId Given contact ID. - * @param writeableDb Writable SQLite database. - */ - public static void removeChatTimelineExceptForContact( - final Long localContactId, final SQLiteDatabase writeableDb) { - DatabaseHelper.trace(false, "DatabaseHelper." - + "removeTimelineContactData()"); - if (localContactId == null || (localContactId == -1)) { - LogUtils.logE("removeTimelineContactData() localContactId == null " - + "localContactId(" + localContactId + ")"); - return; - } - try { - final long olderThan = System.currentTimeMillis() - - Settings.HISTORY_IS_WEEK_LONG; - final String query = Field.LOCAL_CONTACT_ID + "!=" + localContactId - + " AND (" + Field.NATIVE_ITEM_TYPE + "=" - + TimelineNativeTypes.ChatLog.ordinal() + ") AND (" - + Field.TIMESTAMP + "<" + olderThan + ")"; - writeableDb.delete(TABLE_NAME, query, null); - } catch (SQLException e) { - LogUtils.logE("ActivitiesTable.removeTimelineContactData() " - + "Unable to update table", e); - } - } - - /*** - * Returns the number of users have currently have unread chat messages. - * - * @param readableDb Reference to a readable database. - * @return Number of users with unread chat messages. - */ - public static int getNumberOfUnreadChatUsers( - final SQLiteDatabase readableDb) { - final String query = "SELECT " + Field.LOCAL_CONTACT_ID + " FROM " - + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" - + TimelineNativeTypes.ChatLog.ordinal() + " AND (" - /** - * This condition below means the timeline is not yet marked - * as READ. - */ - + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; - Cursor cursor = null; - try { - cursor = readableDb.rawQuery(query, null); - ArrayList<Long> ids = new ArrayList<Long>(); - Long id = null; - while (cursor.moveToNext()) { - id = cursor.getLong(0); - if (!ids.contains(id)) { - ids.add(id); - } - } - return ids.size(); - - } finally { - CloseUtils.close(cursor); - } - } - - /*** - * Returns the number of unread chat messages. - * - * @param readableDb Reference to a readable database. - * @return Number of unread chat messages. - */ - public static int getNumberOfUnreadChatMessages( - final SQLiteDatabase readableDb) { - final String query = "SELECT " + Field.ACTIVITY_ID + " FROM " - + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" - + TimelineNativeTypes.ChatLog.ordinal() + " AND (" - + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; - Cursor cursor = null; - try { - cursor = readableDb.rawQuery(query, null); - return cursor.getCount(); - - } finally { - CloseUtils.close(cursor); - } - } - - /*** - * Returns the number of unread chat messages for this contact besides this - * network. - * - * @param localContactId Given contact ID. - * @param network SNS name. - * @param readableDb Reference to a readable database. - * @return Number of unread chat messages. - */ - public static int getNumberOfUnreadChatMessagesForContactAndNetwork( - final long localContactId, final String network, - final SQLiteDatabase readableDb) { - final String query = "SELECT " + Field.ACTIVITY_ID + " FROM " - + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" - + TimelineNativeTypes.ChatLog.ordinal() + " AND (" + Field.FLAG - + "=" + ActivityItem.TIMELINE_ITEM + ") AND (" - + Field.LOCAL_CONTACT_ID + "=" + localContactId + ") AND (" - + Field.CONTACT_NETWORK + "!=\"" + network + "\")"; - Cursor cursor = null; - try { - cursor = readableDb.rawQuery(query, null); - return cursor.getCount(); - - } finally { - CloseUtils.close(cursor); - } - } - - /*** - * Returns the newest unread chat message. - * - * @param readableDb Reference to a readable database. - * @return TimelineSummaryItem of the newest unread chat message, or NULL if - * none are found. - */ - public static TimelineSummaryItem getNewestUnreadChatMessage( - final SQLiteDatabase readableDb) { - - final String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," - + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," - + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," - + Field.TITLE + "," + Field.DESCRIPTION + "," - + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," - + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," - + Field.CONTACT_ID + "," + Field.USER_ID + "," - + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," - + Field.INCOMING - + " FROM " + TABLE_NAME + " WHERE " - + Field.NATIVE_ITEM_TYPE + "=" - + TimelineNativeTypes.ChatLog.ordinal() - + " AND (" + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; - Cursor cursor = null; - try { - cursor = readableDb.rawQuery(query, null); - long max = 0; - long time = 0; - int index = -1; - while (cursor.moveToNext()) { - time = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), - -1L); - if (time > max) { - max = time; - index = cursor.getPosition(); - } - } - if (index != -1) { - cursor.moveToPosition(index); - return getTimelineData(cursor); - } else { - return null; - } - - } finally { - CloseUtils.close(cursor); - } - } - - /*** - * Cleanup the Activity Table by deleting anything older than - * CLEANUP_MAX_AGE_DAYS, or preventing the total size from exceeding - * CLEANUP_MAX_QUANTITY. - * - * @param writableDb Reference to a writable SQLite Database. - */ - public static void cleanupActivityTable(final SQLiteDatabase writableDb) { - DatabaseHelper.trace(true, "DatabaseHelper.cleanupActivityTable()"); - try { - /* - * Delete any Activities older than CLEANUP_MAX_AGE_DAYS days. - */ - if (CLEANUP_MAX_AGE_DAYS != -1) { - if (writableDb.delete(TABLE_NAME, Field.TIMESTAMP + " < " - + ((System.currentTimeMillis() - / NUMBER_OF_MS_IN_A_SECOND) - - CLEANUP_MAX_AGE_DAYS * NUMBER_OF_MS_IN_A_DAY), - null) < 0) { - LogUtils.logE("ActivitiesTable.cleanupActivityTable() " - + "Unable to cleanup Activities table by date"); - } - } - /* - * Delete oldest Activities, when total number of rows exceeds - * CLEANUP_MAX_QUANTITY in quantity. - */ - if (CLEANUP_MAX_QUANTITY != -1) { - writableDb.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " - + Field.LOCAL_ACTIVITY_ID + " IN (SELECT " - + Field.LOCAL_ACTIVITY_ID + " FROM " + TABLE_NAME - + " ORDER BY " + Field.TIMESTAMP - + " DESC LIMIT -1 OFFSET " + CLEANUP_MAX_QUANTITY - + ")"); - } - } catch (SQLException e) { - LogUtils.logE("ActivitiesTable.cleanupActivityTable() " - + "Unable to cleanup Activities table by date", e); - } - } - - /** - * Returns the TimelineSummaryItem for the corresponding native thread Id. - * - * @param threadId native thread id - * @param readableDb Readable SQLite database - * @return The TimelineSummaryItem of the matching native thread id, - * or NULL if none are found. - */ - public static TimelineSummaryItem fetchTimeLineDataFromNativeThreadId( - final String threadId, - final SQLiteDatabase readableDb) { - DatabaseHelper.trace(false, "DatabaseHelper." - + "fetchTimeLineDataFromNativeThreadId()"); - Cursor cursor = null; - - try { - String query = "SELECT * FROM " + TABLE_NAME + " WHERE " - + Field.NATIVE_THREAD_ID + " = " + threadId + " ORDER BY " - + Field.TIMESTAMP + " DESC"; - - cursor = readableDb.rawQuery(query, null); - if (cursor != null && cursor.moveToFirst() && !cursor.isNull(0)) { - return getTimelineData(cursor); - } else { - return null; - } - } finally { - CloseUtils.close(cursor); - } - } - - /** - * This method deletes the timeline event for the contact by timestamp. - * - * @param localContactId Given contact ID. - * @param the time of the event. - * @param writeableDb Writable SQLite database. - */ - public static void deleteUnsentChatMessageForContact( - final Long localContactId, long timestamp, final SQLiteDatabase writeableDb) { - DatabaseHelper.trace(false, "ActivitiesTable deleteUnsentChatMessageForContact()"); - if (localContactId == null || (localContactId == -1)) { - LogUtils.logE("deleteUnsentChatMessageForContact() localContactId == " - + "null " + "localContactId(" + localContactId + ")"); - return; - } - StringBuffer where1 = StringBufferPool.getStringBuffer(Field.LOCAL_CONTACT_ID.toString()); - where1.append("=").append(localContactId).append(" AND (").append(Field.NATIVE_ITEM_TYPE.toString()).append("=") - .append(TimelineNativeTypes.ChatLog.ordinal()).append(") AND (").append(Field.TIMESTAMP).append("=") - .append(timestamp).append(") AND (").append(Field.INCOMING).append("=") - .append(TimelineSummaryItem.Type.OUTGOING.ordinal()).append(")"); - - if (writeableDb.delete(TABLE_NAME, StringBufferPool.toStringThenRelease(where1), null) > 0) { - StringBuffer where2 = StringBufferPool.getStringBuffer(Field.LOCAL_ACTIVITY_ID.toString()); - where2.append(" IN (SELECT ").append(Field.LOCAL_ACTIVITY_ID.toString()).append(" FROM ").append(TABLE_NAME) - .append(" WHERE ").append(Field.LOCAL_CONTACT_ID.toString()).append("=").append(localContactId).append(" AND ") - .append(Field.NATIVE_ITEM_TYPE).append(" IN (").append(TimelineNativeTypes.CallLog.ordinal()).append(",") - .append(TimelineNativeTypes.SmsLog.ordinal()).append(",").append(TimelineNativeTypes.MmsLog.ordinal()) - .append(",").append(TimelineNativeTypes.ChatLog.ordinal()).append(") ORDER BY ").append(Field.TIMESTAMP).append(" DESC LIMIT 1)"); - ContentValues values = new ContentValues(); - //this value marks the timeline as the latest event for this contact. this value is normally set in addTimeline - //methods for the added event after resetting previous latest activities. - final int LATEST_TIMELINE = 3; - values.put(Field.LATEST_CONTACT_STATUS.toString(), LATEST_TIMELINE); - writeableDb.update(TABLE_NAME, values, StringBufferPool.toStringThenRelease(where2), null); - } - } - +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the Common Development + * and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at + * src/com/vodafone360/people/VODAFONE.LICENSE.txt or + * http://github.com/360/360-Engine-for-Android + * See the License for the specific language governing permissions and + * limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each file and + * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. + * If applicable, add the following below this CDDL HEADER, with the fields + * enclosed by brackets "[]" replaced with your own identifying information: + * Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + * + * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. + * Use is subject to license terms. + */ + +package com.vodafone360.people.database.tables; + +import java.util.ArrayList; +import java.util.List; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.DatabaseUtils; +import android.database.SQLException; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteException; +import android.database.sqlite.SQLiteStatement; +import android.net.Uri; +import android.provider.CallLog.Calls; +import android.telephony.PhoneNumberUtils; + +import com.vodafone360.people.Settings; +import com.vodafone360.people.database.DatabaseHelper; +import com.vodafone360.people.database.SQLKeys; +import com.vodafone360.people.database.utils.SqlUtils; +import com.vodafone360.people.datatypes.ActivityContact; +import com.vodafone360.people.datatypes.ActivityItem; +import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; +import com.vodafone360.people.service.ServiceStatus; +import com.vodafone360.people.utils.CloseUtils; +import com.vodafone360.people.utils.LogUtils; +import com.vodafone360.people.utils.StringBufferPool; + +/** + * Contains all the functionality related to the activities database table. This + * class is never instantiated hence all methods must be static. + * + * @version %I%, %G% + */ +public abstract class ActivitiesTable { + /*** + * The name of the table as it appears in the database. + */ + private static final String TABLE_NAME = "Activities"; + + private static final String TABLE_INDEX_NAME = "ActivitiesIndex"; + + /** Database cleanup will delete any activity older than X days. **/ + private static final int CLEANUP_MAX_AGE_DAYS = 20; + + /** Database cleanup will delete older activities after the first X. **/ + private static final int CLEANUP_MAX_QUANTITY = 400; + + /*** + * An enumeration of all the field names in the database. + */ + public static enum Field { + /** Local timeline id. **/ + LOCAL_ACTIVITY_ID("LocalId"), + /** Activity ID. **/ + ACTIVITY_ID("activityid"), + /** Timestamp. */ + TIMESTAMP("time"), + /** Type of the event. **/ + TYPE("type"), + /** URI. */ + URI("uri"), + /** Title for timelines . **/ + TITLE("title"), + /** Contents of timelines/statuses. **/ + DESCRIPTION("description"), + /** Preview URL. **/ + PREVIEW_URL("previewurl"), + /** Store. **/ + STORE("store"), + /** Type of the event: status, chat messages, phone call or SMS/MMS. **/ + FLAG("flag"), + /** Parent Activity. **/ + PARENT_ACTIVITY("parentactivity"), + /** Has children. **/ + HAS_CHILDREN("haschildren"), + /** Visibility. **/ + VISIBILITY("visibility"), + /** More info. **/ + MORE_INFO("moreinfo"), + /** Contact ID. **/ + CONTACT_ID("contactid"), + /** User ID. **/ + USER_ID("userid"), + /** Contact name or the alternative. **/ + CONTACT_NAME("contactname"), + /** Other contact's localContactId. **/ + LOCAL_CONTACT_ID("contactlocalid"), + /** @see SocialNetwork. **/ + CONTACT_NETWORK("contactnetwork"), + /** Contact address. **/ + CONTACT_ADDRESS("contactaddress"), + /** Contact avatar URL. **/ + CONTACT_AVATAR_URL("contactavatarurl"), + /** Native item type. **/ + NATIVE_ITEM_TYPE("nativeitemtype"), + /** Native item ID. **/ + NATIVE_ITEM_ID("nativeitemid"), + /** Latest contact status. **/ + LATEST_CONTACT_STATUS("latestcontactstatus"), + /** Native thread ID. **/ + NATIVE_THREAD_ID("nativethreadid"), + /** For chat messages: if this message is incoming. **/ + INCOMING("incoming"); + + /** Name of the field as it appears in the database. **/ + private final String mField; + + /** + * Constructor. + * + * @param field - The name of the field (see list above) + */ + private Field(final String field) { + mField = field; + } + + /** + * @return the name of the field as it appears in the database. + */ + public String toString() { + return mField; + } + + } + + /** + * An enumeration of supported timeline types. + */ + public static enum TimelineNativeTypes { + /** Call log type. **/ + CallLog, + /** SMS log type. **/ + SmsLog, + /** MMS log type. **/ + MmsLog, + /** Chat log type. **/ + ChatLog + } + + /** + * This class encapsulates a timeline activity item. + */ + public static class TimelineSummaryItem { + + /*** + * Enum of Timeline types. + */ + public enum Type { + /** Incoming type. **/ + INCOMING, + /** Outgoing type. **/ + OUTGOING, + /** Unsent type. **/ + UNSENT, + /** Unknown type (do not use). **/ + UNKNOWN + } + + /*** + * Get the Type from a given Integer value. + + * @param input Integer.ordinal value of the Type + * @return Relevant Type or UNKNOWN if the Integer is not known. + */ + public static Type getType(final int input) { + if (input < 0 || input > Type.UNKNOWN.ordinal()) { + return Type.UNKNOWN; + } else { + return Type.values()[input]; + } + } + + /** Maps to the local activity ID (primary key). **/ + private Long mLocalActivityId; + /** Maps to the activity timestamp in the table. **/ + public Long mTimestamp; + /** Maps to the contact name in the table. **/ + public String mContactName; + /** Set to true if there is an avatar URL stored in the table. **/ + private boolean mHasAvatar; + /** Maps to type in the table. **/ + public ActivityItem.Type mType; + /** Maps to local contact id in the table. **/ + public Long mLocalContactId; + /** Maps to contact network stored in the table. **/ + public String mContactNetwork; + /** Maps to title stored in the table. **/ + public String mTitle; + /** Maps to description stored in the table. **/ + public String mDescription; + /** + * Maps to native item type in the table Can be an ordinal from the + * {@link ActivitiesTable#TimelineNativeTypes}. + */ + public Integer mNativeItemType; + /** + * Key linking to the call-log or message-log item in the native + * database. + */ + public Integer mNativeItemId; + /** Server contact ID. **/ + public Long mContactId; + /** User ID from the server. **/ + public Long mUserId; + /** Thread ID from the native database (for messages). **/ + public Integer mNativeThreadId; + /** Contact address (phone number or email address). **/ + public String mContactAddress; + /** Messages can be incoming and outgoing. **/ + public Type mIncoming; + + /** + * Returns a string describing the timeline summary item. + * + * @return String describing the timeline summary item. + */ + @Override + public final String toString() { + final StringBuilder sb = + new StringBuilder("TimeLineSummaryItem [mLocalActivityId["); + sb.append(mLocalActivityId); + sb.append("], mTimestamp["); sb.append(mTimestamp); + sb.append("], mContactName["); sb.append(mContactName); + sb.append("], mHasAvatar["); sb.append(mHasAvatar); + sb.append("], mType["); sb.append(mType); + sb.append("], mLocalContactId["); sb.append(mLocalContactId); + sb.append("], mContactNetwork["); sb.append(mContactNetwork); + sb.append("], mTitle["); sb.append(mTitle); + sb.append("], mDescription["); sb.append(mDescription); + sb.append("], mNativeItemType["); sb.append(mNativeItemType); + sb.append("], mNativeItemId["); sb.append(mNativeItemId); + sb.append("], mContactId["); sb.append(mContactId); + sb.append("], mUserId["); sb.append(mUserId); + sb.append("], mNativeThreadId["); sb.append(mNativeThreadId); + sb.append("], mContactAddress["); sb.append(mContactAddress); + sb.append("], mIncoming["); sb.append(mIncoming); + sb.append("]]");; + return sb.toString(); + } + + @Override + public final boolean equals(final Object object) { + if (TimelineSummaryItem.class != object.getClass()) { + return false; + } + TimelineSummaryItem item = (TimelineSummaryItem) object; + return mLocalActivityId.equals(item.mLocalActivityId) + && mTimestamp.equals(item.mTimestamp) + && mContactName.equals(item.mContactName) + && mHasAvatar == item.mHasAvatar + && mType.equals(item.mType) + && mLocalContactId.equals(item.mLocalContactId) + && mContactNetwork.equals(item.mContactNetwork) + && mTitle.equals(item.mTitle) + && mDescription.equals(item.mDescription) + && mNativeItemType.equals(item.mNativeItemType) + && mNativeItemId.equals(item.mNativeItemId) + && mContactId.equals(item.mContactId) + && mUserId.equals(item.mUserId) + && mNativeThreadId.equals(item.mNativeThreadId) + && mContactAddress.equals(item.mContactAddress) + && mIncoming.equals(item.mIncoming); + } + }; + + /** Number of milliseconds in a day. **/ + private static final int NUMBER_OF_MS_IN_A_DAY = 24 * 60 * 60 * 1000; + /** Number of milliseconds in a second. **/ + private static final int NUMBER_OF_MS_IN_A_SECOND = 1000; + + /*** + * Private constructor to prevent instantiation. + */ + private ActivitiesTable() { + // Do nothing. + } + + /** + * Create Activities Table. + * + * @param writeableDb A writable SQLite database. + */ + public static void create(final SQLiteDatabase writeableDb) { + DatabaseHelper.trace(true, "DatabaseHelper.create()"); + writeableDb.execSQL("CREATE TABLE " + TABLE_NAME + " (" + + Field.LOCAL_ACTIVITY_ID + + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + Field.ACTIVITY_ID + " LONG, " + + Field.TIMESTAMP + " LONG, " + + Field.TYPE + " TEXT, " + + Field.URI + " TEXT, " + + Field.TITLE + " TEXT, " + + Field.DESCRIPTION + " TEXT, " + + Field.PREVIEW_URL + " TEXT, " + + Field.STORE + " TEXT, " + + Field.FLAG + " INTEGER, " + + Field.PARENT_ACTIVITY + " LONG, " + + Field.HAS_CHILDREN + " INTEGER, " + + Field.VISIBILITY + " INTEGER, " + + Field.MORE_INFO + " TEXT, " + + Field.CONTACT_ID + " LONG, " + + Field.USER_ID + " LONG, " + + Field.CONTACT_NAME + " TEXT, " + + Field.LOCAL_CONTACT_ID + " LONG, " + + Field.CONTACT_NETWORK + " TEXT, " + + Field.CONTACT_ADDRESS + " TEXT, " + + Field.CONTACT_AVATAR_URL + " TEXT, " + + Field.LATEST_CONTACT_STATUS + " INTEGER, " + + Field.NATIVE_ITEM_TYPE + " INTEGER, " + + Field.NATIVE_ITEM_ID + " INTEGER, " + + Field.NATIVE_THREAD_ID + " INTEGER, " + + Field.INCOMING + " INTEGER);"); + + writeableDb.execSQL("CREATE INDEX " + TABLE_INDEX_NAME + " ON " + TABLE_NAME + " ( " + Field.TIMESTAMP + " )"); + } + + /** + * Fetches a comma separated list of table fields which can be used in an + * SQL SELECT statement as the query projection. One of the + * {@link #getQueryData} methods can used to fetch data from the cursor. + * + * @return SQL string + */ + private static String getFullQueryList() { + DatabaseHelper.trace(false, "DatabaseHelper.getFullQueryList()"); + + final StringBuffer fullQuery = StringBufferPool.getStringBuffer(); + fullQuery.append(Field.LOCAL_ACTIVITY_ID).append(SqlUtils.COMMA). + append(Field.ACTIVITY_ID).append(SqlUtils.COMMA). + append(Field.TIMESTAMP).append(SqlUtils.COMMA). + append(Field.TYPE).append(SqlUtils.COMMA). + append(Field.URI).append(SqlUtils.COMMA). + append(Field.TITLE).append(SqlUtils.COMMA). + append(Field.DESCRIPTION).append(SqlUtils.COMMA). + append(Field.PREVIEW_URL).append(SqlUtils.COMMA). + append(Field.STORE).append(SqlUtils.COMMA). + append(Field.FLAG).append(SqlUtils.COMMA). + append(Field.PARENT_ACTIVITY).append(SqlUtils.COMMA). + append(Field.HAS_CHILDREN).append(SqlUtils.COMMA). + append(Field.VISIBILITY).append(SqlUtils.COMMA). + append(Field.MORE_INFO).append(SqlUtils.COMMA). + append(Field.CONTACT_ID).append(SqlUtils.COMMA). + append(Field.USER_ID).append(SqlUtils.COMMA). + append(Field.CONTACT_NAME).append(SqlUtils.COMMA). + append(Field.LOCAL_CONTACT_ID).append(SqlUtils.COMMA). + append(Field.CONTACT_NETWORK).append(SqlUtils.COMMA). + append(Field.CONTACT_ADDRESS).append(SqlUtils.COMMA). + append(Field.CONTACT_AVATAR_URL).append(SqlUtils.COMMA). + append(Field.INCOMING); + + return StringBufferPool.toStringThenRelease(fullQuery); + } + + /** + * Fetches activities information from a cursor at the current position. The + * {@link #getFullQueryList()} method should be used to make the query. + * + * @param cursor The cursor returned by the query + * @param activityItem An empty activity object that will be filled with the + * result + * @param activityContact An empty activity contact object that will be + * filled + */ + public static void getQueryData(final Cursor cursor, + final ActivityItem activityItem, + final ActivityContact activityContact) { + DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); + + /** Populate ActivityItem. **/ + activityItem.localActivityId = + SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); + activityItem.activityId = + SqlUtils.setLong(cursor, Field.ACTIVITY_ID.toString(), null); + activityItem.time = + SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); + activityItem.type = + SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); + activityItem.uri = SqlUtils.setString(cursor, Field.URI.toString()); + activityItem.title = + SqlUtils.setString(cursor, Field.TITLE.toString()); + activityItem.description = + SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); + activityItem.previewUrl = + SqlUtils.setString(cursor, Field.PREVIEW_URL.toString()); + activityItem.store = + SqlUtils.setString(cursor, Field.STORE.toString()); + activityItem.activityFlags = + SqlUtils.setInt(cursor, Field.FLAG.toString(), null); + activityItem.parentActivity = + SqlUtils.setLong(cursor, Field.PARENT_ACTIVITY.toString(), null); + activityItem.hasChildren = + SqlUtils.setBoolean(cursor, Field.HAS_CHILDREN.toString(), + activityItem.hasChildren); + activityItem.visibilityFlags = + SqlUtils.setInt(cursor, Field.VISIBILITY.toString(), null); + // TODO: Field MORE_INFO is not used, consider deleting. + + /** Populate ActivityContact. **/ + getQueryData(cursor, activityContact); + } + + /** + * Fetches activities information from a cursor at the current position. The + * {@link #getFullQueryList()} method should be used to make the query. + * + * @param cursor The cursor returned by the query. + * @param activityContact An empty activity contact object that will be + * filled + */ + public static void getQueryData(final Cursor cursor, + final ActivityContact activityContact) { + DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); + + /** Populate ActivityContact. **/ + activityContact.mContactId = + SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); + activityContact.mUserId = + SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); + activityContact.mName = + SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); + activityContact.mLocalContactId = + SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); + activityContact.mNetwork = + SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); + activityContact.mAddress = + SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); + activityContact.mAvatarUrl = + SqlUtils.setString(cursor, Field.CONTACT_AVATAR_URL.toString()); + } + + /*** + * Provides a ContentValues object that can be used to update the table. + * + * @param item The source activity item + * @param contactIdx The index of the contact to use for the update, or null + * to exclude contact specific information. + * @return ContentValues for use in an SQL update or insert. + * @note Items that are NULL will be not modified in the database. + */ + private static ContentValues fillUpdateData(final ActivityItem item, + final Integer contactIdx) { + DatabaseHelper.trace(false, "DatabaseHelper.fillUpdateData()"); + ContentValues activityItemValues = new ContentValues(); + ActivityContact ac = null; + if (contactIdx != null) { + ac = item.contactList.get(contactIdx); + } + + activityItemValues.put(Field.ACTIVITY_ID.toString(), item.activityId); + activityItemValues.put(Field.TIMESTAMP.toString(), item.time); + if (item.type != null) { + activityItemValues.put(Field.TYPE.toString(), + item.type.getTypeCode()); + } + if (item.uri != null) { + activityItemValues.put(Field.URI.toString(), item.uri); + } + /** TODO: Not sure if we need this. **/ + // activityItemValues.put(Field.INCOMING.toString(), false); + + activityItemValues.put(Field.TITLE.toString(), item.title); + activityItemValues.put(Field.DESCRIPTION.toString(), item.description); + if (item.previewUrl != null) { + activityItemValues.put(Field.PREVIEW_URL.toString(), + item.previewUrl); + } + if (item.store != null) { + activityItemValues.put(Field.STORE.toString(), item.store); + } + if (item.activityFlags != null) { + activityItemValues.put(Field.FLAG.toString(), item.activityFlags); + } + if (item.parentActivity != null) { + activityItemValues.put(Field.PARENT_ACTIVITY.toString(), + item.parentActivity); + } + if (item.hasChildren != null) { + activityItemValues.put(Field.HAS_CHILDREN.toString(), + item.hasChildren); + } + if (item.visibilityFlags != null) { + activityItemValues.put(Field.VISIBILITY.toString(), + item.visibilityFlags); + } + if (ac != null) { + activityItemValues.put(Field.CONTACT_ID.toString(), ac.mContactId); + activityItemValues.put(Field.USER_ID.toString(), ac.mUserId); + activityItemValues.put(Field.CONTACT_NAME.toString(), ac.mName); + activityItemValues.put(Field.LOCAL_CONTACT_ID.toString(), + ac.mLocalContactId); + if (ac.mNetwork != null) { + activityItemValues.put(Field.CONTACT_NETWORK.toString(), + ac.mNetwork); + } + if (ac.mAddress != null) { + activityItemValues.put(Field.CONTACT_ADDRESS.toString(), + ac.mAddress); + } + if (ac.mAvatarUrl != null) { + activityItemValues.put(Field.CONTACT_AVATAR_URL.toString(), + ac.mAvatarUrl); + } + } + + return activityItemValues; + } + + /** + * Fetches a list of status items from the given time stamp. + * + * @param timeStamp Time stamp in milliseconds + * @param readableDb Readable SQLite database + * @return A cursor (use one of the {@link #getQueryData} methods to read + * the data) + */ + public static Cursor fetchStatusEventList(final long timeStamp, + final SQLiteDatabase readableDb) { + DatabaseHelper.trace(false, "DatabaseHelper.fetchStatusEventList()"); + return readableDb.rawQuery("SELECT " + getFullQueryList() + " FROM " + + TABLE_NAME + " WHERE (" + + Field.FLAG + " & " + ActivityItem.STATUS_ITEM + + ") AND " + Field.TIMESTAMP + " > " + timeStamp + + " ORDER BY " + Field.TIMESTAMP + " DESC", null); + } + + /** + * Returns a list of activity IDs already synced, in reverse chronological + * order Fetches from the given timestamp. + * + * @param actIdList An empty list which will be filled with the result + * @param timeStamp The time stamp to start the fetch + * @param readableDb Readable SQLite database + * @return SUCCESS or a suitable error code + */ + public static ServiceStatus fetchActivitiesIds(final List<Long> actIdList, + final Long timeStamp, final SQLiteDatabase readableDb) { + DatabaseHelper.trace(false, "DatabaseHelper.fetchActivitiesIds()"); + Cursor cursor = null; + try { + long queryTimeStamp; + if (timeStamp != null) { + queryTimeStamp = timeStamp; + } else { + queryTimeStamp = 0; + } + + cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + + " FROM " + TABLE_NAME + " WHERE " + + Field.TIMESTAMP + " >= " + queryTimeStamp + + " ORDER BY " + Field.TIMESTAMP + " DESC", null); + while (cursor.moveToNext()) { + actIdList.add(cursor.getLong(0)); + } + + } catch (SQLiteException e) { + LogUtils.logE("ActivitiesTable.fetchActivitiesIds()" + + "Unable to fetch group list", e); + return ServiceStatus.ERROR_DATABASE_CORRUPT; + + } finally { + CloseUtils.close(cursor); + } + return ServiceStatus.SUCCESS; + } + + /** + * Adds a list of activities to table. The activities added will be grouped + * in the database, based on local contact Id, name or contact address (see + * {@link #removeContactGroup(Long, String, Long, int, + * TimelineNativeTypes[], SQLiteDatabase)} + * for more information on how the grouping works. + * + * @param actList The list of activities + * @param writableDb Writable SQLite database + * @return SUCCESS or a suitable error code + */ + public static ServiceStatus addActivities(final List<ActivityItem> actList, + final SQLiteDatabase writableDb) { + DatabaseHelper.trace(true, "DatabaseHelper.addActivities()"); + SQLiteStatement statement = + ContactsTable.fetchLocalFromServerIdStatement(writableDb); + + for (ActivityItem activity : actList) { + try { + writableDb.beginTransaction(); + + if (activity.contactList != null) { + int clistSize = activity.contactList.size(); + for (int i = 0; i < clistSize; i++) { + final ActivityContact activityContact = activity.contactList.get(i); + activityContact.mLocalContactId = + ContactsTable.fetchLocalFromServerId( + activityContact.mContactId, + statement); + + int latestStatusVal = removeContactGroup( + activityContact.mLocalContactId, + activityContact.mName, activity.time, + activity.activityFlags, null, writableDb); + + ContentValues cv = fillUpdateData(activity, i); + cv.put(Field.LATEST_CONTACT_STATUS.toString(), + latestStatusVal); + activity.localActivityId = + writableDb.insertOrThrow(TABLE_NAME, null, cv); + } + } else { + activity.localActivityId = writableDb.insertOrThrow( + TABLE_NAME, null, fillUpdateData(activity, null)); + } + if (activity.localActivityId < 0) { + LogUtils.logE("ActivitiesTable.addActivities() " + + "Unable to add activity"); + return ServiceStatus.ERROR_DATABASE_CORRUPT; + } + writableDb.setTransactionSuccessful(); + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.addActivities() " + + "Unable to add activity", e); + return ServiceStatus.ERROR_DATABASE_CORRUPT; + } finally { + writableDb.endTransaction(); + } + } + if(statement != null) { + statement.close(); + statement = null; + } + + return ServiceStatus.SUCCESS; + } + + /** + * Deletes all activities from the table. + * + * @param flag Can be a bitmap of: + * <ul> + * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> + * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> + * <li>{@link ActivityItem#ALREADY_READ} - Items that have been + * read</li> + * <li>NULL - to delete all activities</li> + * </ul> + * @param writableDb Writable SQLite database + * @return SUCCESS or a suitable error code + */ + public static ServiceStatus deleteActivities(final Integer flag, + final SQLiteDatabase writableDb) { + DatabaseHelper.trace(true, "DatabaseHelper.deleteActivities()"); + try { + String whereClause = null; + if (flag != null) { + whereClause = Field.FLAG + "&" + flag; + } + if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { + LogUtils.logE("ActivitiesTable.deleteActivities() " + + "Unable to delete activities"); + return ServiceStatus.ERROR_DATABASE_CORRUPT; + } + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.deleteActivities() " + + "Unable to delete activities", e); + return ServiceStatus.ERROR_DATABASE_CORRUPT; + } + return ServiceStatus.SUCCESS; + } + + public static ServiceStatus fetchNativeIdsFromLocalContactId(List<Integer > nativeItemIdList, final long localContactId, final SQLiteDatabase readableDb) { + DatabaseHelper.trace(false, "DatabaseHelper.fetchNativeIdsFromLocalContactId()"); + Cursor cursor = null; + try { + cursor = readableDb.rawQuery("SELECT " + Field.NATIVE_ITEM_ID + + " FROM " + TABLE_NAME + " WHERE " + + Field.LOCAL_CONTACT_ID + " = " + localContactId, null); + while (cursor.moveToNext()) { + nativeItemIdList.add(cursor.getInt(0)); + } + + } catch (SQLiteException e) { + LogUtils.logE("ActivitiesTable.fetchNativeIdsFromLocalContactId()" + + "Unable to fetch list of NativeIds from localcontactId", e); + return ServiceStatus.ERROR_DATABASE_CORRUPT; + + } finally { + CloseUtils.close(cursor); + } + return ServiceStatus.SUCCESS; + } + + /** + * Deletes specified timeline activity from the table. + * + * @param Context + * @param timelineItem TimelineSummaryItem to be deleted + * @param writableDb Writable SQLite database + * @param readableDb Readable SQLite database + * @return SUCCESS or a suitable error code + */ + public static ServiceStatus deleteTimelineActivity(final Context context, final TimelineSummaryItem timelineItem, + final SQLiteDatabase writableDb, final SQLiteDatabase readableDb) { + DatabaseHelper.trace(true, "DatabaseHelper.deleteTimelineActivity()"); + try { + List<Integer > nativeItemIdList = new ArrayList<Integer>() ; + + //Delete from Native Database + if(timelineItem.mNativeThreadId != null) { + //Sms Native Database + final Uri smsUri = Uri.parse("content://sms"); + context.getContentResolver().delete(smsUri , "thread_id=" + timelineItem.mNativeThreadId, null); + + //Mms Native Database + final Uri mmsUri = Uri.parse("content://mms"); + context.getContentResolver().delete(mmsUri, "thread_id=" + timelineItem.mNativeThreadId, null); + } else { // For CallLogs + if(timelineItem.mLocalContactId != null) { + fetchNativeIdsFromLocalContactId(nativeItemIdList, timelineItem.mLocalContactId, readableDb); + if(nativeItemIdList.size() > 0) { + //CallLog Native Database + for(Integer nativeItemId : nativeItemIdList) { + context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + nativeItemId, null); + } + } + } else { + if(timelineItem.mContactAddress != null) { + context.getContentResolver().delete(Calls.CONTENT_URI, Calls.NUMBER + "=" + timelineItem.mContactAddress, null); + } + } + } + + String whereClause = null; + + //Delete from People Client database + if(timelineItem.mLocalContactId != null) { + if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs + whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + + Field.NATIVE_THREAD_ID + " IS NULL;"; + } else { //Delete Sms/MmsLogs + whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; + } + } else if(timelineItem.mContactAddress != null) { + if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs + whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + + Field.NATIVE_THREAD_ID + " IS NULL;"; + } else { //Delete Sms/MmsLogs + whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; + } + } + + if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { + LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + + "Unable to delete specified activity"); + return ServiceStatus.ERROR_DATABASE_CORRUPT; + } + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + + "Unable to delete specified activity", e); + return ServiceStatus.ERROR_DATABASE_CORRUPT; + } + return ServiceStatus.SUCCESS; + } + + /** + * Deletes all the timeline activities for a particular contact from the table. + * + * @param Context + * @param timelineItem TimelineSummaryItem to be deleted + * @param writableDb Writable SQLite database + * @param readableDb Readable SQLite database + * @return SUCCESS or a suitable error code + */ + public static ServiceStatus deleteTimelineActivities(Context context, + TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, + SQLiteDatabase readableDb) { + DatabaseHelper.trace(false, "DatabaseHelper.deleteTimelineActivities()"); + Cursor cursor = null; + try { + TimelineNativeTypes[] typeList = null; + TimelineSummaryItem timelineItem = null; + + //For CallLog Timeline + typeList = new TimelineNativeTypes[] { + TimelineNativeTypes.CallLog + }; + cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, + latestTimelineItem.mContactName, typeList, null, readableDb); + + if(cursor != null && cursor.getCount() > 0) { + cursor.moveToFirst(); + timelineItem = getTimelineData(cursor); + if(timelineItem != null) { + deleteTimelineActivity(context, timelineItem, writableDb, readableDb); + } + } + + //For SmsLog/MmsLog Timeline + typeList = new TimelineNativeTypes[] { + TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog + }; + cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, + latestTimelineItem.mContactName, typeList, null, readableDb); + + if(cursor != null && cursor.getCount() > 0) { + cursor.moveToFirst(); + timelineItem = getTimelineData(cursor); + if(timelineItem != null) { + deleteTimelineActivity(context, timelineItem, writableDb, readableDb); + } + } + + //For ChatLog Timeline + typeList = new TimelineNativeTypes[] { + TimelineNativeTypes.ChatLog + }; + cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, + latestTimelineItem.mContactName, typeList, null, readableDb); + + if(cursor != null && cursor.getCount() > 0) { + cursor.moveToFirst(); + timelineItem = getTimelineData(cursor); + if(timelineItem != null) { + deleteTimelineActivity(context, timelineItem, writableDb, readableDb); + } + } + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + + "Unable to delete timeline activities", e); + return ServiceStatus.ERROR_DATABASE_CORRUPT; + } finally { + if(cursor != null) { + CloseUtils.close(cursor); + } + } + + return ServiceStatus.SUCCESS; + } + + /** + * Fetches timeline events grouped by local contact ID, name or contact + * address. Events returned will be in reverse-chronological order. If a + * native type list is provided the result will be filtered by the list. + * + * @param minTimeStamp Only timeline events from this date will be returned + * @param nativeTypes A list of native types to filter the result, or null + * to return all. + * @param readableDb Readable SQLite database + * @return A cursor containing the result. The + * {@link #getTimelineData(Cursor)} method should be used for + * reading the cursor. + */ + public static Cursor fetchTimelineEventList(final Long minTimeStamp, + final TimelineNativeTypes[] nativeTypes, + final SQLiteDatabase readableDb) { + DatabaseHelper.trace(false, "DatabaseHelper.fetchTimelineEventList() " + + "minTimeStamp[" + minTimeStamp + "]"); + try { + int andVal = 1; + String typesQuery = " AND "; + if (nativeTypes != null) { + typesQuery += DatabaseHelper.createWhereClauseFromList( + Field.NATIVE_ITEM_TYPE.toString(), nativeTypes, "OR"); + typesQuery += " AND "; + andVal = 2; + } + + String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + + Field.TITLE + "," + Field.DESCRIPTION + "," + + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + + Field.CONTACT_ID + "," + Field.USER_ID + "," + + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + + typesQuery + Field.TIMESTAMP + " > " + minTimeStamp + + " AND (" + + Field.LATEST_CONTACT_STATUS + " & " + andVal + + ") ORDER BY " + Field.TIMESTAMP + " DESC"; + return readableDb.rawQuery(query, null); + } catch (SQLiteException e) { + LogUtils.logE("ActivitiesTable.fetchLastUpdateTime() " + + "Unable to fetch timeline event list", e); + return null; + } + } + + /** + * Adds a list of timeline events to the database. Each event is grouped by + * contact and grouped by contact + native type. + * + * @param itemList List of timeline events + * @param isCallLog true to group all activities with call logs, false to + * group with messaging + * @param writableDb Writable SQLite database + * @return SUCCESS or a suitable error + */ + public static ServiceStatus addTimelineEvents( + final ArrayList<TimelineSummaryItem> itemList, + final boolean isCallLog, final SQLiteDatabase writableDb) { + DatabaseHelper.trace(true, "DatabaseHelper.addTimelineEvents()"); + TimelineNativeTypes[] activityTypes; + if (isCallLog) { + activityTypes = new TimelineNativeTypes[] { + TimelineNativeTypes.CallLog + }; + } else { + activityTypes = new TimelineNativeTypes[] { + TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog + }; + } + + for (TimelineSummaryItem item : itemList) { + try { + writableDb.beginTransaction(); + + if (findNativeActivity(item, writableDb)) { + continue; + } + int latestStatusVal = 0; + if (item.mContactName != null || item.mLocalContactId != null) { + latestStatusVal |= removeContactGroup(item.mLocalContactId, + item.mContactName, item.mTimestamp, + ActivityItem.TIMELINE_ITEM, null, writableDb); + latestStatusVal |= removeContactGroup(item.mLocalContactId, + item.mContactName, item.mTimestamp, + ActivityItem.TIMELINE_ITEM, activityTypes, + writableDb); + } + ContentValues values = new ContentValues(); + values.put(Field.CONTACT_NAME.toString(), item.mContactName); + values.put(Field.CONTACT_ID.toString(), item.mContactId); + values.put(Field.USER_ID.toString(), item.mUserId); + values.put(Field.LOCAL_CONTACT_ID.toString(), + item.mLocalContactId); + values.put(Field.CONTACT_NETWORK.toString(), + item.mContactNetwork); + values.put(Field.DESCRIPTION.toString(), item.mDescription); + values.put(Field.TITLE.toString(), item.mTitle); + values.put(Field.CONTACT_ADDRESS.toString(), + item.mContactAddress); + values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM); + values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); + values.put(Field.NATIVE_ITEM_TYPE.toString(), + item.mNativeItemType); + values.put(Field.TIMESTAMP.toString(), item.mTimestamp); + if (item.mType != null) { + values.put(Field.TYPE.toString(), + item.mType.getTypeCode()); + } + values.put(Field.LATEST_CONTACT_STATUS.toString(), + latestStatusVal); + values.put(Field.NATIVE_THREAD_ID.toString(), + item.mNativeThreadId); + if (item.mIncoming != null) { + values.put(Field.INCOMING.toString(), + item.mIncoming.ordinal()); + } + + item.mLocalActivityId = + writableDb.insert(TABLE_NAME, null, values); + if (item.mLocalActivityId < 0) { + LogUtils.logE("ActivitiesTable.addTimelineEvents() " + + "ERROR_DATABASE_CORRUPT - Unable to add " + + "timeline list to database"); + return ServiceStatus.ERROR_DATABASE_CORRUPT; + } + + writableDb.setTransactionSuccessful(); + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + + "Unable to add timeline list to database", e); + return ServiceStatus.ERROR_DATABASE_CORRUPT; + } finally { + writableDb.endTransaction(); + } + } + + return ServiceStatus.SUCCESS; + } + + + /** + * The method returns the ROW_ID i.e. the INTEGER PRIMARY KEY AUTOINCREMENT + * field value for the inserted row, i.e. LOCAL_ID. + * + * @param item TimelineSummaryItem. + * @param read - TRUE if the chat message is outgoing or gets into the + * timeline history view for a contact with LocalContactId. + * @param writableDb Writable SQLite database. + * @return LocalContactID or -1 if the row was not inserted. + */ + public static long addChatTimelineEvent(final TimelineSummaryItem item, + final boolean read, final SQLiteDatabase writableDb) { + DatabaseHelper.trace(true, "DatabaseHelper.addChatTimelineEvent()"); + + try { + + writableDb.beginTransaction(); + + int latestStatusVal = 0; + if (item.mContactName != null || item.mLocalContactId != null) { + latestStatusVal |= removeContactGroup(item.mLocalContactId, + item.mContactName, item.mTimestamp, + ActivityItem.TIMELINE_ITEM, null, writableDb); + latestStatusVal |= removeContactGroup(item.mLocalContactId, + item.mContactName, item.mTimestamp, + ActivityItem.TIMELINE_ITEM, new TimelineNativeTypes[] { + TimelineNativeTypes.ChatLog + }, writableDb); + } + ContentValues values = new ContentValues(); + values.put(Field.CONTACT_NAME.toString(), item.mContactName); + values.put(Field.CONTACT_ID.toString(), item.mContactId); + values.put(Field.USER_ID.toString(), item.mUserId); + values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); + values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); + values.put(Field.DESCRIPTION.toString(), item.mDescription); + /** Chat message body. **/ + values.put(Field.TITLE.toString(), item.mTitle); + values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); + if (read) { + values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM + | ActivityItem.ALREADY_READ); + } else { + values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM + | 0); + } + values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); + values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); + values.put(Field.TIMESTAMP.toString(), item.mTimestamp); + if (item.mType != null) { + values.put(Field.TYPE.toString(), item.mType.getTypeCode()); + } + + values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); + values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); + /** Conversation ID for chat message. **/ + // values.put(Field.URI.toString(), item.conversationId); + // 0 for incoming, 1 for outgoing + if (item.mIncoming != null) { + values.put(Field.INCOMING.toString(), + item.mIncoming.ordinal()); + } + + final long itemId = writableDb.insert(TABLE_NAME, null, values); + if (itemId < 0) { + LogUtils.logE("ActivitiesTable.addTimelineEvents() - " + + "Unable to add timeline list to database, index<0:" + + itemId); + return -1; + } + writableDb.setTransactionSuccessful(); + return itemId; + + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + + "Unable to add timeline list to database", e); + return -1; + + } finally { + writableDb.endTransaction(); + } + } + + /** + * Clears the grouping of an activity in the database, if the given activity + * is newer. This is so that only the latest activity is returned for a + * particular group. Each activity is associated with two groups: + * <ol> + * <li>All group - Grouped by contact only</li> + * <li>Native group - Grouped by contact and native type (call log or + * messaging)</li> + * </ol> + * The group to be removed is determined by the activityTypes parameter. + * Grouping must also work for timeline events that are not associated with + * a contact. The following fields are used to do identify a contact for the + * grouping (in order of priority): + * <ol> + * <li>localContactId - If it not null</li> + * <li>name - If this is a valid telephone number, the match will be done to + * ensure that the same phone number written in different ways will be + * included in the group. See {@link #fetchNameWhereClause(Long, String)} + * for more information.</li> + * </ol> + * + * @param localContactId Local contact Id or NULL if the activity is not + * associated with a contact. + * @param name Name of contact or contact address (telephone number, email, + * etc). + * @param newUpdateTime The time that the given activity has occurred + * @param flag Bitmap of types including: + * <ul> + * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> + * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> + * <li>{@link ActivityItem#ALREADY_READ} - Items that have been + * read</li> + * </ul> + * @param activityTypes A list of native types to include in the grouping. + * Currently, only two groups are supported (see above). If this + * parameter is null the contact will be added to the + * "all group", otherwise the contact is added to the native + * group. + * @param writableDb Writable SQLite database + * @return The latest contact status value which should be added to the + * current activities grouping. + */ + private static int removeContactGroup(final Long localContactId, + final String name, final Long newUpdateTime, final int flag, + final TimelineNativeTypes[] activityTypes, + final SQLiteDatabase writableDb) { + String whereClause = ""; + int andVal = 1; + if (activityTypes != null) { + whereClause = DatabaseHelper.createWhereClauseFromList( + Field.NATIVE_ITEM_TYPE.toString(), activityTypes, "OR"); + whereClause += " AND "; + andVal = 2; + } + + String nameWhereClause = fetchNameWhereClause(localContactId, name); + + if (nameWhereClause == null) { + return 0; + } + whereClause += nameWhereClause; + Long prevTime = null; + Long prevLocalId = null; + Integer prevLatestContactStatus = null; + Cursor cursor = null; + try { + cursor = writableDb.rawQuery("SELECT " + Field.TIMESTAMP + "," + + Field.LOCAL_ACTIVITY_ID + "," + + Field.LATEST_CONTACT_STATUS + " FROM " + TABLE_NAME + + " WHERE " + whereClause + + " AND " + + "(" + Field.LATEST_CONTACT_STATUS + " & " + andVal + + ") AND (" + + Field.FLAG + "&" + flag + + ") ORDER BY " + Field.TIMESTAMP + " DESC", null); + if (cursor.moveToFirst()) { + prevTime = cursor.getLong(0); + prevLocalId = cursor.getLong(1); + prevLatestContactStatus = cursor.getInt(2); + } + } catch (SQLException e) { + return 0; + + } finally { + CloseUtils.close(cursor); + } + if (prevTime != null && newUpdateTime != null) { + if (newUpdateTime >= prevTime) { + ContentValues cv = new ContentValues(); + cv.put(Field.LATEST_CONTACT_STATUS.toString(), + prevLatestContactStatus & (~andVal)); + if (writableDb.update(TABLE_NAME, cv, Field.LOCAL_ACTIVITY_ID + + "=" + prevLocalId, null) <= 0) { + LogUtils.logE("ActivitiesTable.addTimelineEvents() " + + "Unable to update timeline as the latest"); + return 0; + } + return andVal; + } else { + return 0; + } + } + return andVal; + } + + /** + * Checks if an activity exists in the database. + * + * @param item The native SMS item to check against our client activities DB table. + * + * @return true if the activity was found, false otherwise + * + */ + private static boolean findNativeActivity(TimelineSummaryItem item, final SQLiteDatabase readableDb) { + DatabaseHelper.trace(false, "DatabaseHelper.findNativeActivity()"); + Cursor cursor = null; + boolean result = false; + try { + final String[] args = { + Integer.toString(item.mNativeItemId), Integer.toString(item.mNativeItemType), Long.toString(item.mTimestamp) + }; + cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + + " WHERE " + Field.NATIVE_ITEM_ID + "=? AND " + Field.NATIVE_ITEM_TYPE + "=?" + + " AND " + Field.TIMESTAMP + "=?", args); + if (cursor.moveToFirst()) { + result = true; + } + } finally { + CloseUtils.close(cursor); + } + return result; + } + + /** + * Returns a string which can be added to the where clause in an SQL query + * on the activities table, to filter the result for a specific contact or + * name. The clause will prioritise in the following way: + * <ol> + * <li>Use localContactId - If it not null</li> + * <li>Use name - If this is a valid telephone number, the match will be + * done to ensure that the same phone number written in different ways will + * be included in the group. + * </ol> + * + * @param localContactId The local contact ID, or null if the contact does + * not exist in the People database. + * @param name A string containing the name, or a telephone number/email + * identifying the contact. + * @return The where clause string + */ + private static String fetchNameWhereClause(final Long localContactId, + final String name) { + DatabaseHelper.trace(false, "DatabaseHelper.fetchNameWhereClause()"); + if (localContactId != null) { + return Field.LOCAL_CONTACT_ID + "=" + localContactId; + } + + if (name == null) { + return null; + } + final String searchName = DatabaseUtils.sqlEscapeString(name); + if (PhoneNumberUtils.isWellFormedSmsAddress(name)) { + return "(PHONE_NUMBERS_EQUAL(" + Field.CONTACT_NAME + "," + + searchName + ") OR "+ Field.CONTACT_NAME + "=" + + searchName+")"; + } else { + return Field.CONTACT_NAME + "=" + searchName; + } + } + + + /** + * Returns the timeline summary data from the current location of the given + * cursor. The cursor can be obtained using + * {@link #fetchTimelineEventList(Long, TimelineNativeTypes[], + * SQLiteDatabase)} or + * {@link #fetchTimelineEventsForContact(Long, Long, String, + * TimelineNativeTypes[], SQLiteDatabase)}. + * + * @param cursor Cursor in the required position. + * @return A filled out TimelineSummaryItem object + */ + public static TimelineSummaryItem getTimelineData(final Cursor cursor) { + DatabaseHelper.trace(false, "DatabaseHelper.getTimelineData()"); + TimelineSummaryItem item = new TimelineSummaryItem(); + item.mLocalActivityId = + SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); + item.mTimestamp = + SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); + item.mContactName = + SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); + if (!cursor.isNull( + cursor.getColumnIndex(Field.CONTACT_AVATAR_URL.toString()))) { + item.mHasAvatar = true; + } + item.mLocalContactId = + SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); + item.mTitle = SqlUtils.setString(cursor, Field.TITLE.toString()); + item.mDescription = + SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); + item.mContactNetwork = + SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); + item.mNativeItemType = + SqlUtils.setInt(cursor, Field.NATIVE_ITEM_TYPE.toString(), null); + item.mNativeItemId = + SqlUtils.setInt(cursor, Field.NATIVE_ITEM_ID.toString(), null); + item.mType = + SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); + item.mContactId = + SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); + item.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); + item.mNativeThreadId = + SqlUtils.setInt(cursor, Field.NATIVE_THREAD_ID.toString(), null); + item.mContactAddress = + SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); + item.mIncoming = SqlUtils.setTimelineSummaryItemType(cursor, + Field.INCOMING.toString()); + return item; + } + + /** + * Fetches timeline events for a specific contact identified by local + * contact ID, name or address. Events returned will be in + * reverse-chronological order. If a native type list is provided the result + * will be filtered by the list. + * + * @param timeStamp Only events from this time will be returned + * @param localContactId The local contact ID if the contact is in the + * People database, or null. + * @param name The name or address of the contact (required if local contact + * ID is NULL). + * @param nativeTypes A list of required native types to filter the result, + * or null to return all timeline events for the contact. + * @param readableDb Readable SQLite database + * @param networkName The name of the network the contacts belongs to + * (required in order to provide appropriate chat messages + * filtering) If the parameter is null messages from all networks + * will be returned. The values are the + * SocialNetwork.VODAFONE.toString(), + * SocialNetwork.GOOGLE.toString(), or + * SocialNetwork.MICROSOFT.toString() results. + * @return The cursor that can be read using + * {@link #getTimelineData(Cursor)}. + */ + public static Cursor fetchTimelineEventsForContact(final Long timeStamp, + final Long localContactId, final String name, + final TimelineNativeTypes[] nativeTypes, final String networkName, + final SQLiteDatabase readableDb) { + DatabaseHelper.trace(false, "DatabaseHelper." + + "fetchTimelineEventsForContact()"); + try { + String typesQuery = " AND "; + if (nativeTypes.length > 0) { + StringBuffer typesQueryBuffer = new StringBuffer(); + typesQueryBuffer.append(" AND ("); + for (int i = 0; i < nativeTypes.length; i++) { + final TimelineNativeTypes type = nativeTypes[i]; + typesQueryBuffer.append(Field.NATIVE_ITEM_TYPE + + "=" + type.ordinal()); + if (i < nativeTypes.length - 1) { + typesQueryBuffer.append(" OR "); + } + } + typesQueryBuffer.append(") AND "); + typesQuery = typesQueryBuffer.toString(); + } + + /** Filter by account. **/ + String networkQuery = ""; + String queryNetworkName = networkName; + if (queryNetworkName != null) { + if (queryNetworkName.equals(SocialNetwork.PC.toString()) + || queryNetworkName.equals( + SocialNetwork.MOBILE.toString())) { + queryNetworkName = SocialNetwork.VODAFONE.toString(); + } + networkQuery = Field.CONTACT_NETWORK + "='" + queryNetworkName + + "' AND "; + } + + String whereAppend; + if (localContactId == null) { + whereAppend = Field.LOCAL_CONTACT_ID + " IS NULL AND " + + fetchNameWhereClause(localContactId, name); + if (whereAppend == null) { + return null; + } + } else { + whereAppend = Field.LOCAL_CONTACT_ID + "=" + localContactId; + } + String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + + Field.TITLE + "," + Field.DESCRIPTION + "," + + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + + + Field.CONTACT_ID + "," + Field.USER_ID + "," + + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + + typesQuery + networkQuery + whereAppend + + " ORDER BY " + Field.TIMESTAMP + " ASC"; + return readableDb.rawQuery(query, null); + } catch (SQLiteException e) { + LogUtils.logE("ActivitiesTable.fetchTimelineEventsForContact() " + + "Unable to fetch timeline event for contact list", e); + return null; + } + } + + /** + * Mark the chat timeline events for a given contact as read. + * + * @param localContactId Local contact ID. + * @param networkName Name of the SNS. + * @param writableDb Writable SQLite reference. + * @return Number of rows affected by database update. + */ + public static int markChatTimelineEventsForContactAsRead( + final Long localContactId, final String networkName, + final SQLiteDatabase writableDb) { + DatabaseHelper.trace(false, "DatabaseHelper." + + "fetchTimelineEventsForContact()"); + ContentValues values = new ContentValues(); + values.put(Field.FLAG.toString(), + ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); + + String networkQuery = ""; + if (networkName != null) { + networkQuery = " AND (" + Field.CONTACT_NETWORK + "='" + + networkName + "')"; + } + + final String where = Field.LOCAL_CONTACT_ID + "=" + localContactId + + " AND " + Field.NATIVE_ITEM_TYPE + "=" + + TimelineNativeTypes.ChatLog.ordinal() + " AND (" + /** + * If the network is null, set all messages as read for this + * contact. + */ + + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")" + + networkQuery; + + return writableDb.update(TABLE_NAME, values, where, null); + } + + /** + * Returns the latest status event for a contact with the given local contact id. + * + * @param local contact id Server contact ID. + * @param readableDb Readable SQLite database. + * @return The ActivityItem representing the latest status event for given local contact id, + * or null if nothing was found. + */ + public static ActivityItem getLatestStatusForContact(final long localContactId, + final SQLiteDatabase readableDb) { + DatabaseHelper.trace(false, "DatabaseHelper getLatestStatusForContact"); + Cursor cursor = null; + try { + StringBuffer query = StringBufferPool.getStringBuffer(SQLKeys.SELECT); + query.append(getFullQueryList()).append(SQLKeys.FROM).append(TABLE_NAME).append(SQLKeys.WHERE). + append(Field.FLAG).append('&').append(ActivityItem.STATUS_ITEM).append(SQLKeys.AND). + append(Field.LOCAL_CONTACT_ID).append('=').append(localContactId). + append(" ORDER BY ").append(Field.TIMESTAMP).append(" DESC"); + + cursor = readableDb.rawQuery(StringBufferPool.toStringThenRelease(query), null); + if (cursor.moveToFirst()) { + final ActivityItem activityItem = new ActivityItem(); + final ActivityContact activityContact = new ActivityContact(); + ActivitiesTable.getQueryData(cursor, activityItem, activityContact); + return activityItem; + } + } finally { + CloseUtils.close(cursor); + cursor = null; + } + return null; + } + + /** + * Updates timeline when a new contact is added to the People database. + * Updates all timeline events that are not associated with a contact and + * have a phone number that matches the oldName parameter. + * + * @param oldName The telephone number (since is the name of an activity + * that is not associated with a contact) + * @param newName The new name + * @param newLocalContactId The local Contact Id for the added contact. + * @param newContactId The server Contact Id for the added contact (or null + * if the contact has not yet been synced). + * @param witeableDb Writable SQLite database + */ + public static void updateTimelineContactNameAndId(final String oldName, + final String newName, final Long newLocalContactId, + final Long newContactId, final SQLiteDatabase witeableDb) { + DatabaseHelper.trace(false, "DatabaseHelper." + + "updateTimelineContactNameAndId()"); + + try { + ContentValues values = new ContentValues(); + if (newName != null) { + values.put(Field.CONTACT_NAME.toString(), newName); + } else { + LogUtils.logE("updateTimelineContactNameAndId() " + + "newName should never be null"); + } + if (newLocalContactId != null) { + values.put(Field.LOCAL_CONTACT_ID.toString(), + newLocalContactId); + } else { + LogUtils.logE("updateTimelineContactNameAndId() " + + "newLocalContactId should never be null"); + } + if (newContactId != null) { + values.put(Field.CONTACT_ID.toString(), newContactId); + } else { + /** + * newContactId will be null if adding a contact from the UI. + */ + LogUtils.logI("updateTimelineContactNameAndId() " + + "newContactId is null"); + /** + * We haven't got server Contact it, it means it haven't been + * synced yet. + */ + } + + String name = ""; + if (oldName != null) { + name = oldName; + LogUtils.logW("ActivitiesTable." + + "updateTimelineContactNameAndId() oldName is NULL"); + } + String[] args = { + "2", name + }; + + String whereClause = Field.LOCAL_CONTACT_ID + " IS NULL AND " + + Field.FLAG + "=? AND PHONE_NUMBERS_EQUAL(" + + Field.CONTACT_ADDRESS + ",?)"; + witeableDb.update(TABLE_NAME, values, whereClause, args); + + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.updateTimelineContactNameAndId() " + + "Unable update table", e); + throw e; + } + } + + /** + * Updates the timeline when a contact name is modified in the database. + * + * @param newName The new name. + * @param localContactId Local contact Id which was modified. + * @param witeableDb Writable SQLite database + */ + public static void updateTimelineContactNameAndId(final String newName, + final Long localContactId, final SQLiteDatabase witeableDb) { + DatabaseHelper.trace(false, "DatabaseHelper." + + "updateTimelineContactNameAndId()"); + if (newName == null || localContactId == null) { + LogUtils.logE("updateTimelineContactNameAndId() newName or " + + "localContactId == null newName(" + newName + + ") localContactId(" + localContactId + ")"); + return; + } + + try { + ContentValues values = new ContentValues(); + Long cId = ContactsTable.fetchServerId(localContactId, witeableDb); + values.put(Field.CONTACT_NAME.toString(), newName); + if (cId != null) { + values.put(Field.CONTACT_ID.toString(), cId); + } + String[] args = { + localContactId.toString() + }; + String whereClause = Field.LOCAL_CONTACT_ID + "=?"; + witeableDb.update(TABLE_NAME, values, whereClause, args); + + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.updateTimelineContactNameAndId()" + + " Unable update table", e); + } + } + + /** + * Updates the timeline entries in the activities table to remove deleted + * contact info. + * + * @param localContactId - the contact id that has been deleted + * @param writeableDb - reference to the database + */ + public static void removeTimelineContactData(final Long localContactId, + final SQLiteDatabase writeableDb) { + DatabaseHelper.trace(false, "DatabaseHelper." + + "removeTimelineContactData()"); + if (localContactId == null) { + LogUtils.logE("removeTimelineContactData() localContactId == null " + + "localContactId(" + localContactId + ")"); + return; + } + try { + //Remove all the Chat Entries + removeChatTimelineForContact(localContactId, writeableDb); + + String[] args = { + localContactId.toString() + }; + String query = "UPDATE " + + TABLE_NAME + + " SET " + + Field.LOCAL_CONTACT_ID + "=NULL, " + + Field.CONTACT_ID + "=NULL, " + Field.CONTACT_NAME + "=" + + Field.CONTACT_ADDRESS + " WHERE " + + Field.LOCAL_CONTACT_ID + "=? AND (" + + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")"; + writeableDb.execSQL(query, args); + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.removeTimelineContactData() Unable " + + "to update table: \n", e); + } + } + + /** + * Removes all the items from the chat timeline for the given contact. + * + * @param localContactId Given contact ID. + * @param writeableDb Writable SQLite database. + */ + private static void removeChatTimelineForContact( + final Long localContactId, final SQLiteDatabase writeableDb) { + DatabaseHelper.trace(false, "DatabaseHelper." + + "removeChatTimelineForContact()"); + if (localContactId == null || (localContactId == -1)) { + LogUtils.logE("removeChatTimelineForContact() localContactId == " + + "null " + "localContactId(" + localContactId + ")"); + return; + } + final String query = Field.LOCAL_CONTACT_ID + "=" + localContactId + + " AND (" + Field.NATIVE_ITEM_TYPE + "=" + + TimelineNativeTypes.ChatLog.ordinal() + ")"; + try { + writeableDb.delete(TABLE_NAME, query, null); + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.removeChatTimelineForContact() " + + "Unable to update table", e); + } + } + + /** + * Removes items from the chat timeline that are not for the given contact. + * + * @param localContactId Given contact ID. + * @param writeableDb Writable SQLite database. + */ + public static void removeChatTimelineExceptForContact( + final Long localContactId, final SQLiteDatabase writeableDb) { + DatabaseHelper.trace(false, "DatabaseHelper." + + "removeTimelineContactData()"); + if (localContactId == null || (localContactId == -1)) { + LogUtils.logE("removeTimelineContactData() localContactId == null " + + "localContactId(" + localContactId + ")"); + return; + } + try { + final long olderThan = System.currentTimeMillis() + - Settings.HISTORY_IS_WEEK_LONG; + final String query = Field.LOCAL_CONTACT_ID + "!=" + localContactId + + " AND (" + Field.NATIVE_ITEM_TYPE + "=" + + TimelineNativeTypes.ChatLog.ordinal() + ") AND (" + + Field.TIMESTAMP + "<" + olderThan + ")"; + writeableDb.delete(TABLE_NAME, query, null); + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.removeTimelineContactData() " + + "Unable to update table", e); + } + } + + /*** + * Returns the number of users have currently have unread chat messages. + * + * @param readableDb Reference to a readable database. + * @return Number of users with unread chat messages. + */ + public static int getNumberOfUnreadChatUsers( + final SQLiteDatabase readableDb) { + final String query = "SELECT " + Field.LOCAL_CONTACT_ID + " FROM " + + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + + TimelineNativeTypes.ChatLog.ordinal() + " AND (" + /** + * This condition below means the timeline is not yet marked + * as READ. + */ + + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; + Cursor cursor = null; + try { + cursor = readableDb.rawQuery(query, null); + ArrayList<Long> ids = new ArrayList<Long>(); + Long id = null; + while (cursor.moveToNext()) { + id = cursor.getLong(0); + if (!ids.contains(id)) { + ids.add(id); + } + } + return ids.size(); + + } finally { + CloseUtils.close(cursor); + } + } + + /*** + * Returns the number of unread chat messages. + * + * @param readableDb Reference to a readable database. + * @return Number of unread chat messages. + */ + public static int getNumberOfUnreadChatMessages( + final SQLiteDatabase readableDb) { + final String query = "SELECT " + Field.ACTIVITY_ID + " FROM " + + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + + TimelineNativeTypes.ChatLog.ordinal() + " AND (" + + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; + Cursor cursor = null; + try { + cursor = readableDb.rawQuery(query, null); + return cursor.getCount(); + + } finally { + CloseUtils.close(cursor); + } + } + + /*** + * Returns the number of unread chat messages for this contact besides this + * network. + * + * @param localContactId Given contact ID. + * @param network SNS name. + * @param readableDb Reference to a readable database. + * @return Number of unread chat messages. + */ + public static int getNumberOfUnreadChatMessagesForContactAndNetwork( + final long localContactId, final String network, + final SQLiteDatabase readableDb) { + final String query = "SELECT " + Field.ACTIVITY_ID + " FROM " + + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + + TimelineNativeTypes.ChatLog.ordinal() + " AND (" + Field.FLAG + + "=" + ActivityItem.TIMELINE_ITEM + ") AND (" + + Field.LOCAL_CONTACT_ID + "=" + localContactId + ") AND (" + + Field.CONTACT_NETWORK + "!=\"" + network + "\")"; + Cursor cursor = null; + try { + cursor = readableDb.rawQuery(query, null); + return cursor.getCount(); + + } finally { + CloseUtils.close(cursor); + } + } + + /*** + * Returns the newest unread chat message. + * + * @param readableDb Reference to a readable database. + * @return TimelineSummaryItem of the newest unread chat message, or NULL if + * none are found. + */ + public static TimelineSummaryItem getNewestUnreadChatMessage( + final SQLiteDatabase readableDb) { + + final String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + + Field.TITLE + "," + Field.DESCRIPTION + "," + + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + + Field.CONTACT_ID + "," + Field.USER_ID + "," + + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + + Field.INCOMING + + " FROM " + TABLE_NAME + " WHERE " + + Field.NATIVE_ITEM_TYPE + "=" + + TimelineNativeTypes.ChatLog.ordinal() + + " AND (" + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; + Cursor cursor = null; + try { + cursor = readableDb.rawQuery(query, null); + long max = 0; + long time = 0; + int index = -1; + while (cursor.moveToNext()) { + time = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), + -1L); + if (time > max) { + max = time; + index = cursor.getPosition(); + } + } + if (index != -1) { + cursor.moveToPosition(index); + return getTimelineData(cursor); + } else { + return null; + } + + } finally { + CloseUtils.close(cursor); + } + } + + /*** + * Cleanup the Activity Table by deleting anything older than + * CLEANUP_MAX_AGE_DAYS, or preventing the total size from exceeding + * CLEANUP_MAX_QUANTITY. + * + * @param writableDb Reference to a writable SQLite Database. + */ + public static void cleanupActivityTable(final SQLiteDatabase writableDb) { + DatabaseHelper.trace(true, "DatabaseHelper.cleanupActivityTable()"); + try { + /* + * Delete any Activities older than CLEANUP_MAX_AGE_DAYS days. + */ + if (CLEANUP_MAX_AGE_DAYS != -1) { + if (writableDb.delete(TABLE_NAME, Field.TIMESTAMP + " < " + + ((System.currentTimeMillis() + / NUMBER_OF_MS_IN_A_SECOND) + - CLEANUP_MAX_AGE_DAYS * NUMBER_OF_MS_IN_A_DAY), + null) < 0) { + LogUtils.logE("ActivitiesTable.cleanupActivityTable() " + + "Unable to cleanup Activities table by date"); + } + } + /* + * Delete oldest Activities, when total number of rows exceeds + * CLEANUP_MAX_QUANTITY in quantity. + */ + if (CLEANUP_MAX_QUANTITY != -1) { + writableDb.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + + Field.LOCAL_ACTIVITY_ID + " IN (SELECT " + + Field.LOCAL_ACTIVITY_ID + " FROM " + TABLE_NAME + + " ORDER BY " + Field.TIMESTAMP + + " DESC LIMIT -1 OFFSET " + CLEANUP_MAX_QUANTITY + + ")"); + } + } catch (SQLException e) { + LogUtils.logE("ActivitiesTable.cleanupActivityTable() " + + "Unable to cleanup Activities table by date", e); + } + } + + /** + * Returns the TimelineSummaryItem for the corresponding native thread Id. + * + * @param threadId native thread id + * @param readableDb Readable SQLite database + * @return The TimelineSummaryItem of the matching native thread id, + * or NULL if none are found. + */ + public static TimelineSummaryItem fetchTimeLineDataFromNativeThreadId( + final String threadId, + final SQLiteDatabase readableDb) { + DatabaseHelper.trace(false, "DatabaseHelper." + + "fetchTimeLineDataFromNativeThreadId()"); + Cursor cursor = null; + + try { + String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + + Field.NATIVE_THREAD_ID + " = " + threadId + " ORDER BY " + + Field.TIMESTAMP + " DESC"; + + cursor = readableDb.rawQuery(query, null); + if (cursor != null && cursor.moveToFirst() && !cursor.isNull(0)) { + return getTimelineData(cursor); + } else { + return null; + } + } finally { + CloseUtils.close(cursor); + } + } + + /** + * This method deletes the timeline event for the contact by timestamp. + * + * @param localContactId Given contact ID. + * @param the time of the event. + * @param writeableDb Writable SQLite database. + */ + public static void deleteUnsentChatMessageForContact( + final Long localContactId, long timestamp, final SQLiteDatabase writeableDb) { + DatabaseHelper.trace(false, "ActivitiesTable deleteUnsentChatMessageForContact()"); + if (localContactId == null || (localContactId == -1)) { + LogUtils.logE("deleteUnsentChatMessageForContact() localContactId == " + + "null " + "localContactId(" + localContactId + ")"); + return; + } + StringBuffer where1 = StringBufferPool.getStringBuffer(Field.LOCAL_CONTACT_ID.toString()); + where1.append("=").append(localContactId).append(" AND (").append(Field.NATIVE_ITEM_TYPE.toString()).append("=") + .append(TimelineNativeTypes.ChatLog.ordinal()).append(") AND (").append(Field.TIMESTAMP).append("=") + .append(timestamp).append(") AND (").append(Field.INCOMING).append("=") + .append(TimelineSummaryItem.Type.OUTGOING.ordinal()).append(")"); + + if (writeableDb.delete(TABLE_NAME, StringBufferPool.toStringThenRelease(where1), null) > 0) { + StringBuffer where2 = StringBufferPool.getStringBuffer(Field.LOCAL_ACTIVITY_ID.toString()); + where2.append(" IN (SELECT ").append(Field.LOCAL_ACTIVITY_ID.toString()).append(" FROM ").append(TABLE_NAME) + .append(" WHERE ").append(Field.LOCAL_CONTACT_ID.toString()).append("=").append(localContactId).append(" AND ") + .append(Field.NATIVE_ITEM_TYPE).append(" IN (").append(TimelineNativeTypes.CallLog.ordinal()).append(",") + .append(TimelineNativeTypes.SmsLog.ordinal()).append(",").append(TimelineNativeTypes.MmsLog.ordinal()) + .append(",").append(TimelineNativeTypes.ChatLog.ordinal()).append(") ORDER BY ").append(Field.TIMESTAMP).append(" DESC LIMIT 1)"); + ContentValues values = new ContentValues(); + //this value marks the timeline as the latest event for this contact. this value is normally set in addTimeline + //methods for the added event after resetting previous latest activities. + final int LATEST_TIMELINE = 3; + values.put(Field.LATEST_CONTACT_STATUS.toString(), LATEST_TIMELINE); + writeableDb.update(TABLE_NAME, values, StringBufferPool.toStringThenRelease(where2), null); + } + } + } \ No newline at end of file
360/360-Engine-for-Android
29ad8d3ce3b27eb8f4f3841dfcf3060fe72e1a9c
fixed code review comments
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 18680c6..5d685f6 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,782 +1,782 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.identities; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import android.os.Bundle; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Identities; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; /** * Engine responsible for handling retrieval and validation of Identities (e.g. * 3rd party/web accounts). The Identities engine can fetch a list of available * accounts, and set required capabilities and validate credentials for * specified accounts. */ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { /** * States for IdentitiesEngine. States are based on the requests that the * engine needs to handle. */ private enum State { IDLE, FETCHING_IDENTITIES, VALIDATING_IDENTITY_CREDENTIALS, SETTING_IDENTITY_STATUS, GETTING_MY_IDENTITIES, GETTING_MY_CHATABLE_IDENTITIES } /** * Mutex for thread synchronisation */ private final Object mMutex = new Object(); /** * Container class for Identity Capability Status request. Consists of a * network, identity id and a filter containing the required capabilities. */ private static class IdentityStatusRequest { private String mNetwork; private String mIdentityId; private String mIdentityStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setIdentityStatus(String status) { mIdentityStatus = status; } } /** * Container class encapsulating an Identity validation request containing: * dry-run flag, network, user-name, password, set of required capabilities. */ private static class IdentityValidateCredentialsRequest { /** Performs a dry run if true. */ private boolean mDryRun; /** Network to sign into. */ private String mNetwork; /** Username to sign into identity with. */ private String mUserName; /** Password to sign into identity with. */ private String mPassword; private Map<String, Boolean> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private ArrayList<Identity> mMyIdentityList; /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; mMyIdentityList = new ArrayList<Identity>(); mAvailableIdentityList = new ArrayList<Identity>(); mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { if ((mAvailableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return mMyIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = getMyThirdPartyChattableIdentities(); // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chattableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chattableIdentities; } /** * * Takes all third party identities that have a chat capability set to true. * * @return A list of chattable 3rd party identities the user is signed in to. If the retrieval identities failed the returned list will be empty. * */ public ArrayList<Identity> getMyThirdPartyChattableIdentities() { ArrayList<Identity> chattableIdentities = new ArrayList<Identity>(); int identityListSize = mMyIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = mMyIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && - (capability.mValue == true)) { + (capability.mValue)) { chattableIdentities.add(identity); break; } } } return chattableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } // invalidate 'chat-able' identities cache if (mMyChatableIdentityList != null) { mMyChatableIdentityList.clear(); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(DecodedResponse resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if ((null == resp) || (null == resp.mDataTypes)) { LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); return; } // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); } } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; idBundle = mAvailableIdentityList; } else { requestKey = KEY_MY_IDS; idBundle = mMyIdentityList; } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } /** * * Retrieves the filter for the getAvailableIdentities and getMyIdentities * calls. * * @return The identities filter in form of a bundle. * */ private Bundle getIdentitiesFilter() { Bundle b = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); l.add(IdentityCapability.CapabilityID.get_own_status.name()); b.putStringArrayList("capability", l); return b; } @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } /** * Generate Map containing String capability filters for m supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, List<String>> prepareStringFilter(Bundle filter) { Map<String, List<String>> returnFilter = null; if (filter != null && filter.keySet().size() > 0) { returnFilter = new Hashtable<String, List<String>>(); for (String key : filter.keySet()) { returnFilter.put(key, filter.getStringArrayList(key)); } } else { returnFilter = null; } return returnFilter; } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ /** {@inheritDoc} */ @Override public final void onReset() { if (null != mMyIdentityList) { mMyIdentityList.clear(); } super.onReset(); } }
360/360-Engine-for-Android
1ce99d65aa8c1ecfa6f5f0edc1715de16d372b97
altered identities engine to be able to deliver identities properly to the me profile
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 8484612..18680c6 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,769 +1,782 @@ -/* - * CDDL HEADER START - * - * The contents of this file are subject to the terms of the Common Development - * and Distribution License (the "License"). - * You may not use this file except in compliance with the License. - * - * You can obtain a copy of the license at - * src/com/vodafone360/people/VODAFONE.LICENSE.txt or - * http://github.com/360/360-Engine-for-Android - * See the License for the specific language governing permissions and - * limitations under the License. - * - * When distributing Covered Code, include this CDDL HEADER in each file and - * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. - * If applicable, add the following below this CDDL HEADER, with the fields - * enclosed by brackets "[]" replaced with your own identifying information: - * Portions Copyright [yyyy] [name of copyright owner] - * - * CDDL HEADER END - * - * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. - * Use is subject to license terms. - */ - -package com.vodafone360.people.engine.identities; - -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; - -import android.os.Bundle; - -import com.vodafone360.people.datatypes.BaseDataType; -import com.vodafone360.people.datatypes.Identity; -import com.vodafone360.people.datatypes.IdentityCapability; -import com.vodafone360.people.datatypes.PushEvent; -import com.vodafone360.people.datatypes.StatusMsg; -import com.vodafone360.people.engine.BaseEngine; -import com.vodafone360.people.engine.EngineManager; -import com.vodafone360.people.engine.EngineManager.EngineId; -import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; -import com.vodafone360.people.service.ServiceStatus; -import com.vodafone360.people.service.ServiceUiRequest; -import com.vodafone360.people.service.agent.UiAgent; -import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; -import com.vodafone360.people.service.io.api.Identities; -import com.vodafone360.people.service.io.rpg.PushMessageTypes; -import com.vodafone360.people.service.transport.ConnectionManager; -import com.vodafone360.people.service.transport.http.HttpConnectionThread; -import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; -import com.vodafone360.people.utils.LogUtils; - -/** - * Engine responsible for handling retrieval and validation of Identities (e.g. - * 3rd party/web accounts). The Identities engine can fetch a list of available - * accounts, and set required capabilities and validate credentials for - * specified accounts. - */ -public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { - - /** - * States for IdentitiesEngine. States are based on the requests that the - * engine needs to handle. - */ - private enum State { - IDLE, - FETCHING_IDENTITIES, - VALIDATING_IDENTITY_CREDENTIALS, - SETTING_IDENTITY_STATUS, - GETTING_MY_IDENTITIES, - GETTING_MY_CHATABLE_IDENTITIES - } - - /** - * Mutex for thread synchronisation - */ - private final Object mMutex = new Object(); - - /** - * Container class for Identity Capability Status request. Consists of a - * network, identity id and a filter containing the required capabilities. - */ - private static class IdentityStatusRequest { - private String mNetwork; - - private String mIdentityId; - - private String mIdentityStatus = null; - - /** - * Supply filter containing required capabilities. - * - * @param filter Bundle containing capabilities filter. - */ - public void setIdentityStatus(String status) { - mIdentityStatus = status; - } - } - - /** - * Container class encapsulating an Identity validation request containing: - * dry-run flag, network, user-name, password, set of required capabilities. - */ - private static class IdentityValidateCredentialsRequest { - /** Performs a dry run if true. */ - private boolean mDryRun; - /** Network to sign into. */ - private String mNetwork; - /** Username to sign into identity with. */ - private String mUserName; - /** Password to sign into identity with. */ - private String mPassword; - - private Map<String, Boolean> mStatus = null; - - /** - * Supply filter containing required capabilities. - * - * @param filter Bundle containing capabilities filter. - */ - public void setCapabilityStatus(Bundle filter) { - mStatus = prepareBoolFilter(filter); - } - } - - /** The minimum interval between identity requests. */ - private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; - /** The timestamp of which my identities were last requested. */ - private long mLastMyIdentitiesRequestTimestamp; - /** The timestamp of which available identities were last requested. */ - private long mLastAvailableIdentitiesRequestTimestamp; - - /** The state of the state machine handling ui requests. */ - private State mState = State.IDLE; - - /** List array of Identities retrieved from Server. */ - private ArrayList<Identity> mAvailableIdentityList; - - /** List array of Identities retrieved from Server. */ - private ArrayList<Identity> mMyIdentityList; - - /** List array of Identities supporting chat retrieved from Server. */ - private ArrayList<String> mMyChatableIdentityList = null; - - /** Holds the status messages of the setIdentityCapability-request. */ - private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); - - /** The key for setIdentityCapability data type for the push ui message. */ - public static final String KEY_DATA = "data"; - /** The key for available identities for the push ui message. */ - public static final String KEY_AVAILABLE_IDS = "availableids"; - /** The key for my identities for the push ui message. */ - public static final String KEY_MY_IDS = "myids"; - - /** - * Constructor - * - * @param eventCallback IEngineEventCallback allowing engine to report back. - */ - public IdentityEngine(IEngineEventCallback eventCallback) { - super(eventCallback); - mEngineId = EngineId.IDENTITIES_ENGINE; - - mMyIdentityList = new ArrayList<Identity>(); - mAvailableIdentityList = new ArrayList<Identity>(); - - mLastMyIdentitiesRequestTimestamp = 0; - mLastAvailableIdentitiesRequestTimestamp = 0; - } - - /** - * - * Gets all third party identities and adds the mobile identity - * from 360 to them. - * - * @return A list of all 3rd party identities the user is signed in to plus - * the 360 identity mobile. If the retrieval failed the list will - * be empty. - * - */ - public ArrayList<Identity> getAvailableThirdPartyIdentities() { - if ((mAvailableIdentityList.size() == 0) && ( - (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) - > MIN_REQUEST_INTERVAL)) { - sendGetAvailableIdentitiesRequest(); - } - - return mAvailableIdentityList; - } - - /** - * - * Gets all third party identities the user is currently signed up for. - * - * @return A list of 3rd party identities the user is signed in to or an - * empty list if something went wrong retrieving the identities. - * - */ - public ArrayList<Identity> getMyThirdPartyIdentities() { - if ((mMyIdentityList.size() == 0) && ( - (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) - > MIN_REQUEST_INTERVAL)) { - sendGetMyIdentitiesRequest(); - } - - return mMyIdentityList; - } - - /** - * - * Takes all third party identities that have a chat capability set to true. - * It also includes the 360 identity mobile. - * - * @return A list of chattable 3rd party identities the user is signed in to - * plus the mobile 360 identity. If the retrieval identities failed the - * returned list will be empty. - * - */ - public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { - ArrayList<Identity> chatableIdentities = new ArrayList<Identity>(); - int identityListSize = mMyIdentityList.size(); - - // checking each identity for its chat capability and adding it to the - // list if it does - for (int i = 0; i < identityListSize; i++) { - Identity identity = mMyIdentityList.get(i); - List<IdentityCapability> capabilities = identity.mCapabilities; - - if (null == capabilities) { - continue; // if the capabilties are null skip to next identity - } - - // run through capabilties and check for chat - for (int j = 0; j < capabilities.size(); j++) { - IdentityCapability capability = capabilities.get(j); - - if (null == capability) { - continue; // skip null capabilities - } - - if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && - (capability.mValue == true)) { - chatableIdentities.add(identity); - break; - } - } - } - - // add mobile identity to support 360 chat - IdentityCapability capability = new IdentityCapability(); - capability.mCapability = IdentityCapability.CapabilityID.chat; - capability.mValue = new Boolean(true); - ArrayList<IdentityCapability> mobileCapabilities = - new ArrayList<IdentityCapability>(); - mobileCapabilities.add(capability); - - Identity mobileIdentity = new Identity(); - mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); - mobileIdentity.mName = "Vodafone"; - mobileIdentity.mCapabilities = mobileCapabilities; - chatableIdentities.add(mobileIdentity); - // end: add mobile identity to support 360 chat - - return chatableIdentities; - } - - - /** - * Sends a get my identities request to the server which will be handled - * by onProcessCommsResponse once a response comes in. - */ - private void sendGetMyIdentitiesRequest() { - Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); - } - - /** - * Send a get available identities request to the backend which will be - * handled by onProcessCommsResponse once a response comes in. - */ - private void sendGetAvailableIdentitiesRequest() { - Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); - } - - /** - * Enables or disables the given social network. - * - * @param network Name of the identity, - * @param identityId Id of identity. - * @param identityStatus True if identity should be enabled, false otherwise. - */ - public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { - LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); - IdentityStatusRequest data = new IdentityStatusRequest(); - data.mIdentityId = identityId; - data.mNetwork = network; - data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY - : Identities.DISABLE_IDENTITY); - // do not empty reqQueue here, ui can put many at one time - addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); - } - - /** - * Add request to validate user credentials for a specified identity. - * - * @param dryRun True if this is a dry-run. - * @param network Name of the network/identity. - * @param username User-name for login for this identity. - * @param password Password for login for this identity. - * @param identityCapabilityStatus Bundle containing capability details for - * this identity. - */ - public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, - String password, Bundle identityCapabilityStatus) { - LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); - IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); - data.mDryRun = dryRun; - data.mNetwork = network; - data.mPassword = password; - data.mUserName = username; - data.setCapabilityStatus(identityCapabilityStatus); - emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); - } - - /** - * Issue any outstanding UI request. - * - * @param requestType Request to be issued. - * @param dara Data associated with the request. - */ - @Override - protected void processUiRequest(ServiceUiRequest requestType, Object data) { - LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); - switch (requestType) { - case VALIDATE_IDENTITY_CREDENTIALS: - executeValidateIdentityCredentialsRequest(data); - break; - case SET_IDENTITY_CAPABILITY_STATUS: - executeSetIdentityStatusRequest(data); - break; - default: - completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); - break; - } - } - - /** - * Issue request to set capabilities for a given Identity. (Request is not - * issued if there is currently no connectivity). - * - * @param data Bundled request data. - */ - private void executeSetIdentityStatusRequest(Object data) { - if (!isConnected()) { - return; - } - newState(State.SETTING_IDENTITY_STATUS); - IdentityStatusRequest reqData = (IdentityStatusRequest)data; - if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, - reqData.mIdentityStatus))) { - completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); - } - // invalidate 'chat-able' identities cache - if (mMyChatableIdentityList != null) { - mMyChatableIdentityList.clear(); - } - - } - - /** - * Issue request to validate the user credentials for an Identity. (Request - * is not issued if there is currently no connectivity). - * - * @param data Bundled request data. - */ - private void executeValidateIdentityCredentialsRequest(Object data) { - if (!isConnected()) { - return; - } - newState(State.VALIDATING_IDENTITY_CREDENTIALS); - IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; - if (!setReqId(Identities - .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, - reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { - completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); - } - } - - /** - * Process a response received from Server. The response is handled - * according to the current IdentityEngine state. - * - * @param resp The decoded response. - */ - @Override - protected void processCommsResponse(DecodedResponse resp) { - LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); - - if ((null == resp) || (null == resp.mDataTypes)) { - LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); - return; - } - - // TODO replace this whole block with the response type in the DecodedResponse class in the future! - if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg - PushEvent evt = (PushEvent)resp.mDataTypes.get(0); - handlePushResponse(evt.mMessageType); - } else if (resp.mDataTypes.size() > 0) { // regular response - switch (resp.mDataTypes.get(0).getType()) { - case BaseDataType.MY_IDENTITY_DATA_TYPE: - handleGetMyIdentitiesResponse(resp.mDataTypes); - break; - case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: - handleGetAvailableIdentitiesResponse(resp.mDataTypes); - break; - case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: - handleSetIdentityStatus(resp.mDataTypes); - break; - case BaseDataType.STATUS_MSG_DATA_TYPE: - handleValidateIdentityCredentials(resp.mDataTypes); - break; - default: - LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); - break; - } - } else { // responses data list is 0, that means e.g. no identities in an identities response - LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); - - if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { - pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); - } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { - pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); - } - } // end: replace this whole block with the response type in the DecodedResponse class in the future! - } - - /** - * Handle Status or Timeline Activity change Push message - * - * @param evt Push message type (Status change or Timeline change). - */ - private void handlePushResponse(PushMessageTypes evt) { - LogUtils.logD("IdentityEngine handlePushRequest"); - switch (evt) { - case IDENTITY_NETWORK_CHANGE: - sendGetAvailableIdentitiesRequest(); - break; - case IDENTITY_CHANGE: - EngineManager.getInstance().getPresenceEngine().setMyAvailability(); - sendGetMyIdentitiesRequest(); - mEventCallback.kickWorkerThread(); - break; - default: - // do nothing - } - } - - /** - * Run function called via EngineManager. Should have a UI, Comms response - * or timeout event to handle. - */ - @Override - public void run() { - LogUtils.logD("IdentityEngine.run()"); - if (isCommsResponseOutstanding() && processCommsInQueue()) { - LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " - + mState.name()); - return; - } - if (processTimeout()) { - return; - } - if (isUiRequestOutstanding()) { - processUiQueue(); - } - } - - /** - * Change current IdentityEngine state. - * - * @param newState new state. - */ - private void newState(State newState) { - State oldState = mState; - synchronized (mMutex) { - if (newState == mState) { - return; - } - mState = newState; - } - LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); - } - - - /** - * Handle Server response to request for available Identities. The response - * should be a list of Identity items. The request is completed with - * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type - * retrieved are not Identity items. - * - * @param data List of BaseDataTypes generated from Server response. - */ - private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { - LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); - ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); - - if (errorStatus == ServiceStatus.SUCCESS) { - synchronized (mAvailableIdentityList) { - mAvailableIdentityList.clear(); - - for (BaseDataType item : data) { - mAvailableIdentityList.add((Identity)item); - } - } - } - - pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); - - LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); - } - - /** - * Handle Server response to request for available Identities. The response - * should be a list of Identity items. The request is completed with - * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type - * retrieved are not Identity items. - * - * @param data List of BaseDataTypes generated from Server response. - */ - private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { - LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); - ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); - - if (errorStatus == ServiceStatus.SUCCESS) { - synchronized (mMyIdentityList) { - mMyIdentityList.clear(); - - for (BaseDataType item : data) { - mMyIdentityList.add((Identity)item); - } - } - } - - pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); - - LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); - } - - /** - * Handle Server response to set validate credentials request. The response - * should be a Status-msg indicating whether the request has succeeded or - * failed. The request is completed with the status result (or - * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a - * Status-msg). - * - * @param data List of BaseDataTypes generated from Server response. - */ - private void handleValidateIdentityCredentials(List<BaseDataType> data) { - Bundle bu = null; - ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); - if (errorStatus == ServiceStatus.SUCCESS) { - mStatusList.clear(); - for (BaseDataType item : data) { - if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { - mStatusList.add((StatusMsg)item); - } else { - completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); - return; - } - } - bu = new Bundle(); - if (mStatusList.size() == 1) { - bu.putBoolean("status", mStatusList.get(0).mStatus); - } else { - LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); - bu.putParcelableArrayList(KEY_DATA, mStatusList); - } - } - completeUiRequest(errorStatus, bu); - - newState(State.IDLE); - - } - - /** - * Handle Server response to set capability status request. The response - * should be a Status-msg indicating whether the request has succeeded or - * failed. The request is completed with the status result (or - * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a - * Status-msg). - * - * @param data List of BaseDataTypes generated from Server response. - */ - private void handleSetIdentityStatus(List<BaseDataType> data) { - Bundle bu = null; - ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); - if (errorStatus == ServiceStatus.SUCCESS) { - mStatusList.clear(); - for (BaseDataType item : data) { - if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { - mStatusList.add((StatusMsg)item); - } else { - completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); - return; - } - } - bu = new Bundle(); - bu.putParcelableArrayList(KEY_DATA, mStatusList); - } - completeUiRequest(errorStatus, bu); - newState(State.IDLE); - } - - /** - * - * Pushes the identities retrieved by get my identities or by get available identities - * to the ui. - * - * @param request The request type: either get my identities, or get available identities. - */ - private void pushIdentitiesToUi(ServiceUiRequest request) { - String requestKey = null; - ArrayList<Identity> idBundle = null; - if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { - requestKey = KEY_AVAILABLE_IDS; - idBundle = mAvailableIdentityList; - } else { - requestKey = KEY_MY_IDS; - idBundle = mMyIdentityList; - } - - // send update to 3rd party identities ui if it is up - Bundle b = new Bundle(); - b.putParcelableArrayList(requestKey, idBundle); - - UiAgent uiAgent = mEventCallback.getUiAgent(); - if (uiAgent != null && uiAgent.isSubscribed()) { - uiAgent.sendUnsolicitedUiEvent(request, b); - } // end: send update to 3rd party identities ui if it is up - } - - /** - * Get Connectivity status from the connection manager. - * - * @return true True if the connection is active, false otherwise. - * - */ - private boolean isConnected() { - int connState = ConnectionManager.getInstance().getConnectionState(); - return (connState == ITcpConnectionListener.STATE_CONNECTED); - } - - /** - * - * Retrieves the filter for the getAvailableIdentities and getMyIdentities - * calls. - * - * @return The identities filter in form of a bundle. - * - */ - private Bundle getIdentitiesFilter() { - Bundle b = new Bundle(); - ArrayList<String> l = new ArrayList<String>(); - l.add(IdentityCapability.CapabilityID.chat.name()); - l.add(IdentityCapability.CapabilityID.get_own_status.name()); - b.putStringArrayList("capability", l); - return b; - } - - @Override - public void onConnectionStateChanged(int state) { - if (state == ITcpConnectionListener.STATE_CONNECTED) { - emptyUiRequestQueue(); - sendGetAvailableIdentitiesRequest(); - sendGetMyIdentitiesRequest(); - } - } - - /** - * Return the next run-time for the IdentitiesEngine. Will run as soon as - * possible if we need to issue a request, or we have a resonse waiting. - * - * @return next run-time. - */ - @Override - public long getNextRunTime() { - if (isUiRequestOutstanding()) { - return 0; - } - if (isCommsResponseOutstanding()) { - return 0; - } - return getCurrentTimeout(); - } - - /** {@inheritDoc} */ - @Override - public void onCreate() { - } - - /** {@inheritDoc} */ - @Override - public void onDestroy() { - } - - /** {@inheritDoc} */ - @Override - protected void onRequestComplete() { - } - - /** {@inheritDoc} */ - @Override - protected void onTimeoutEvent() { - } - - /** - * Generate Map containing boolean capability filters for supplied Bundle. - * - * @param filter Bundle containing filter. - * @return Map containing set of capabilities. - */ - private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { - Map<String, Boolean> objectFilter = null; - if (filter != null && (filter.keySet().size() > 0)) { - objectFilter = new Hashtable<String, Boolean>(); - for (String key : filter.keySet()) { - objectFilter.put(key, filter.getBoolean(key)); - } - } else { - objectFilter = null; - } - return objectFilter; - } - - /** - * Generate Map containing String capability filters for m supplied Bundle. - * - * @param filter Bundle containing filter. - * @return Map containing set of capabilities. - */ - private static Map<String, List<String>> prepareStringFilter(Bundle filter) { - Map<String, List<String>> returnFilter = null; - if (filter != null && filter.keySet().size() > 0) { - returnFilter = new Hashtable<String, List<String>>(); - for (String key : filter.keySet()) { - returnFilter.put(key, filter.getStringArrayList(key)); - } - } else { - returnFilter = null; - } - return returnFilter; - } - - /** - * This method needs to be called as part of removeAllData()/changeUser() - * routine. - */ - /** {@inheritDoc} */ - @Override - public final void onReset() { - if (null != mMyIdentityList) { - mMyIdentityList.clear(); - } - super.onReset(); - } - -} +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the Common Development + * and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at + * src/com/vodafone360/people/VODAFONE.LICENSE.txt or + * http://github.com/360/360-Engine-for-Android + * See the License for the specific language governing permissions and + * limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each file and + * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. + * If applicable, add the following below this CDDL HEADER, with the fields + * enclosed by brackets "[]" replaced with your own identifying information: + * Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + * + * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. + * Use is subject to license terms. + */ + +package com.vodafone360.people.engine.identities; + +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; + +import android.os.Bundle; + +import com.vodafone360.people.datatypes.BaseDataType; +import com.vodafone360.people.datatypes.Identity; +import com.vodafone360.people.datatypes.IdentityCapability; +import com.vodafone360.people.datatypes.PushEvent; +import com.vodafone360.people.datatypes.StatusMsg; +import com.vodafone360.people.engine.BaseEngine; +import com.vodafone360.people.engine.EngineManager; +import com.vodafone360.people.engine.EngineManager.EngineId; +import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; +import com.vodafone360.people.service.ServiceStatus; +import com.vodafone360.people.service.ServiceUiRequest; +import com.vodafone360.people.service.agent.UiAgent; +import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; +import com.vodafone360.people.service.io.api.Identities; +import com.vodafone360.people.service.io.rpg.PushMessageTypes; +import com.vodafone360.people.service.transport.ConnectionManager; +import com.vodafone360.people.service.transport.http.HttpConnectionThread; +import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; +import com.vodafone360.people.utils.LogUtils; + +/** + * Engine responsible for handling retrieval and validation of Identities (e.g. + * 3rd party/web accounts). The Identities engine can fetch a list of available + * accounts, and set required capabilities and validate credentials for + * specified accounts. + */ +public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { + + /** + * States for IdentitiesEngine. States are based on the requests that the + * engine needs to handle. + */ + private enum State { + IDLE, + FETCHING_IDENTITIES, + VALIDATING_IDENTITY_CREDENTIALS, + SETTING_IDENTITY_STATUS, + GETTING_MY_IDENTITIES, + GETTING_MY_CHATABLE_IDENTITIES + } + + /** + * Mutex for thread synchronisation + */ + private final Object mMutex = new Object(); + + /** + * Container class for Identity Capability Status request. Consists of a + * network, identity id and a filter containing the required capabilities. + */ + private static class IdentityStatusRequest { + private String mNetwork; + + private String mIdentityId; + + private String mIdentityStatus = null; + + /** + * Supply filter containing required capabilities. + * + * @param filter Bundle containing capabilities filter. + */ + public void setIdentityStatus(String status) { + mIdentityStatus = status; + } + } + + /** + * Container class encapsulating an Identity validation request containing: + * dry-run flag, network, user-name, password, set of required capabilities. + */ + private static class IdentityValidateCredentialsRequest { + /** Performs a dry run if true. */ + private boolean mDryRun; + /** Network to sign into. */ + private String mNetwork; + /** Username to sign into identity with. */ + private String mUserName; + /** Password to sign into identity with. */ + private String mPassword; + + private Map<String, Boolean> mStatus = null; + + /** + * Supply filter containing required capabilities. + * + * @param filter Bundle containing capabilities filter. + */ + public void setCapabilityStatus(Bundle filter) { + mStatus = prepareBoolFilter(filter); + } + } + + /** The minimum interval between identity requests. */ + private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; + /** The timestamp of which my identities were last requested. */ + private long mLastMyIdentitiesRequestTimestamp; + /** The timestamp of which available identities were last requested. */ + private long mLastAvailableIdentitiesRequestTimestamp; + + /** The state of the state machine handling ui requests. */ + private State mState = State.IDLE; + + /** List array of Identities retrieved from Server. */ + private ArrayList<Identity> mAvailableIdentityList; + + /** List array of Identities retrieved from Server. */ + private ArrayList<Identity> mMyIdentityList; + + /** List array of Identities supporting chat retrieved from Server. */ + private ArrayList<String> mMyChatableIdentityList = null; + + /** Holds the status messages of the setIdentityCapability-request. */ + private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); + + /** The key for setIdentityCapability data type for the push ui message. */ + public static final String KEY_DATA = "data"; + /** The key for available identities for the push ui message. */ + public static final String KEY_AVAILABLE_IDS = "availableids"; + /** The key for my identities for the push ui message. */ + public static final String KEY_MY_IDS = "myids"; + + /** + * Constructor + * + * @param eventCallback IEngineEventCallback allowing engine to report back. + */ + public IdentityEngine(IEngineEventCallback eventCallback) { + super(eventCallback); + mEngineId = EngineId.IDENTITIES_ENGINE; + + mMyIdentityList = new ArrayList<Identity>(); + mAvailableIdentityList = new ArrayList<Identity>(); + + mLastMyIdentitiesRequestTimestamp = 0; + mLastAvailableIdentitiesRequestTimestamp = 0; + } + + /** + * + * Gets all third party identities and adds the mobile identity + * from 360 to them. + * + * @return A list of all 3rd party identities the user is signed in to plus + * the 360 identity mobile. If the retrieval failed the list will + * be empty. + * + */ + public ArrayList<Identity> getAvailableThirdPartyIdentities() { + if ((mAvailableIdentityList.size() == 0) && ( + (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) + > MIN_REQUEST_INTERVAL)) { + sendGetAvailableIdentitiesRequest(); + } + + return mAvailableIdentityList; + } + + /** + * + * Gets all third party identities the user is currently signed up for. + * + * @return A list of 3rd party identities the user is signed in to or an + * empty list if something went wrong retrieving the identities. + * + */ + public ArrayList<Identity> getMyThirdPartyIdentities() { + if ((mMyIdentityList.size() == 0) && ( + (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) + > MIN_REQUEST_INTERVAL)) { + sendGetMyIdentitiesRequest(); + } + + return mMyIdentityList; + } + + /** + * + * Takes all third party identities that have a chat capability set to true. + * It also includes the 360 identity mobile. + * + * @return A list of chattable 3rd party identities the user is signed in to + * plus the mobile 360 identity. If the retrieval identities failed the + * returned list will be empty. + * + */ + public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { + ArrayList<Identity> chattableIdentities = getMyThirdPartyChattableIdentities(); + + // add mobile identity to support 360 chat + IdentityCapability capability = new IdentityCapability(); + capability.mCapability = IdentityCapability.CapabilityID.chat; + capability.mValue = new Boolean(true); + ArrayList<IdentityCapability> mobileCapabilities = + new ArrayList<IdentityCapability>(); + mobileCapabilities.add(capability); + + Identity mobileIdentity = new Identity(); + mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); + mobileIdentity.mName = "Vodafone"; + mobileIdentity.mCapabilities = mobileCapabilities; + chattableIdentities.add(mobileIdentity); + // end: add mobile identity to support 360 chat + + return chattableIdentities; + } + + /** + * + * Takes all third party identities that have a chat capability set to true. + * + * @return A list of chattable 3rd party identities the user is signed in to. If the retrieval identities failed the returned list will be empty. + * + */ + public ArrayList<Identity> getMyThirdPartyChattableIdentities() { + ArrayList<Identity> chattableIdentities = new ArrayList<Identity>(); + int identityListSize = mMyIdentityList.size(); + + // checking each identity for its chat capability and adding it to the + // list if it does + for (int i = 0; i < identityListSize; i++) { + Identity identity = mMyIdentityList.get(i); + List<IdentityCapability> capabilities = identity.mCapabilities; + + if (null == capabilities) { + continue; // if the capabilties are null skip to next identity + } + + // run through capabilties and check for chat + for (int j = 0; j < capabilities.size(); j++) { + IdentityCapability capability = capabilities.get(j); + + if (null == capability) { + continue; // skip null capabilities + } + + if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && + (capability.mValue == true)) { + chattableIdentities.add(identity); + break; + } + } + } + + return chattableIdentities; + } + + + /** + * Sends a get my identities request to the server which will be handled + * by onProcessCommsResponse once a response comes in. + */ + private void sendGetMyIdentitiesRequest() { + Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); + } + + /** + * Send a get available identities request to the backend which will be + * handled by onProcessCommsResponse once a response comes in. + */ + private void sendGetAvailableIdentitiesRequest() { + Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); + } + + /** + * Enables or disables the given social network. + * + * @param network Name of the identity, + * @param identityId Id of identity. + * @param identityStatus True if identity should be enabled, false otherwise. + */ + public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { + LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); + IdentityStatusRequest data = new IdentityStatusRequest(); + data.mIdentityId = identityId; + data.mNetwork = network; + data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY + : Identities.DISABLE_IDENTITY); + // do not empty reqQueue here, ui can put many at one time + addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); + } + + /** + * Add request to validate user credentials for a specified identity. + * + * @param dryRun True if this is a dry-run. + * @param network Name of the network/identity. + * @param username User-name for login for this identity. + * @param password Password for login for this identity. + * @param identityCapabilityStatus Bundle containing capability details for + * this identity. + */ + public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, + String password, Bundle identityCapabilityStatus) { + LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); + IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); + data.mDryRun = dryRun; + data.mNetwork = network; + data.mPassword = password; + data.mUserName = username; + data.setCapabilityStatus(identityCapabilityStatus); + emptyUiRequestQueue(); + addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); + } + + /** + * Issue any outstanding UI request. + * + * @param requestType Request to be issued. + * @param dara Data associated with the request. + */ + @Override + protected void processUiRequest(ServiceUiRequest requestType, Object data) { + LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); + switch (requestType) { + case VALIDATE_IDENTITY_CREDENTIALS: + executeValidateIdentityCredentialsRequest(data); + break; + case SET_IDENTITY_CAPABILITY_STATUS: + executeSetIdentityStatusRequest(data); + break; + default: + completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); + break; + } + } + + /** + * Issue request to set capabilities for a given Identity. (Request is not + * issued if there is currently no connectivity). + * + * @param data Bundled request data. + */ + private void executeSetIdentityStatusRequest(Object data) { + if (!isConnected()) { + return; + } + newState(State.SETTING_IDENTITY_STATUS); + IdentityStatusRequest reqData = (IdentityStatusRequest)data; + if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, + reqData.mIdentityStatus))) { + completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); + } + // invalidate 'chat-able' identities cache + if (mMyChatableIdentityList != null) { + mMyChatableIdentityList.clear(); + } + + } + + /** + * Issue request to validate the user credentials for an Identity. (Request + * is not issued if there is currently no connectivity). + * + * @param data Bundled request data. + */ + private void executeValidateIdentityCredentialsRequest(Object data) { + if (!isConnected()) { + return; + } + newState(State.VALIDATING_IDENTITY_CREDENTIALS); + IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; + if (!setReqId(Identities + .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, + reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { + completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); + } + } + + /** + * Process a response received from Server. The response is handled + * according to the current IdentityEngine state. + * + * @param resp The decoded response. + */ + @Override + protected void processCommsResponse(DecodedResponse resp) { + LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); + + if ((null == resp) || (null == resp.mDataTypes)) { + LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); + return; + } + + // TODO replace this whole block with the response type in the DecodedResponse class in the future! + if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg + PushEvent evt = (PushEvent)resp.mDataTypes.get(0); + handlePushResponse(evt.mMessageType); + } else if (resp.mDataTypes.size() > 0) { // regular response + switch (resp.mDataTypes.get(0).getType()) { + case BaseDataType.MY_IDENTITY_DATA_TYPE: + handleGetMyIdentitiesResponse(resp.mDataTypes); + break; + case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: + handleGetAvailableIdentitiesResponse(resp.mDataTypes); + break; + case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: + handleSetIdentityStatus(resp.mDataTypes); + break; + case BaseDataType.STATUS_MSG_DATA_TYPE: + handleValidateIdentityCredentials(resp.mDataTypes); + break; + default: + LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); + break; + } + } else { // responses data list is 0, that means e.g. no identities in an identities response + LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); + + if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { + pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); + } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { + pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); + } + } // end: replace this whole block with the response type in the DecodedResponse class in the future! + } + + /** + * Handle Status or Timeline Activity change Push message + * + * @param evt Push message type (Status change or Timeline change). + */ + private void handlePushResponse(PushMessageTypes evt) { + LogUtils.logD("IdentityEngine handlePushRequest"); + switch (evt) { + case IDENTITY_NETWORK_CHANGE: + sendGetAvailableIdentitiesRequest(); + break; + case IDENTITY_CHANGE: + EngineManager.getInstance().getPresenceEngine().setMyAvailability(); + sendGetMyIdentitiesRequest(); + mEventCallback.kickWorkerThread(); + break; + default: + // do nothing + } + } + + /** + * Run function called via EngineManager. Should have a UI, Comms response + * or timeout event to handle. + */ + @Override + public void run() { + LogUtils.logD("IdentityEngine.run()"); + if (isCommsResponseOutstanding() && processCommsInQueue()) { + LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + + mState.name()); + return; + } + if (processTimeout()) { + return; + } + if (isUiRequestOutstanding()) { + processUiQueue(); + } + } + + /** + * Change current IdentityEngine state. + * + * @param newState new state. + */ + private void newState(State newState) { + State oldState = mState; + synchronized (mMutex) { + if (newState == mState) { + return; + } + mState = newState; + } + LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); + } + + + /** + * Handle Server response to request for available Identities. The response + * should be a list of Identity items. The request is completed with + * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type + * retrieved are not Identity items. + * + * @param data List of BaseDataTypes generated from Server response. + */ + private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { + LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); + ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); + + if (errorStatus == ServiceStatus.SUCCESS) { + synchronized (mAvailableIdentityList) { + mAvailableIdentityList.clear(); + + for (BaseDataType item : data) { + mAvailableIdentityList.add((Identity)item); + } + } + } + + pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); + + LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); + } + + /** + * Handle Server response to request for available Identities. The response + * should be a list of Identity items. The request is completed with + * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type + * retrieved are not Identity items. + * + * @param data List of BaseDataTypes generated from Server response. + */ + private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { + LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); + ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); + + if (errorStatus == ServiceStatus.SUCCESS) { + synchronized (mMyIdentityList) { + mMyIdentityList.clear(); + + for (BaseDataType item : data) { + mMyIdentityList.add((Identity)item); + } + } + } + + pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); + + LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); + } + + /** + * Handle Server response to set validate credentials request. The response + * should be a Status-msg indicating whether the request has succeeded or + * failed. The request is completed with the status result (or + * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a + * Status-msg). + * + * @param data List of BaseDataTypes generated from Server response. + */ + private void handleValidateIdentityCredentials(List<BaseDataType> data) { + Bundle bu = null; + ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); + if (errorStatus == ServiceStatus.SUCCESS) { + mStatusList.clear(); + for (BaseDataType item : data) { + if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { + mStatusList.add((StatusMsg)item); + } else { + completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); + return; + } + } + bu = new Bundle(); + if (mStatusList.size() == 1) { + bu.putBoolean("status", mStatusList.get(0).mStatus); + } else { + LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); + bu.putParcelableArrayList(KEY_DATA, mStatusList); + } + } + completeUiRequest(errorStatus, bu); + + newState(State.IDLE); + + } + + /** + * Handle Server response to set capability status request. The response + * should be a Status-msg indicating whether the request has succeeded or + * failed. The request is completed with the status result (or + * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a + * Status-msg). + * + * @param data List of BaseDataTypes generated from Server response. + */ + private void handleSetIdentityStatus(List<BaseDataType> data) { + Bundle bu = null; + ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); + if (errorStatus == ServiceStatus.SUCCESS) { + mStatusList.clear(); + for (BaseDataType item : data) { + if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { + mStatusList.add((StatusMsg)item); + } else { + completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); + return; + } + } + bu = new Bundle(); + bu.putParcelableArrayList(KEY_DATA, mStatusList); + } + completeUiRequest(errorStatus, bu); + newState(State.IDLE); + } + + /** + * + * Pushes the identities retrieved by get my identities or by get available identities + * to the ui. + * + * @param request The request type: either get my identities, or get available identities. + */ + private void pushIdentitiesToUi(ServiceUiRequest request) { + String requestKey = null; + ArrayList<Identity> idBundle = null; + if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { + requestKey = KEY_AVAILABLE_IDS; + idBundle = mAvailableIdentityList; + } else { + requestKey = KEY_MY_IDS; + idBundle = mMyIdentityList; + } + + // send update to 3rd party identities ui if it is up + Bundle b = new Bundle(); + b.putParcelableArrayList(requestKey, idBundle); + + UiAgent uiAgent = mEventCallback.getUiAgent(); + if (uiAgent != null && uiAgent.isSubscribed()) { + uiAgent.sendUnsolicitedUiEvent(request, b); + } // end: send update to 3rd party identities ui if it is up + } + + /** + * Get Connectivity status from the connection manager. + * + * @return true True if the connection is active, false otherwise. + * + */ + private boolean isConnected() { + int connState = ConnectionManager.getInstance().getConnectionState(); + return (connState == ITcpConnectionListener.STATE_CONNECTED); + } + + /** + * + * Retrieves the filter for the getAvailableIdentities and getMyIdentities + * calls. + * + * @return The identities filter in form of a bundle. + * + */ + private Bundle getIdentitiesFilter() { + Bundle b = new Bundle(); + ArrayList<String> l = new ArrayList<String>(); + l.add(IdentityCapability.CapabilityID.chat.name()); + l.add(IdentityCapability.CapabilityID.get_own_status.name()); + b.putStringArrayList("capability", l); + return b; + } + + @Override + public void onConnectionStateChanged(int state) { + if (state == ITcpConnectionListener.STATE_CONNECTED) { + emptyUiRequestQueue(); + sendGetAvailableIdentitiesRequest(); + sendGetMyIdentitiesRequest(); + } + } + + /** + * Return the next run-time for the IdentitiesEngine. Will run as soon as + * possible if we need to issue a request, or we have a resonse waiting. + * + * @return next run-time. + */ + @Override + public long getNextRunTime() { + if (isUiRequestOutstanding()) { + return 0; + } + if (isCommsResponseOutstanding()) { + return 0; + } + return getCurrentTimeout(); + } + + /** {@inheritDoc} */ + @Override + public void onCreate() { + } + + /** {@inheritDoc} */ + @Override + public void onDestroy() { + } + + /** {@inheritDoc} */ + @Override + protected void onRequestComplete() { + } + + /** {@inheritDoc} */ + @Override + protected void onTimeoutEvent() { + } + + /** + * Generate Map containing boolean capability filters for supplied Bundle. + * + * @param filter Bundle containing filter. + * @return Map containing set of capabilities. + */ + private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { + Map<String, Boolean> objectFilter = null; + if (filter != null && (filter.keySet().size() > 0)) { + objectFilter = new Hashtable<String, Boolean>(); + for (String key : filter.keySet()) { + objectFilter.put(key, filter.getBoolean(key)); + } + } else { + objectFilter = null; + } + return objectFilter; + } + + /** + * Generate Map containing String capability filters for m supplied Bundle. + * + * @param filter Bundle containing filter. + * @return Map containing set of capabilities. + */ + private static Map<String, List<String>> prepareStringFilter(Bundle filter) { + Map<String, List<String>> returnFilter = null; + if (filter != null && filter.keySet().size() > 0) { + returnFilter = new Hashtable<String, List<String>>(); + for (String key : filter.keySet()) { + returnFilter.put(key, filter.getStringArrayList(key)); + } + } else { + returnFilter = null; + } + return returnFilter; + } + + /** + * This method needs to be called as part of removeAllData()/changeUser() + * routine. + */ + /** {@inheritDoc} */ + @Override + public final void onReset() { + if (null != mMyIdentityList) { + mMyIdentityList.clear(); + } + super.onReset(); + } + +}
360/360-Engine-for-Android
b59646ea7c451b3d680a9a4b71a74ee1d8d44283
PAND1933 Application crashes when Me profile is updated
diff --git a/src/com/vodafone360/people/engine/meprofile/SyncMeEngine.java b/src/com/vodafone360/people/engine/meprofile/SyncMeEngine.java index 20ed3c3..cf9728d 100644 --- a/src/com/vodafone360/people/engine/meprofile/SyncMeEngine.java +++ b/src/com/vodafone360/people/engine/meprofile/SyncMeEngine.java @@ -1,684 +1,691 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.meprofile; import java.io.IOException; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.List; import android.content.Context; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ContactSummaryTable; import com.vodafone360.people.database.tables.StateTable; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactChanges; import com.vodafone360.people.datatypes.ContactDetail; import com.vodafone360.people.datatypes.ExternalResponseObject; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.PersistSettings; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Contacts; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.ThumbnailUtils; import com.vodafone360.people.utils.WidgetUtils; /** * This is an implementation for an engine to synchronize * Me profile data. * */ public class SyncMeEngine extends BaseEngine { /** * Current engine state. */ private State mState = State.IDLE; /** * Database. */ private DatabaseHelper mDbHelper; /** * The latest revision of Me Profile. */ private long mFromRevision; /** * The Me Profile, as it was uploaded. */ private ArrayList<ContactDetail> mUploadedMeDetails; /** * Indicates if the first time sync has been ever initiated. */ private boolean mFirstTimeSyncStarted; /** * Indicates if the first time sync has been completed. */ private boolean mFirstTimeMeSyncComplete; /** * UiAgent reference to update progress bar. */ private final UiAgent mUiAgent; /** * ApplicationCache reference to update progress bar. */ private final ApplicationCache mCache; /** * Defines the contact sync mode. The mode determines the sequence in which * the contact sync processors are run. */ private enum State { /** * The state when the engine is not running and has nothing on the todo list. */ IDLE, /** * The state when the engine is downloading Me Profile from server. */ FETCHING_ME_PROFILE_CHANGES, /** * The state when the engine is uploading Me Profile to server. */ UPDATING_ME_PROFILE, /** * The state when the engine is uploading Me Profile status message. */ UPDATING_ME_PRESENCE_TEXT, /** * The state when the engine is downloading Me Profile thumbnail. */ FETCHING_ME_PROFILE_THUMBNAIL, } /** * Percentage used to show progress when the me sync is half complete. */ private static final int PROGRESS_50 = 50; /** * The service context. */ private Context mContext; /** * The constructor. * @param eventCallback IEngineEventCallback * @param db DatabaseHelper - database. */ public SyncMeEngine(final Context context, final IEngineEventCallback eventCallback, DatabaseHelper db) { super(eventCallback); mEngineId = EngineId.SYNCME_ENGINE; mDbHelper = db; mContext = context; mFromRevision = StateTable.fetchMeProfileRevision(mDbHelper.getReadableDatabase()); mUiAgent = mEventCallback.getUiAgent(); mCache = mEventCallback.getApplicationCache(); } @Override public long getNextRunTime() { if (!isReady()) { return -1; } if (mFirstTimeSyncStarted && !mFirstTimeMeSyncComplete && (mState == State.IDLE)) { return 0; } if (isCommsResponseOutstanding()) { return 0; } if (isUiRequestOutstanding()) { return 0; } return getCurrentTimeout(); } /** * The condition for the sync me engine run. * @return boolean - TRUE when the engine is ready to run. */ private boolean isReady() { return EngineManager.getInstance().getLoginEngine().isLoggedIn() && checkConnectivity() && mFirstTimeSyncStarted; } @Override public void run() { LogUtils.logD("SyncMeEngine run"); processTimeout(); if (isCommsResponseOutstanding() && processCommsInQueue()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } if (mFromRevision == 0 && (mState == State.IDLE)) { addGetMeProfileContactRequest(); } } @Override public void onCreate() { PersistSettings setting1 = mDbHelper .fetchOption(PersistSettings.Option.FIRST_TIME_MESYNC_STARTED); PersistSettings setting2 = mDbHelper .fetchOption(PersistSettings.Option.FIRST_TIME_MESYNC_COMPLETE); if (setting1 != null) { mFirstTimeSyncStarted = setting1.getFirstTimeMeSyncStarted(); } if (setting2 != null) { mFirstTimeMeSyncComplete = setting2.getFirstTimeMeSyncComplete(); } } @Override public void onDestroy() { } @Override protected void onRequestComplete() { } @Override protected void onTimeoutEvent() { } @Override protected final void processUiRequest(final ServiceUiRequest requestId, Object data) { switch (requestId) { case UPDATE_ME_PROFILE: uploadMeProfile(); break; case GET_ME_PROFILE: getMeProfileChanges(); break; case UPLOAD_ME_STATUS: uploadStatusUpdate(SyncMeDbUtils.updateStatus(mDbHelper, (String)data)); break; default: // do nothing. break; } } /** * Sends a GetMyChanges request to the server, with the current version of * the me profile used as a parameter. */ private void getMeProfileChanges() { if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { return; } newState(State.FETCHING_ME_PROFILE_CHANGES); setReqId(Contacts.getMyChanges(this, mFromRevision)); } /** * The call to download the thumbnail picture for the me profile. * @param url String - picture url of Me Profile (comes with getMyChanges()) * @param localContactId long - local contact id of Me Profile */ private void downloadMeProfileThumbnail(final String url, final long localContactId) { if (NetworkAgent.getAgentState() == NetworkAgent.AgentState.CONNECTED) { Request request = new Request(url, ThumbnailUtils.REQUEST_THUMBNAIL_URI, engineId()); newState(State.FETCHING_ME_PROFILE_THUMBNAIL); setReqId(QueueManager.getInstance().addRequestAndNotify(request)); } } /** * Starts uploading a status update to the server and ignores all other * @param statusDetail - status ContactDetail */ private void uploadStatusUpdate(final ContactDetail statusDetail) { LogUtils.logE("SyncMeProfile uploadStatusUpdate()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { LogUtils.logE("SyncMeProfile uploadStatusUpdate: no internet connection"); return; } if (statusDetail == null) { LogUtils.logE("SyncMeProfile uploadStatusUpdate: null status can't be posted"); return; } newState(State.UPDATING_ME_PRESENCE_TEXT); List<ContactDetail> details = new ArrayList<ContactDetail>(); statusDetail.updated = null; details.add(statusDetail); setReqId(Contacts.setMe(this, details, null, null)); } /** * * Sends a SetMe request to the server in the case that the me profile has * been changed locally. If the me profile thumbnail has always been changed * it will also be uploaded to the server. */ private void uploadMeProfile() { if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { return; } newState(State.UPDATING_ME_PROFILE); Contact meProfile = new Contact(); mDbHelper.fetchContact(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), meProfile); mUploadedMeDetails = SyncMeDbUtils.saveContactDetailChanges(mDbHelper, meProfile); setReqId(Contacts.setMe(this, mUploadedMeDetails, meProfile.aboutMe, meProfile.gender)); } /** * Get current connectivity state from the NetworkAgent. If not connected * completed UI request with COMMs error. * @return true NetworkAgent reports we are connected, false otherwise. */ private boolean checkConnectivity() { if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return false; } return true; } /** * Changes the state of the engine. * @param newState The new state */ private void newState(final State newState) { State oldState = mState; mState = newState; LogUtils.logV("SyncMeEngine newState(): " + oldState + " -> " + mState); } /** * Called by framework when a response to a server request is received. * @param resp The response received */ public final void processCommsResponse(final DecodedResponse resp) { if (!processPushEvent(resp)) { switch (mState) { case FETCHING_ME_PROFILE_CHANGES: processGetMyChangesResponse(resp); break; case UPDATING_ME_PRESENCE_TEXT: processUpdateStatusResponse(resp); break; case UPDATING_ME_PROFILE: processSetMeResponse(resp); break; case FETCHING_ME_PROFILE_THUMBNAIL: processMeProfileThumbnailResponse(resp); break; default: // do nothing. break; } } } /** * This method stores the thumbnail picture for the me profile * @param resp Response - normally contains ExternalResponseObject for the * picture */ private void processMeProfileThumbnailResponse(final DecodedResponse resp) { + + if (resp.mDataTypes.size()==0){ + LogUtils.logE("SyncMeProfile processMeProfileThumbnailResponse():" + + SystemNotification.SysNotificationCode.EXTERNAL_HTTP_ERROR); + completeUiRequest(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); + return; + + } Contact currentMeProfile = new Contact(); ServiceStatus status = SyncMeDbUtils.fetchMeProfile(mDbHelper, currentMeProfile); if (status == ServiceStatus.SUCCESS) { if (resp.mReqId == null || resp.mReqId == 0) { - if (resp.mDataTypes.size() > 0 - && resp.mDataTypes.get(0).getType() == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE + if (resp.mDataTypes.get(0).getType() == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE && ((SystemNotification)resp.mDataTypes.get(0)).getSysCode() == SystemNotification.SysNotificationCode.EXTERNAL_HTTP_ERROR) { LogUtils.logE("SyncMeProfile processMeProfileThumbnailResponse():" + SystemNotification.SysNotificationCode.EXTERNAL_HTTP_ERROR); } completeUiRequest(status); return; } else if (resp.mDataTypes.get(0).getType() == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { if (((SystemNotification)resp.mDataTypes.get(0)).getSysCode() == SystemNotification.SysNotificationCode.EXTERNAL_HTTP_ERROR) { LogUtils.logE("SyncMeProfile processMeProfileThumbnailResponse():" + SystemNotification.SysNotificationCode.EXTERNAL_HTTP_ERROR); } completeUiRequest(status); return; } status = BaseEngine .getResponseStatus(BaseDataType.EXTERNAL_RESPONSE_OBJECT_DATA_TYPE, resp.mDataTypes); if (status != ServiceStatus.SUCCESS) { completeUiRequest(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); LogUtils .logE("SyncMeProfile processMeProfileThumbnailResponse() - Can't read response"); return; } if (resp.mDataTypes == null || resp.mDataTypes.isEmpty()) { LogUtils .logE("SyncMeProfile processMeProfileThumbnailResponse() - Datatypes are null"); completeUiRequest(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); return; } // finally save the thumbnails ExternalResponseObject ext = (ExternalResponseObject)resp.mDataTypes.get(0); if (ext.mBody == null) { LogUtils.logE("SyncMeProfile processMeProfileThumbnailResponse() - no body"); completeUiRequest(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); return; } try { ThumbnailUtils.saveExternalResponseObjectToFile(currentMeProfile.localContactID, ext); ContactSummaryTable.modifyPictureLoadedFlag(currentMeProfile.localContactID, true, mDbHelper.getWritableDatabase()); mDbHelper.markMeProfileAvatarChanged(); } catch (IOException e) { LogUtils.logE("SyncMeProfile processMeProfileThumbnailResponse()", e); completeUiRequest(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); } } completeUiRequest(status); } /** * Processes the response from a GetMyChanges request. The me profile data * will be merged in the local database if the response is successful. * Otherwise the processor will complete with a suitable error. * @param resp Response from server. */ private void processGetMyChangesResponse(final DecodedResponse resp) { LogUtils.logD("SyncMeEngine processGetMyChangesResponse()"); ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.CONTACT_CHANGES_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { ContactChanges changes = (ContactChanges)resp.mDataTypes.get(0); Contact currentMeProfile = new Contact(); status = SyncMeDbUtils.fetchMeProfile(mDbHelper, currentMeProfile); switch (status) { case SUCCESS: String url = SyncMeDbUtils.updateMeProfile(mDbHelper, currentMeProfile, changes.mUserProfile); if (url != null) { downloadMeProfileThumbnail(url, currentMeProfile.localContactID); } else { completeUiRequest(status); } break; case ERROR_NOT_FOUND: // this is the 1st time sync currentMeProfile.copy(changes.mUserProfile); status = SyncMeDbUtils.setMeProfile(mDbHelper, currentMeProfile); mFromRevision = changes.mCurrentServerVersion; StateTable.modifyMeProfileRevision(mFromRevision, mDbHelper .getWritableDatabase()); setFirstTimeMeSyncComplete(true); completeUiRequest(status); break; default: completeUiRequest(status); } } else { completeUiRequest(status); } } /** * Processes the response from a SetMe request. If successful, the server * IDs will be stored in the local database if they have changed. Otherwise * the processor will complete with a suitable error. * @param resp Response from server. */ private void processSetMeResponse(final DecodedResponse resp) { LogUtils.logD("SyncMeProfile.processMeProfileUpdateResponse()"); ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.CONTACT_CHANGES_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { ContactChanges result = (ContactChanges) resp.mDataTypes.get(0); SyncMeDbUtils.updateMeProfileDbDetailIds(mDbHelper, mUploadedMeDetails, result); if (updateRevisionPostUpdate(result.mServerRevisionBefore, result.mServerRevisionAfter, mFromRevision, mDbHelper)) { mFromRevision = result.mServerRevisionAfter; } } completeUiRequest(status); } /** * This method processes the response to status update by setMe() method * @param resp Response - the expected response datatype is ContactChanges */ private void processUpdateStatusResponse(final DecodedResponse resp) { LogUtils.logD("SyncMeDbUtils processUpdateStatusResponse()"); ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.CONTACT_CHANGES_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { ContactChanges result = (ContactChanges) resp.mDataTypes.get(0); LogUtils.logI("SyncMeProfile.processUpdateStatusResponse() - Me profile userId = " + result.mUserProfile.userID); SyncMeDbUtils.savePresenceStatusResponse(mDbHelper, result); } completeUiRequest(status); } @Override protected void completeUiRequest(ServiceStatus status) { super.completeUiRequest(status); newState(State.IDLE); WidgetUtils.kickWidgetUpdateNow(mContext); } /** * Updates the revision of the me profile in the local state table after the * SetMe has completed. This will only happen if the version of the me * profile on the server before the update matches our previous version. * @param before Version before the update * @param after Version after the update * @param currentFromRevision Current version from our database * @param db Database helper used for storing the change * @return true if the update was done, false otherwise. */ private static boolean updateRevisionPostUpdate(final Integer before, final Integer after, final long currentFromRevision, final DatabaseHelper db) { if (before == null || after == null) { return false; } if (!before.equals(currentFromRevision)) { LogUtils .logW("SyncMeProfile.updateRevisionPostUpdate - Previous version is not as expected, current version=" + currentFromRevision + ", server before=" + before + ", server after=" + after); return false; } else { StateTable.modifyMeProfileRevision(after, db.getWritableDatabase()); return true; } } /** * This method adds an external request to Contacts/setMe() method to update * the Me Profile... * @param meProfile Contact - contact to be pushed to the server */ public void addUpdateMeProfileContactRequest() { LogUtils.logV("SyncMeEngine addUpdateMeProfileContactRequest()"); addUiRequestToQueue(ServiceUiRequest.UPDATE_ME_PROFILE, null); } /** * This method adds an external request to Contacts/setMe() method to update * the Me Profile status... * @param textStatus String - the new me profile status to be pushed to the * server */ public void addUpdateMyStatusRequest(String textStatus) { LogUtils.logV("SyncMeEngine addUpdateMyStatusRequest()"); addUiRequestToQueue(ServiceUiRequest.UPLOAD_ME_STATUS, textStatus); } /** * This method adds an external request to Contacts/getMyChanges() method to * update the Me Profile status server. Is called when "pc "push message is * received */ private void addGetMeProfileContactRequest() { LogUtils.logV("SyncMeEngine addGetMeProfileContactRequest()"); addUiRequestToQueue(ServiceUiRequest.GET_ME_PROFILE, null); } /** * This method adds an external request to Contacts/getMyChanges() method to * update the Me Profile status server, is called by the UI at the 1st sync. */ public void addGetMeProfileContactFirstTimeRequest() { LogUtils.logV("SyncMeEngine addGetMeProfileContactFirstTimeRequest()"); setFirstTimeSyncStarted(true); addUiRequestToQueue(ServiceUiRequest.GET_ME_PROFILE, null); } /** * This method process the "pc" push event. * @param resp Response - server response normally containing a "pc" * PushEvent data type * @return boolean - TRUE if a push event was found in the response */ private boolean processPushEvent(final DecodedResponse resp) { if (resp.mDataTypes == null || resp.mDataTypes.size() == 0) { return false; } BaseDataType dataType = resp.mDataTypes.get(0); if ((dataType == null) || dataType.getType() != BaseDataType.PUSH_EVENT_DATA_TYPE) { return false; } PushEvent pushEvent = (PushEvent) dataType; LogUtils.logV("SyncMeEngine processPushMessage():" + pushEvent.mMessageType); switch (pushEvent.mMessageType) { case PROFILE_CHANGE: addGetMeProfileContactRequest(); break; default: break; } return true; } /** * Helper function to update the database when the state of the * {@link #mFirstTimeMeSyncStarted} flag changes. * @param value New value to the flag. True indicates that first time sync * has been started. The flag is never set to false again by the * engine, it will be only set to false when a remove user data * is done (and the database is deleted). * @return SUCCESS or a suitable error code if the database could not be * updated. */ private ServiceStatus setFirstTimeSyncStarted(final boolean value) { if (mFirstTimeSyncStarted == value) { return ServiceStatus.SUCCESS; } PersistSettings setting = new PersistSettings(); setting.putFirstTimeMeSyncStarted(value); ServiceStatus status = mDbHelper.setOption(setting); if (ServiceStatus.SUCCESS == status) { synchronized (this) { mFirstTimeSyncStarted = value; } } return status; } /** * Helper function to update the database when the state of the * {@link #mFirstTimeMeSyncComplete} flag changes. * @param value New value to the flag. True indicates that first time sync * has been completed. The flag is never set to false again by * the engine, it will be only set to false when a remove user * data is done (and the database is deleted). * @return SUCCESS or a suitable error code if the database could not be * updated. */ private ServiceStatus setFirstTimeMeSyncComplete(final boolean value) { if (mFirstTimeMeSyncComplete == value) { return ServiceStatus.SUCCESS; } PersistSettings setting = new PersistSettings(); setting.putFirstTimeMeSyncComplete(value); ServiceStatus status = mDbHelper.setOption(setting); if (ServiceStatus.SUCCESS == status) { synchronized (this) { mFirstTimeMeSyncComplete = value; } } return status; } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ /** {@inheritDoc} */ @Override public final void onReset() { mFirstTimeMeSyncComplete = false; mFirstTimeSyncStarted = false; mFromRevision = 0; super.onReset(); } /** * This method TRUE if the Me Profile has been synced once. * @return boolean - TRUE if the Me Profile has been synced once. */ public final boolean isFirstTimeMeSyncComplete() { return mFirstTimeMeSyncComplete; } }
360/360-Engine-for-Android
abe7575a521620a9ce99b4d62b2d50cb17730ae0
just copied over a resource so that the engine compiles standalone. no review needed.
diff --git a/res/values/strings.xml b/res/values/strings.xml index 38e811d..2497693 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -129,514 +129,515 @@ <!-- Server Prompts [dialog_scroll_view.xml + progress_layout.xml] --> <string name="ProgressLayout_waiting_for_server">Processing...</string> <!-- [edit_contact.xml] -> EditPhoneticName [edit_phonetic_name.xml] --> <!-- The label describing the phonetic pronunciation/reading of a contact name --> <string name="EditPhoneticName_label_phonetic_name">Phonetic</string> <!-- Hint text for the phonetic reading of the contact name when editing --> <string name="EditPhoneticName_ghostData_phonetic_name">Phonetic name</string> <!-- .ui.contacts.EditContactActivity [edit_contact.xml] --> <!-- Hint text for the contact name when editing --> <string name="EditContactActivity_ghostData_name">First and Last</string> <!-- Menu item to indicate you are done editing a contact and want to save the changes you've made --> <string name="EditContactActivity_menu_done">Done</string> <!-- Menu item to indicate you want to stop editing a contact and NOT save the changes you've made --> <string name="EditContactActivity_menu_doNotSave">Cancel</string> <!-- .ui.startup.EnterMobileNumberActivity [enter_phone_number_manually.xml] --> <string name="SignupEnterMobileNumberActivity_problem_getting_deviceinfo">Mobile number</string> <string name="SignupEnterMobileNumberActivity_device_problem_explanation">Please enter your mobile number.</string> <string name="SignupEnterMobileNumberActivity_use_international_format">Use international format eg. +447700900999</string> <!-- .ui.contacts.EditContactActivity --> <!-- Toast message when a user tries to add a contact to a group which they are already a member --> <string name="group_member">This contact is already in </string> <!-- dynamic 'group' --> <!-- Section header in the Edit Contacts screen for dates --> <string name="listSeparatorDates">Birthday</string> <!-- Section header in the Edit Contacts screen for bookmarks --> <string name="ghostData_company">Company</string> <string name="ghostData_title">Job title</string> <string name="ghostData_dept">Department</string> <string name="ghostData_url">Website</string> <string name="label_url">Website</string> <string name="label_date">Birthday</string> <string name="label_notes">Notes</string> <string name="ghostData_notes">My note</string> <string name="ghostData_phone">Phone number</string> <string name="ghostData_postal_address_line1">Address line 1</string> <string name="ghostData_postal_address_line2">Address line 2</string> <string name="ghostData_postal_city">City</string> <string name="ghostData_postal_postcode">Post code</string> <string name="ghostData_postal_county">County</string> <string name="ghostData_postal_country">Country</string> <string name="ghostData_email">Email address</string> <string name="ghostData_date">Birthday</string> <string name="cancel">Cancel</string> <string name="contactSavedToast">Contact saved</string> <string name="selectTypeLabel">Choose label</string> <string name="selectLabel">Add contact to a group</string> <string name="removePicture">Remove icon</string> <string name="addPicture">Add icon</string> <string name="errorDialogTitle">No pictures</string> <string name="photoPickerNotFoundText">No pictures are available on the phone.</string> <string name="contactCreatedToast">Contact created.</string> <string name="editContact_title_edit">Edit contact</string> <string name="editContact_title_insert">New contact</string> <string name="customLabelPickerTitle">Custom label name</string> <!-- Separator in the contact details list describing that the items below it will place a call when clicked --> <string name="listSeparatorCallNumber">Call</string> <!-- Section header in the Edit Contacts screen for phone numbers --> <string name="listSeparatorCallNumber_edit">Phone numbers</string> <!-- Separator in the contact details list describing that the items below it will send an SMS/MMS to a phone number--> <string name="listSeparatorSendSmsMms">Send text message</string> <!-- Separator in the contact details list describing that the items below it will send an email --> <string name="listSeparatorSendEmail">Send email</string> <!-- Section header in the Edit Contacts screen for E-mail addresses --> <string name="listSeparatorSendEmail_edit">Email addresses</string> <!-- Separator in the contact details list describing that the items below it will send an IM --> <string name="listSeparatorSendIm">Chat</string> <!-- Section header in the Edit Contacts screen for Instant messanger accounts, should not display in Edit contact details --> <string name="listSeparatorSendIm_edit">Chat accounts</string> <!-- Separator in the contact details list describing that the items below it will open maps with the given address --> <string name="listSeparatorMapAddress">Map address</string> <!-- Section header in the Edit Contacts screen for map addresses --> <string name="listSeparatorMapAddress_edit">Addresses</string> <!-- Separator in the contact details list describing that the items below are non-actionable organization information --> <string name="listSeparatorOrganizations">Work Info</string> <!-- Section header in the Edit Contacts screen for other options, such as setting ringtone --> <string name="listSeparatorOtherInformation_edit">Other options</string> <!-- Section header in the Edit Contacts screen for the "Add more items" button --> <string name="listSeparatorMore_edit">More</string> <!-- Section header in the Edit Contacts screen for URLs --> <string name="listSeparatorUrls">Websites</string> <!-- Section header in the Edit Contacts screen for social network accounts --> <string name="listSeparatorSocialNetworks">Accounts</string> <!-- Section header in the Edit Contacts screen for contact groups --> <string name="listSeparatorGroups">Groups</string> <!-- Detail type in Edit Contacts --> <string name="EditContactActivity_detail_type_home">Home</string> <!-- Detail type in Edit Contacts --> <string name="EditContactActivity_detail_type_mobile">Mobile</string> <!-- Detail type in Edit Contacts --> <string name="EditContactActivity_detail_type_work">Work</string> <!-- Detail type in Edit Contacts --> <string name="EditContactActivity_detail_type_work_fax">Work Fax</string> <!-- Detail type in Edit Contacts --> <string name="EditContactActivity_detail_type_other">Other</string> <string name="EditContactActivity_age_check">You must be at least 14 years old to use Vodafone 360 People.</string> <!-- .engine.login.LoginEngine --> <string name="login_required_notification">Please log in to 360 People</string> <string name="login_notification_label">360 People</string> <!-- .ui.startup.signup.SignupCreateAccountDetailsActivity [wizard_signup.xml] --> <string name="SignupCreateAccountDetailsActivity_create_new_nowplus_account">360 People Set-up</string> <string name="SignupCreateAccountDetailsActivity_hint_firstname">First name</string> <string name="SignupCreateAccountDetailsActivity_hint_lastname">Last name</string> <string name="SignupCreateAccountDetailsActivity_hint_email_address">Email address</string> <string name="SignupCreateAccountDetailsActivity_privacy_statement"><u>Privacy statement</u></string> <!-- .ui.tabs.StartTabsActivity --> <string name="contactmain_contacts">Contacts</string> <string name="contactmain_dialerIconLabel">Dialer</string> <string name="contactmain_recentCallsIconLabel">Timeline</string> <string name="contactmain_statusIconLabel">Status</string> <string name="contactmain_pleaseWait">Please wait while Timeline finishes loading</string> <!-- .ui.tabs.TwelveKeyDialer --> <string name="dialer_addAnotherCall">Add call</string> <string name="dialer_useDtmfDialpad">Use touch tone keypad</string> <string name="dialer_returnToInCallScreen">Return to call in progress</string> <string name="dialerDialpadHintText">Dial to add a call</string> <!-- .ui.timeline.TimelinelistActivity, .ui.timeline.TimelineHistoryActivity --> <string name="RecentCallsListActivity_unknown">Unknown</string> <string name="RecentCallsListActivity_callNumber">Call %s</string> <string name="RecentCallsListActivity_addToContact">Add to contacts</string> <string name="RecentCallsListActivity_deleteAll">Clear Timeline</string> <string name="RecentCallsListActivity_editNumberBeforeCall">Edit number before call</string> <string name="RecentCallsListActivity_payphone">Pay phone</string> <string name="RecentCallsListActivity_removeFromRecentList">Remove from Timeline</string> <string name="RecentCallsListActivity_private_num">Private number</string> <string name="RecentCallsListActivity_voicemail">Voicemail</string> <string name="RecentCallsListActivity_empty">Timeline is empty.</string> <!-- .ui.timeline.TimelineListActivity --> <string name="TimelineListActivity_filter_all">All</string> <string name="TimelineListActivity_button_more">Load more</string> <string name="TimelineListActivity_filter_call_log">Calls</string> <string name="TimelineListActivity_filter_sms_mms">Messages</string> <string name="TimelineListActivity_filter_chat">Chat</string> <string name="TimelineListActivity_empty_calls">No calls</string> <string name="TimelineListActivity_empty_messages">No messages</string> <string name="TimelineListActivity_no_contact_name">Unknown</string> <string name="menu_sendTextMessage">Send text message</string> <!-- .ui.timeline.TimelineHistoryActivity [timeline_history.xml] --> <string name="TimelineHistory_noHistory">No history available</string> <string name="TimelineHistory_composer_edit_hint">Compose message...</string> <string name="TimelineHistoryActivity_forward">Forward</string> <string name="TimelineHistoryActivity_copy">Copy</string> <string name="TimelineHistoryActivity_button_send">Send</string> <string name="TimelineHistoryActivity_sending_message">Sending message</string> <string name="TimelineHistoryActivity_contact_offline">Contact appears offline</string> <!-- .ui.timeline.TimelineHistoryActivity [timeline_history_menu.xml] --> <string name="TimelineHistoryActivity_menu_call">Call</string> <string name="TimelineHistoryActivity_menu_view_profile">View contact</string> <string name="TimelineHistoryActivity_menu_add_contact">Add contact</string> <string name="TimelineHistoryActivity_menu_goto_timeline">Timeline</string> <!-- .ui.timeline.TimelineListActivity, .ui.timeline.ContactStatusListActivity --> <string name="menu_viewContact">View profile</string> <!-- .ui.contacts.ContactListActivity --> <string name="ContactListActivity_fast_scroll_alphabet">\u0020ABCDEFGHIJKLMNOPQRSTUVWXYZ</string> <string name="ContactListActivity_filter_progress">Filtering</string> <string name="ContactListActivity_group_all">All</string> <string name="ContactListActivity_group_phonebook">Phonebook</string> <string name="ContactListActivity_group_online">Online</string> <string name="ContactListActivity_MenuItem_checkForUpdates">Check for updates</string> <string name="ContactListActivity_noContactsHelpText">"You don\'t have any contacts.\n\nTo add contacts, press <b>Menu</b> and select:\n \n<li><b>Add contact</b> to create a new contact from scratch\n</li></string> <string name="pickerNewContactHeader">Create new contact</string> <string name="ContactListActivity_removedata_progress">Removing user data...</string> <string name="ContactListActivity_select_group">%s (%s)</string> <string name="ContactListActivity_no_me_profile_name">Me</string> <!-- .ui.contacts.ContactListActivity [contact_list.xml] --> <string name="ContactListActivity_TextView_noContacts">No contacts.</string> <!-- .ui.contacts.ContactListActivity [contact_list_menu.xml] --> <string name="ContactListActivity_MenuItem_searchContacts">Search</string> <string name="ContactListActivity_MenuItem_addContact">Add contact</string> <string name="ContactListActivity_MenuItem_settings">Settings</string> <string name="ContactListActivity_MenuItem_datasettings">Data settings</string> <string name="ContactListActivity_MenuItem_sendemail">Send Email</string> <string name="ContactListActivity_MenuItem_nowplusPrivacy">Privacy</string> <string name="ContactListActivity_MenuItem_nowplusAbout">About</string> <string name="ContactListActivity_MenuItem_nowplusHelp">Help</string> <string name="ContactListActivity_MenuItem_nowplusTerms">Terms &amp; Conditions</string> <string name="ContactListActivity_MenuItem_nowplusRemoveUserData">Change user</string> <string name="ContactListActivity_MenuItem_nowplusToggleRoaming">Toggle Roaming</string> <string name="ContactListActivity_MenuItem_nowplusWebAccounts">Accounts</string> <!-- .ui.contacts.ContactListActivity [contact_list_context_menu.xml] --> <string name="ContactListActivity_MenuItem_viewContact">View contact</string> <string name="ContactListActivity_MenuItem_phoneContact">Call %s</string> <string name="ContactListActivity_MenuItem_smsContact">Send text message</string> <string name="ContactListActivity_MenuItem_editContact">Edit contact</string> <string name="ContactListActivity_MenuItem_deleteContact">Delete contact</string> <!-- .ui.contacts.ContactProfile [contact_profile.xml] --> <string name="ContactProfile_TextView_noDetailsHelpText">"You haven\'t added any details for this contact.\n\nTo add details, press <b>Menu</b> and select:\n \n<li><b>Edit profile</b> to add some new details\n</li></string> <string name="ContactProfile_EditText_Status_Hint">What are you up to right now?</string> <string name="ContactProfile_Button_Status">Update</string> <string name="menu_editProfile">Edit contact</string> <string name="menu_editContact">Edit contact</string> <string name="menu_deleteContact">Delete contact</string> <string name="contact_detail_location_map">maps</string> <!-- .ui.contacts.ContactStatusListActivity --> <string name="ContactStatusListActivity_button_update_state">update</string> <string name="ContactStatusListActivity_what_are_you_doing">What are you doing?</string> <string name="ContactStatusListActivity_update_status_on_hyves_and_facebook">Your status will be posted to both \n Hyves and Facebook.</string> <string name="ContactStatusListActivity_update_status_on_facebook">Your status will be posted to Facebook.</string> <string name="ContactStatusListActivity_update_status_on_hyves">Your status will be posted to Hyves.</string> <string name="ContactStatusListActivity_ToastStatusUpdated">Status updated</string> <string name="ContactStatusListActivity_filter_progress">Loading</string> <string name="ContactStatusListActivity_fast_scroll_alphabet">\u0020ABCDEFGHIJKLMNOPQRSTUVWXYZ</string> <string name="ContactStatusListActivity_TextView_noStatusUpdates">Status messages are loading, this may take a few minutes if you are using the application for the first time.</string> <string name="ContactStatusListActivity_error_updating_status">Your status was not updated. Please try again later.</string> <string name="ContactStatusListActivity_button_refresh_text">Refresh</string> <string name="ContactStatusListActivity_button_more_text">Load more</string> <!-- .ui.contacts.ContactProfileActivity --> <string name="ContactProfile_setpreferred_phone">Set preferred number</string> <string name="ContactProfile_setpreferred_email">Set preferred email</string> <string name="ContactProfile_call_number">Call %s</string> <string name="ContactProfile_send_sms">Send text message</string> <string name="ContactProfile_send_email">Send Email</string> <string name="ContactProfile_chat">Chat</string> <string name="ContactProfile_birthday">Birthday: %s</string> <string name="ContactProfile_available">available</string> <string name="ContactProfile_invisible">invisible</string> <string name="UiUtils_detail_aboutme">About Me</string> <string name="ContactProfile_no_connection">No network connection available!</string> <!-- .ui.settings.AboutActivity [about.xml] --> <string name="about_nowplus">Vodafone 360 People for Android</string> <string name="about_nowplus2">Version</string> <string name="about_nowplus_info">About 360 People \n360 People is a service for your phone, PC and Mac(tm) which keeps you in sync with your friends. It brings together everything you need to communicate with the people that matter to you in a single easily accessible place.\n \n360 People is open to everyone, you don\'t have to be a Vodafone customer to join the community.\n \nCopyright (c) 2010 Vodafone Limited. \nhttp://www.vodafone.com/about\n \nSupport Email:\[email protected]\n \nMedia Enquiries:\nContact Group Media Relations on:\n+44 (0) 1635 664 444</string> <!-- .ui.settings.NetworkSettingsActivity [network_settings.xml] --> <string name="dataSettings_button_change_romaming_settings">Change roaming settings</string> <string name="dataSettings_content">\nPlaceholder for statistics\n</string> <string name="dataSettings_nowplus_data_sync">People Data Synchronisation ...</string> <string name="dataSettings_option_roaming">Always on</string> <string name="dataSettings_option_off">Off</string> <string name="dataSettings_title">Data Settings</string> <string name="dataSettings_statistics">Statistics</string> <string name="dataSettings_data_connection">Data connection</string> <string name="dataSettings_global_roaming">Global roaming</string> <string name="dataSettings_data_connection_content">360 People uses your phone\'s data connection, even when it is in the background.</string> <string name="dataSettings_roaming_state_on">Roaming is currently turned on.</string> <string name="dataSettings_roaming_state_off">Roaming is currently turned off.</string> <string name="login_succesful_title">You are now logged in to 360 People</string> <string name="signup_succesful_title">You are now signed up and logged in to 360 People</string> <!-- .ui.startup.signup.SignupLoginServerActivity [creating_your_account1.xml] --> <string name="SignupMobileNumberActivity_creating_your_account">Creating your account ...</string> <string name="sign_up_creating_your_account">Creating Your account ...</string> <!-- .ui.utils.UiUtils --> <string name="UiUtils_service_err_success">The operation has completed successfully</string> <string name="UiUtils_service_err_cancelled">The operation has been cancelled</string> <string name="UiUtils_service_err_comms">Sorry, there was a problem trying to connect. Please try again later.</string> <string name="UiUtils_service_err_bad_parameter">An internal error has occurred (bad parameter)</string> <string name="UiUtils_service_err_comms_timeout">Sorry, there was a problem trying to connect. Please try again later.</string> <string name="UiUtils_service_err_in_use">An internal error has occurred (in use)</string> <string name="UiUtils_service_err_disconnected">Sorry, there was a problem trying to connect. Please try again later.</string> <string name="UiUtils_service_err_account_activation_failed">Sorry, we could not activate your account. Please try again.</string> <string name="UiUtils_service_err_invalid_dob">Please try entering your date of birth again.</string> <string name="UiUtils_service_err_username_in_use">Username is already in use</string> <string name="UiUtils_service_err_not_ready">An internal error has occurred (not ready)</string> <string name="UiUtils_service_err_auth_failed">Sorry, there was a problem while logging in. Please try again.</string> <string name="UiUtils_service_err_not_logged_in">Sorry, you are not logged in. Try logging in again.</string> <string name="UiUtils_service_err_no_internet">There may be a problem with the data connection. Please try again later.</string> <string name="UiUtils_service_err_internet_disallowed">Internet access is not permitted</string> <string name="UiUtils_service_err_invalid_session">You were logged out of People. Please log in again.</string> <string name="UiUtils_service_err_user_not_found">User could not be found</string> <string name="UiUtils_service_err_username_missing">Please enter a username.</string> <string name="UiUtils_service_err_username_blacklisted">The username you have chosen can not be used in 360 People. Please try a different username.</string> <string name="UiUtils_service_err_username_forbidden">The username you have chosen can not be used in 360 People. Please try a different username.</string> <string name="UiUtils_service_err_username_invalid">The username entered is invalid.</string> <string name="UiUtils_service_err_fullname_missing">Please enter your first and last name.</string> <string name="UiUtils_service_err_invalid_password">Your username or password is not correct. Please try logging in again.</string> <string name="UiUtils_service_err_password_missing">Please enter your password.</string> <string name="UiUtils_service_err_tc_missing">Sorry, you can not use People without agreeing to the Terms &amp; Conditions.</string> <string name="UiUtils_service_err_email_missing">Please enter your email address.</string> <string name="UiUtils_service_err_country_invalid">Country is invalid</string> <string name="UiUtils_service_err_msisdn_missing">Please enter your mobile number.</string> <string name="UiUtils_service_err_msisdn_invalid">Please enter your mobile number using international format.</string> <string name="UiUtils_service_err_timezone_missing">Please select your Timezone</string> <string name="UiUtils_service_err_timezone_invalid">Please select your Timezone</string> <string name="UiUtils_service_err_mobile_operator_invalid">Please select your Mobile operator</string> <string name="UiUtils_service_err_mobile_model_invalid">Please select your Mobile model</string> <string name="UiUtils_service_err_language_invalid">Language is invalid</string> <string name="UiUtils_service_err_invalid_code">Activation code is invalid</string> <string name="UiUtils_service_err_no_service_response">Sorry, there was a problem trying to connect. Please try again later.</string> <string name="UiUtils_service_err_not_implemented">The required functionality is not available</string> <string name="UiUtils_service_err_unexpected_response">Sorry, there was a problem trying to connect. Please try again later.</string> <string name="UiUtils_service_err_database_corrupt">A database error has occurred</string> <string name="UiUtils_service_err_comms_bad_response">The server responded with invalid data</string> <string name="UiUtils_service_err_sms_code_not_received">Please check if the mobile number is correct.</string> <string name="UiUtils_service_err_not_found">The item could not be found</string> <string name="UiUtils_service_err_internal_server">An internal error has occurred on the server</string> <string name="UiUtils_service_err_unknown">An internal error has occurred</string> <string name="UiUtils_service_err_internet_romaing_not_allowed">Internet connection while roaming is not allowed</string> <string name="UiUtils_service_err_sync_failed">A general error occurred during the contact sync</string> <string name="UiUtils_service_err_already_exists">The item already exists</string> <string name="UiUtils_service_err_out_of_memory">Sorry, there was a problem trying to connect. Please try again later.</string> <string name="UiUtils_service_err_chat_notsent">Your chat message has not been sent. Please retry later.</string> <string name="UiUtils_service_message_no_more_items">No more items.</string> <string name="UiUtils_detail_bookmark">Bookmark</string> <string name="UiUtils_detail_external">External</string> <string name="UiUtils_detail_folder">Folder</string> <string name="UiUtils_detail_gender">Gender</string> <string name="UiUtils_detail_interest">Interest</string> <string name="UiUtils_detail_link">Link</string> <string name="UiUtils_detail_location">Location</string> <string name="UiUtils_detail_presence_status">Presence status</string> <string name="UiUtils_detail_presence_text">Presence text</string> <string name="UiUtils_detail_relation">Relation</string> <string name="UiUtils_detail_unknown">Unknown</string> <string name="UiUtils_detail_name">Name</string> <string name="UiUtils_detail_note">Note</string> <string name="UiUtils_detail_group">Group</string> <string name="UiUtils_detail_photo">Photo</string> <string name="UiUtils_detail_address">Addresses</string> <string name="UiUtils_detail_date">Birthday</string> <string name="UiUtils_detail_email">Email</string> <string name="UiUtils_detail_social_network">Accounts</string> <string name="UiUtils_detail_im">Chat</string> <string name="UiUtils_detail_nickname">Nickname</string> <string name="UiUtils_detail_org">Company</string> <string name="UiUtils_detail_phone">Phone</string> <string name="UiUtils_detail_dept">Department</string> <string name="UiUtils_detail_title">Title</string> <string name="UiUtils_detail_role">Role</string> <string name="UiUtils_detail_url">Website</string> <string name="UiUtils_detail_none">None</string> <string name="UiUtils_detail_home">Home</string> <string name="UiUtils_detail_work">Work</string> <string name="UiUtils_detail_other">Other</string> <string name="UiUtils_detail_mobile">Mobile</string> <string name="UiUtils_detail_cell">Mobile</string> <string name="UiUtils_detail_fax">Fax</string> <string name="UiUtils_detail_birthday">Birthday</string> <string name="UiUtils_DialogDataDeleteWarningText">This will remove all data from this application? Do you want to continue?</string> <string name="UiUtils_DialogDataDeleteWarningTitle">Change user?</string> <string name="UiUtils_DialogDataWarningDelete">Continue</string> <string name="UiUtils_DialogDataWarningCancel">Cancel</string> <string name="UiUtils_DialogDataDeleteConfirmationText">Are you sure you want to delete all data from this application? \nThis is can not be undone.</string> <string name="UiUtils_DialogDataDeleteTitle">Confirm Delete</string> <string name="UiUtils_DialogDataDeleteYes">Delete</string> <string name="UiUtils_DialogDataDeleteNo">Cancel</string> <string name="UiUtils_Toast_AllDataRemoved">All data has been removed from this application.</string> <string name="deleteConfirmation_title">Delete</string> <string name="deleteConfirmation">This contact will be deleted.</string> <!-- .service.agent.NetworkAgent --> <string name="service_roaming_notification">You are roaming and data charges might be expensive.</string> <string name="service_roaming_notification_label">Roaming</string> <!-- .service.agent.UiAgent --> <string name="UiAgent_Notification_new_messages">New messages</string> <string name="UiAgent_Notification_unread_messages">%S unread messages.</string> <!-- .ui.utils.RoamingNotificationActivity [dialog_roaming.xml] --> <string name="roaming_dialog_title">Roaming</string> <string name="roaming_dialog_text_for_global_off">You are roaming and your global roaming setting is turned off. \n\n If you want to continue using the data connection please change your roaming settings. You may incur additional data charges.</string> <string name="roaming_dialog_text_for_global_on">You are roaming and your global roaming setting is turned on. \n\n If You want to continue using the data connection you may incur additional data charges. Please change your roaming settings if you do not want to connect.</string> <string name="roaming_dialog_dont_ask_me_box">Don\'t ask me again for 24 hours</string> <string name="roaming_dialog_button_change_settings">Change settings</string> <string name="roaming_dialog_button_do_not_change_settings">Do not change settings</string> <!-- .ui.thirdparty.ThirdPartyAccountsActivity [third_party_accounts.xml]--> <string name="add_accounts_title">Import contacts</string> <string name="android_contacts">Your phone\'s address book will be backed up and synced</string> <string name="more_web_accounts">Accounts</string> <string name="third_party_add_new_account_seletion_title">Available accounts</string> <string name="third_party_all">All</string> <string name="third_party_add_account">Add new account</string> <string name="third_party_adding_success"> added</string> <!-- dynamic "[web account] added" --> <string name="third_party_applying_changes">Getting ready to sync...</string> <string name="third_party_favourites">Favourites</string> <string name="third_party_setup">%s setup</string> <string name="third_party_web_accounts_title">Accounts</string> <string name="third_party_hint_username">username/email</string> <string name="third_party_hint_password">password</string> <string name="third_party_validation_waiting_text">Checking %s account</string> <string name="third_party_account_placeholder">Unnamed Account</string> <string name="getting_third_party_accounts">Getting accounts...</string> <string name="third_party_account_error_title">Problem</string> <string name="validating_third_party_account">Logging into %S</string> <!-- "Signing into [web account]" --> <string name="third_party_account_validation_error">There was a problem logging into %S. Please check if your username and password are correct.</string> <string name="third_party_account_info_title">Information</string> <string name="third_party_account_info_cannot_break_message_text">We are in the middle of processing important data. This process cannot be interrupted. Please be patient, it may take a while.</string> <string name="third_party_account_error_message_text">There was a problem getting information. Please try again later.</string> <!-- [account] --> <string name="account">Account ...</string> <!-- .ui.startup.login.LoginAccountDetailsActivity --> <string name="text_login">Login</string> <string name="forgot_credentials">Forgot credentials</string> <string name="forgot_credentials_info">Please go to Vodafone 360 on the web to retrieve your credentials\n</string> <string name="forgot_credentials_info_web_link">http://www.vodafone360.com</string> <string name="forgot_credentials_info_web_link_text"><u>Vodafone 360 People</u></string> <!-- .ui.debug.PresenceViewActivity --> <string name="PresenceViewActivity_TextView_title">Presence info</string> <!-- .ui.startup.login.LoginAccountServerActivity --> <string name="signing_in">Logging in ...</string> <string name="comms_text1">Your phone is communicating with 360 People and setting up your account. This may take a moment.</string> <!-- .ui.startup.signup.SignupCreateAccountDetailsActivity --> <string name="dateofbirth">Date of Birth</string> <string name="user_is_too_young">You need to be at least 14 to sign up</string> <!-- .ui.startup.signup.SignupPasswordCreationActivity --> <string name="strong">Strong</string> <string name="passwords_do_not_match">Passwords do not match</string> <string name="password_too_short">Password is too short</string> <string name="warning">Warning</string> <string name="error">Error</string> <string name="username_is_too_short">Username is too short. Please use a minimum of 6 characters.</string> <string name="username_is_too_long">Username is too long</string> <string name="username_contains_invalid_characters">Username contains invalid characters</string> <string name="password_contains_invalid_characters">Password contains invalid characters</string> <string name="you_must_accept_terms_and_conditions">Terms &amp; Conditions must be accepted</string> <!-- .ui.utils.DisplayTermsActivity --> <string name="terms_and_conditions_title">Terms &amp; Conditions</string> <string name="privacy_title">Privacy</string> <string name="loading_title">Loading...</string> <string name="i_agree">I agree</string> <string name="i_dont_agree">I don\'t agree</string> <!-- .ui.startup.login.ForgotUsernameActivity --> <string name="error_text">Error</string> <!-- .engine.contactsync.FetchNativeContacts --> <string name="native_sync_title_mr">mr</string> <string name="native_sync_title_miss">miss</string> <string name="native_sync_title_mrs">mrs</string> <string name="native_sync_title_ms">ms</string> <string name="native_sync_title_dr">dr</string> <!-- .ui.widget.WidgetProvider --> <string name="widget_error_not_logged_in">You must be logged in to use this feature.</string> <string name="widget_other_error">There was a problem getting information</string> <string name="WidgetProvider_timestamp_today">Today</string> <string name="WidgetProvider_timestamp_yesterday">Yesterday</string> <!-- .ui.utils.PeopleEditText --> <string name="edit_text_context_menu_title">Edit Text</string> <!-- .ui.thirdparty.ThirdPartyEnterAccountsActivity [third_party_account_details.xml]--> <string name="facebook_terms_title">Terms &amp; Conditions for Facebook</string> <!-- Terms and Conditions for Facebook --> <string name="facebook_terms">Connecting this application with Face-\n book will enable you to bring public\n profile pics and contact details of your\n friends in Vodafone People in order to\n populate your address book.\n\n By clicking add Facebook you agree\n that you are granted a non-exclusive,\n non-transferable, personal license to\n use the public profile photos of your\n friends on Vodafone People.\n\n This license ends when either Facebook\n or the owner of that photo requests\n that you delete it. This license does not\n allow you to use those photos for any\n commercial purpose or with any other\n service or application.</string> <!-- .ui.utils.SNSIconUtils --> <string name="Utils_sns_name_facebook">Facebook</string> <string name="Utils_sns_name_twitter">Twitter</string> <string name="Utils_sns_name_google">Google</string> <string name="Utils_sns_name_msn">Windows Live Messenger</string> <string name="Utils_sns_name_hyves">Hyves</string> <string name="Utils_sns_name_vodafone">Vodafone</string> + <string name="Utils_sns_name_studivz">StudiVZ</string> </resources> \ No newline at end of file
360/360-Engine-for-Android
af8956db440e3a4a54b4a68c124fb621c5781f19
Fixed PAND-1734 - Missing StudiVZ icon.
diff --git a/src/com/vodafone360/people/utils/ThirdPartyAccount.java b/src/com/vodafone360/people/utils/ThirdPartyAccount.java index 8def94d..55e56d3 100644 --- a/src/com/vodafone360/people/utils/ThirdPartyAccount.java +++ b/src/com/vodafone360/people/utils/ThirdPartyAccount.java @@ -1,271 +1,275 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.utils; import android.content.Context; import android.graphics.Bitmap; import com.vodafone360.people.R; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.utils.LogUtils; /** * Holds data about a third party account i.e. facebook, msn, google. */ public class ThirdPartyAccount { private Identity mIdentity; private Bitmap mBitmap; private boolean mIsVerified = false; private boolean mChecked = true; private boolean mShouldBeProcessed = false; private String mDisplayName; /** username */ private String mIdentityID; public static final String SNS_TYPE_FACEBOOK = "facebook"; private static final String SNS_TYPE_MICROSOFT = "microsoft"; private static final String SNS_TYPE_MSN = "msn"; private static final String SNS_TYPE_WINDOWS = "windows"; private static final String SNS_TYPE_LIVE = "live"; public static final String SNS_TYPE_GOOGLE = "google"; public static final String SNS_TYPE_VODAFONE = "vodafone"; private static final String SNS_TYPE_NOWPLUS = "nowplus"; private static final String SNS_TYPE_ZYB = "zyb"; public static final String SNS_TYPE_TWITTER = "twitter"; public static final String SNS_TYPE_HYVES = "hyves"; + + public static final String SNS_TYPE_STUDIVZ = "studivz"; /** * Create a new third party account object. * * @param userName - the username for the account. * @param identity - Identity details retrieved from server. * @param checkedByDefault - true for the account to be enabled in the list. * @param isVerified - */ public ThirdPartyAccount(String userName, Identity identity, boolean checkedByDefault, boolean isVerified) { mIdentityID = userName; mChecked = checkedByDefault; mIdentity = identity; mIsVerified = isVerified; mDisplayName = identity.mName; } /** * Create a new third party account object. * * @param userName - the username for the account. * @param identity - Identity details retrieved from server. * @param isVerified - */ public ThirdPartyAccount(final String userName, final Identity identity, final boolean isVerified) { /**In ui-refresh will not have flag status of mChecked==false. * Because ui-refresh remove checkBox UI of this flag. * */ this(userName, identity, /*checkedByDefault*/true, isVerified); /** Always TRUE for UI-Refresh. */ mShouldBeProcessed = true; } /** {@inheritDoc} */ @Override public String toString() { final StringBuffer sb = new StringBuffer("ThirdPartyAccount: \n\tmUsername = "); sb.append(getIdentityID()); sb.append("\n\tmDisplayName = "); sb.append(getDisplayName()); sb.append("\n\tmCheckedByDefault = "); sb.append(isChecked()); sb.append("\n\tmIsVerified = "); sb.append(isVerified()); sb.append("\n\tmShouldBeProcesed = "); sb.append(isShouldBeProcessed()); return sb.toString(); } /* * Checks if the sns string contains text to identify it as Windows live sns * @param sns - the text to check * @return true if this is a Windows Live sns */ public static boolean isWindowsLive(String sns) { String snsLower = sns.toLowerCase(); return (snsLower.contains(SNS_TYPE_MSN) || snsLower.contains(SNS_TYPE_LIVE) || snsLower.contains(SNS_TYPE_MICROSOFT) || snsLower.contains(SNS_TYPE_WINDOWS)); } /* * Checks if the sns string contains text to identify it as Vodafone sns * @param sns - the text to check * @return true if this is a Vodafone sns */ public static boolean isVodafone(String sns) { String snsLower = sns.toLowerCase(); return (snsLower.contains(SNS_TYPE_VODAFONE) || snsLower.contains(SNS_TYPE_NOWPLUS) || snsLower .contains(SNS_TYPE_ZYB)); } /** * Gets the Localised string for the given SNS. * * @param sns - text of the sns type * @return Localised string for the given SNS. */ public static String getSnsString(Context context, String sns) { if (sns == null || isVodafone(sns)) { return context.getString(R.string.Utils_sns_name_vodafone); } else if (sns.contains(SNS_TYPE_FACEBOOK)) { return context.getString(R.string.Utils_sns_name_facebook); } else if (sns.contains(SNS_TYPE_GOOGLE)) { return context.getString(R.string.Utils_sns_name_google); } else if (isWindowsLive(sns)) { return context.getString(R.string.Utils_sns_name_msn); } else if (sns.contains(SNS_TYPE_TWITTER)) { return context.getString(R.string.Utils_sns_name_twitter); } else if (sns.startsWith(SNS_TYPE_HYVES)) { return context.getString(R.string.Utils_sns_name_hyves); + } else if (sns.startsWith(SNS_TYPE_STUDIVZ)) { + return context.getString(R.string.Utils_sns_name_studivz); } else { LogUtils.logE("SNSIconUtils.getSNSStringResId() SNS String[" + sns + "] is not of a " + "known type, so returning empty string value"); return ""; } } /** * @param mBitmap the mBitmap to set */ public void setBitmap(Bitmap mBitmap) { this.mBitmap = mBitmap; } /** * @return the mBitmap */ public Bitmap getBitmap() { return mBitmap; } /** * @param mIdentity the mIdentity to set */ public void setIdentity(Identity mIdentity) { this.mIdentity = mIdentity; } /** * @return the mIdentity */ public Identity getIdentity() { return mIdentity; } /** * @param mIsVerified the mIsVerified to set */ public void setIsVerified(boolean mIsVerified) { this.mIsVerified = mIsVerified; } /** * @return the mIsVerified */ public boolean isVerified() { return mIsVerified; } /** * @param mDisplayName the mDisplayName to set */ public void setDisplayName(String mDisplayName) { this.mDisplayName = mDisplayName; } /** * @return the mDisplayName */ public String getDisplayName() { return mDisplayName; } /** * @param mIdentityID the mIdentityID to set */ public void setIdentityID(String mIdentityID) { this.mIdentityID = mIdentityID; } /** * @return the mIdentityID */ public String getIdentityID() { return mIdentityID; } /** * @param mChecked the mChecked to set */ public void setChecked(boolean mChecked) { this.mChecked = mChecked; } /** * @return the mChecked */ public boolean isChecked() { return mChecked; } /** * @param mShouldBeProcessed the mShouldBeProcessed to set */ public void setShouldBeProcessed(boolean mShouldBeProcessed) { this.mShouldBeProcessed = mShouldBeProcessed; } /** * @return the mShouldBeProcessed */ public boolean isShouldBeProcessed() { return mShouldBeProcessed; } }
360/360-Engine-for-Android
4bfd851c73d98dd32b127d1713cf764fbe2e79eb
PAND-1797 added null check for mAccount
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index 5f489c1..1bdb149 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -125,1051 +125,1052 @@ public class NativeContactsApi2 extends NativeContactsApi { * Selection where clause for a NULL Account */ private static final String NULL_ACCOUNT_WHERE_CLAUSE = RawContacts.ACCOUNT_NAME + " IS NULL AND " + RawContacts.ACCOUNT_TYPE + " IS NULL"; /** * Selection where clause for an Organization detail. */ private static final String ORGANIZATION_DETAIL_WHERE_CLAUSE = RawContacts.Data.MIMETYPE + "=\"" + Organization.CONTENT_ITEM_TYPE + "\""; /** * The list of Uri that need to be listened to for contacts changes on * native side. */ private static final Uri[] sUri = { ContactsContract.RawContacts.CONTENT_URI, ContactsContract.Data.CONTENT_URI }; /** * Holds mapping from a NAB type (MIME) to a VCard Key */ private static final HashMap<String, Integer> sFromNabContentTypeToKeyMap; /** * Holds mapping from a VCard Key to a NAB type (MIME) */ private static final SparseArray<String> sFromKeyToNabContentTypeArray; static { sFromNabContentTypeToKeyMap = new HashMap<String, Integer>(9, 1); sFromNabContentTypeToKeyMap.put(StructuredName.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NAME); sFromNabContentTypeToKeyMap.put(Nickname.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NICKNAME); sFromNabContentTypeToKeyMap.put(Phone.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_PHONE); sFromNabContentTypeToKeyMap.put(Email.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_EMAIL); sFromNabContentTypeToKeyMap.put(StructuredPostal.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ADDRESS); sFromNabContentTypeToKeyMap .put(Organization.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ORG); sFromNabContentTypeToKeyMap.put(Website.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_URL); sFromNabContentTypeToKeyMap.put(Note.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NOTE); sFromNabContentTypeToKeyMap.put(Event.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_DATE); // sFromNabContentTypeToKeyMap.put( // Photo.CONTENT_ITEM_TYPE, ContactChange.KEY_PHOTO); sFromKeyToNabContentTypeArray = new SparseArray<String>(10); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NAME, StructuredName.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NICKNAME, Nickname.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_PHONE, Phone.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_EMAIL, Email.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ADDRESS, StructuredPostal.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ORG, Organization.CONTENT_ITEM_TYPE); // Special case: VCARD_TITLE maps to the same NAB type as sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_TITLE, Organization.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_URL, Website.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NOTE, Note.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_DATE, Event.CONTENT_ITEM_TYPE); // sFromKeyToNabContentTypeArray.append( // ContactChange.KEY_PHOTO, Photo.CONTENT_ITEM_TYPE); } /** * The observer registered by the upper layer. */ private ContactsObserver mAbstractedObserver; /** * Content values used for writing to NAB. */ private final ContentValues mValues = new ContentValues(); /** * The content observers that listens for native contacts changes. */ private final ContentObserver[] mContentObservers = new ContentObserver[sUri.length]; /** * Array of row ID in the groups table to the "My Contacts" System Group. * The reason for this being an array is because there may be multiple * "My Contacts" groups (Platform Bug!?). */ private long[] mMyContactsGroupRowIds = null; /** * Arguably another example where Organization and Title force us into extra * effort. We use this value to pass the correct detail ID when an 'add * detail' is done for one the two although the other is already present. * Make sure to reset this value for every UpdateContact operation */ private long mExistingOrganizationId = ContactChange.INVALID_ID; /** * Flag to check if we have already read a Birthday detail */ private boolean mHaveReadBirthday = false; /** * Yield value for our ContentProviderOperations. */ private boolean mYield = true; /** * Batch used for Contact Writing operations. */ private BatchOperation mBatch = new BatchOperation(); /** * Inner class for applying batches. TODO: Move to own class if batches * become supported in other areas */ private class BatchOperation { // List for storing the batch mOperations ArrayList<ContentProviderOperation> mOperations; /** * Default constructor */ public BatchOperation() { mOperations = new ArrayList<ContentProviderOperation>(); } /** * Current size of the batch * * @return Size of the batch */ public int size() { return mOperations.size(); } /** * Adds a new operation to the batch * * @param cpo The */ public void add(ContentProviderOperation cpo) { mOperations.add(cpo); } /** * Clears all operations in the batch Effectively resets the batch. */ public void clear() { mOperations.clear(); } public ContentProviderResult[] execute() { ContentProviderResult[] resultArray = null; if (mOperations.size() > 0) { // Apply the mOperations to the content provider try { resultArray = mCr.applyBatch(ContactsContract.AUTHORITY, mOperations); } catch (final OperationApplicationException e1) { LogUtils.logE("storing contact data failed", e1); } catch (final RemoteException e2) { LogUtils.logE("storing contact data failed", e2); } mOperations.clear(); } return resultArray; } } /** * Convenience interface to map the generic DATA column names to the People * profile detail column names. */ private interface PeopleProfileColumns { /** * 360 People profile MIME Type */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/com.vodafone360.people.profile"; /** * 360 People Contact's profile ID (Corresponds to Contact's Internal * Contact ID) */ public static final String DATA_PID = Data.DATA1; /** * 360 People Contact profile Summary */ public static final String DATA_SUMMARY = Data.DATA2; /** * 360 People Contact profile detail */ public static final String DATA_DETAIL = Data.DATA3; } /** * This class holds a native content observer that will be notified in case * of changes on the registered URI. */ private class NativeContentObserver extends ContentObserver { public NativeContentObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { LogUtils.logI("NativeContactsApi2.NativeContentObserver.onChange(" + selfChange + ")"); mAbstractedObserver.onChange(); } } /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { LogUtils.logI("NativeContactsApi2.registerObserver()"); if (mAbstractedObserver != null) { throw new RuntimeException( "Only one observer at a time supported... Please unregister first."); } mAbstractedObserver = observer; final ContentResolver cr = mContext.getContentResolver(); for (int i = 0; i < mContentObservers.length; i++) { mContentObservers[i] = new NativeContentObserver(); cr.registerContentObserver(sUri[i], true, mContentObservers[i]); } } /** * @see NativeContactsApi#unregisterObserver(ContactsObserver) */ @Override public void unregisterObserver() { LogUtils.logI("NativeContactsApi2.unregisterObserver()"); if (mCr != null) { mAbstractedObserver = null; for (int i = 0; i < mContentObservers.length; i++) { if (mContentObservers[i] != null) { mCr.unregisterContentObserver(mContentObservers[i]); mContentObservers[i] = null; } } } } /** * @see NativeContactsApi#initialize() */ @Override protected void initialize() { // perform here any one time initialization sPhoneAccount = getVendorSpecificAccount(); } /** * @see NativeContactsApi#getAccounts() */ @Override public Account[] getAccounts() { AccountManager accountManager = AccountManager.get(mContext); final android.accounts.Account[] accounts2xApi = accountManager.getAccounts(); Account[] accounts = null; if (accounts2xApi.length > 0) { accounts = new Account[accounts2xApi.length]; for (int i = 0; i < accounts2xApi.length; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } } return accounts; } /** * Reads vendor specific accounts from settings and through accountmanager. * Some phones with custom ui like sense have additional account that we * have to take care of. This method tryes to read them * * @return Account object if vendor specific account is found, null * otherwise */ public Account getVendorSpecificAccount() { // first read the settings String[] PROJECTION = { Settings.ACCOUNT_NAME, Settings.ACCOUNT_TYPE, Settings.UNGROUPED_VISIBLE }; // Get a cursor with all people Cursor cursor = mCr.query(Settings.CONTENT_URI, PROJECTION, null, null, null); // Got no cursor? Return with null! if (null == cursor) { return null; } try { String[] values = new String[cursor.getCount()]; for (int i = 0; i < values.length; i++) { cursor.moveToNext(); if (isVendorSpecificAccount(cursor.getString(1))) { return new Account(cursor.getString(0), cursor.getString(1)); } } } catch (Exception exc) { return null; } CursorUtils.closeCursor(cursor); // nothing found in the settings? try accountmanager Account[] accounts = getAccounts(); if (accounts == null) { return null; } for (Account account : accounts) { if (isVendorSpecificAccount(account.getType())) { return account; } } return null; } /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override public Account[] getAccountsByType(int type) { switch (type) { // people and google type lead to the same block the difference is // then handled inside in two if statements. // Otherwise we would have a lot of redundant code, case PEOPLE_ACCOUNT_TYPE: case GOOGLE_ACCOUNT_TYPE: { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts2xApi = null; // For people account set the people account type string... if (PEOPLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); } // .. and for google the same only with google string. if (GOOGLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(GOOGLE_ACCOUNT_TYPE_STRING); } final int numAccounts = accounts2xApi.length; if (numAccounts > 0) { Account[] accounts = new Account[numAccounts]; for (int i = 0; i < numAccounts; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } return accounts; } else { return null; } } case PHONE_ACCOUNT_TYPE: { if (sPhoneAccount == null) { return null; } return new Account[] { sPhoneAccount }; } default: return null; } } /** * @see NativeContactsApi#addPeopleAccount(String) */ @Override public boolean addPeopleAccount(String username) { boolean isAdded = false; try { android.accounts.Account account = new android.accounts.Account(username, PEOPLE_ACCOUNT_TYPE_STRING); AccountManager accountMan = AccountManager.get(mContext); isAdded = accountMan.addAccountExplicitly(account, null, null); if (isAdded) { if (VersionUtils.isHtcSenseDevice(mContext)) { createSettingsEntryForAccount(username); } // TODO: RE-ENABLE SYNC VIA SYSTEM ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0); // ContentResolver.setSyncAutomatically(account, // ContactsContract.AUTHORITY, true); } } catch (Exception ex) { LogUtils.logE("People Account creation failed because of exception:\n", ex); } if (isAdded) { // Updating MyContacts Group IDs here for now because it needs to be // done one time just before first time sync. // In the future, this code may change if we modify // the way we retrieve contact IDs. fetchMyContactsGroupRowIds(); } return isAdded; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); return accounts != null && accounts.length > 0; } /** * @see NativeContactsApi#removePeopleAccount() */ @Override public void removePeopleAccount() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); if (accounts != null && accounts.length > 0) { accountMan.removeAccount(accounts[0], null, null); } } /** * @see NativeContactsApi#getContactIds(Account) */ @Override public long[] getContactIds(Account account) { // Need to construct a where clause if (account != null) { final StringBuffer clauseBuffer = new StringBuffer(); clauseBuffer.append(RawContacts.ACCOUNT_NAME); clauseBuffer.append("=\""); clauseBuffer.append(account.getName()); clauseBuffer.append("\" AND "); clauseBuffer.append(RawContacts.ACCOUNT_TYPE); clauseBuffer.append("=\""); clauseBuffer.append(account.getType()); clauseBuffer.append('\"'); return getContactIds(clauseBuffer.toString()); } else { return getContactIds(NULL_ACCOUNT_WHERE_CLAUSE); } } /** * @see NativeContactsApi#getContact(long) */ @Override public ContactChange[] getContact(long nabContactId) { // Reset the boolean flags mHaveReadOrganization = false; mHaveReadBirthday = false; final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, nabContactId); final Uri dataUri = Uri.withAppendedPath(rawContactUri, RawContacts.Data.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(dataUri, null, null, null, null); try { if (cursor != null && cursor.getCount() > 0) { final List<ContactChange> ccList = new ArrayList<ContactChange>(); while (cursor.moveToNext()) { readDetail(cursor, ccList, nabContactId); } return ccList.toArray(new ContactChange[ccList.size()]); } } finally { CursorUtils.closeCursor(cursor); } return null; } /** * @see NativeContactsApi#addContact(Account, ContactChange[]) */ @Override public ContactChange[] addContact(Account account, ContactChange[] ccList) { // Make sure to reset all the member variables we need mYield = true; mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mValues.clear(); mBatch.clear(); mValues.put(RawContacts.ACCOUNT_TYPE, account.getType()); mValues.put(RawContacts.ACCOUNT_NAME, account.getName()); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI)).withYieldAllowed(mYield) .withValues(mValues); mBatch.add(builder.build()); + // according to the calling method ccList here has at least 1 element, ccList[0] is not null final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc != null) { final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } putDetail(cc); addValuesToBatch(ContactChange.INVALID_ID); } } // Special case for the organization/title if it was flagged in the // putDetail call putOrganization(ccList); addValuesToBatch(ContactChange.INVALID_ID); // Add 360 profile detail - addProfileAction(ccList[0].getInternalContactId()); + addProfileAction(ccList[0].getInternalContactId()); // Execute the batch and Generate ID changes from it return executeNewContactBatch(ccList); } /** * @see NativeContactsApi#updateContact(ContactChange[]) */ @Override public ContactChange[] updateContact(ContactChange[] ccList) { if (ccList == null || ccList.length == 0) { LogUtils.logW("NativeContactsApi2.updateContact() nothing to update - empty ccList!"); return null; } // Make sure to reset all the member variables we need mYield = true; mBatch.clear(); mValues.clear(); mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mExistingOrganizationId = ContactChange.INVALID_ID; final long nabContactId = ccList[0].getNabContactId(); if (nabContactId == ContactChange.INVALID_ID) { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update request because of invalid NAB Contact ID. Internal Contact ID is " + ccList[0].getInternalContactId()); return null; } final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } switch (cc.getType()) { case ContactChange.TYPE_ADD_DETAIL: putDetail(cc); addValuesToBatch(nabContactId); // not a new contact break; case ContactChange.TYPE_UPDATE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { putDetail(cc); addUpdateValuesToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update to detail for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; case ContactChange.TYPE_DELETE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { addDeleteDetailToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring detail deletion for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; default: break; } } updateOrganization(ccList, nabContactId); // Execute the batch and Generate ID changes from it return executeUpdateContactBatch(ccList); } /** * @see NativeContactsApi#removeContact(long) */ @Override public void removeContact(long nabContactId) { mCr.delete(addCallerIsSyncAdapterParameter(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId)), null, null); } /** * @see NativeContactsApi#isKeySupported(int) */ @Override public boolean isKeySupported(int key) { // Only supported if in the SparseArray return sFromKeyToNabContentTypeArray.indexOfKey(key) >= 0; } /** * Inner (private) method for getting contact ids. Allows a cleaner * separation the public API method. * * @param selection The where clause for the operation * @return An array containing the Contact IDs that have been found */ private long[] getContactIds(final String selection) { // Store ids in a temporary array because of possible null values long[] tempIds = null; int idCount = 0; final Cursor cursor = mCr.query(RawContacts.CONTENT_URI, CONTACTID_PROJECTION, selection, null, null); if (cursor == null) { return null; } try { final int cursorCount = cursor.getCount(); if (cursorCount > 0) { tempIds = new long[cursorCount]; while (cursor.moveToNext()) { final long id = cursor.getLong(CONTACTID_PROJECTION_RAW_ID); final String accountType = cursor.getString(CONTACTID_PROJECTION_ACCOUNT_TYPE); // TODO: Remove hardcoding (if statement) if (TextUtils.isEmpty(accountType) || accountType.equals(NativeContactsApi.PEOPLE_ACCOUNT_TYPE_STRING) || isVendorSpecificAccount(accountType) || isContactInMyContactsGroup(id)) { tempIds[idCount] = id; idCount++; } } } } finally { CursorUtils.closeCursor(cursor); } if (idCount > 0) { // Here we copy the array to strip any eventual nulls at the end of // the tempIds array final long[] ids = new long[idCount]; System.arraycopy(tempIds, 0, ids, 0, idCount); return ids; } return null; } /** * Fetches the IDs corresponding to the "My Contacts" System Group The * reason why we return an array is because there may be multiple * "My Contacts" groups. * * @return Array containing all IDs of the "My Contacts" group or null if * none exist */ private void fetchMyContactsGroupRowIds() { final Cursor cursor = mCr.query(Groups.CONTENT_URI, GROUPID_PROJECTION, MY_CONTACTS_GROUP_WHERE_CLAUSE, null, null); if (cursor == null) { return; } try { final int count = cursor.getCount(); if (count > 0) { mMyContactsGroupRowIds = new long[count]; for (int i = 0; i < count; i++) { cursor.moveToNext(); mMyContactsGroupRowIds[i] = cursor.getLong(0); } } } finally { CursorUtils.closeCursor(cursor); } } /** * Checks if a Contact is in the "My Contacts" System Group * * @param nabContactId ID of the Contact to check * @return true if the Contact is in the Group, false if not */ private boolean isContactInMyContactsGroup(long nabContactId) { boolean belongs = false; if (mMyContactsGroupRowIds != null) { final Uri dataUri = Uri.withAppendedPath(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId), RawContacts.Data.CONTENT_DIRECTORY); // build query containing row ID values final StringBuilder sb = new StringBuilder(); sb.append(MY_CONTACTS_MULTI_GROUP_MEMBERSHIP); final int rowIdCount = mMyContactsGroupRowIds.length; for (int i = 0; i < rowIdCount; i++) { sb.append(mMyContactsGroupRowIds[i]); if (i < rowIdCount - 1) { sb.append(','); } } sb.append(')'); final Cursor cursor = mCr.query(dataUri, null, sb.toString(), null, null); try { belongs = cursor != null && cursor.getCount() > 0; } finally { CursorUtils.closeCursor(cursor); } } return belongs; } /** * Reads a Contact Detail from a Cursor into the supplied Contact Change * List. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to read Detail into * @param nabContactId NAB ID of the Contact */ private void readDetail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String mimetype = CursorUtils.getString(cursor, Data.MIMETYPE); final Integer key = sFromNabContentTypeToKeyMap.get(mimetype); if (key != null) { switch (key.intValue()) { case ContactChange.KEY_VCARD_NAME: readName(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_NICKNAME: readNickname(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_PHONE: readPhone(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_EMAIL: readEmail(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ADDRESS: readAddress(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ORG: // Only one Organization can be read (CAB limitation!) if (!mHaveReadOrganization) { readOrganization(cursor, ccList, nabContactId); } break; case ContactChange.KEY_VCARD_URL: readWebsite(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_DATE: if (!mHaveReadBirthday) { readBirthday(cursor, ccList, nabContactId); } break; default: // The default case is also a valid key final String value = CursorUtils.getString(cursor, Data.DATA1); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Data._ID); final ContactChange cc = new ContactChange(key, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } break; } } } /** * Reads an name detail as a {@link ContactChange} from the provided cursor. * For this type of detail we need to use a VCARD (semicolon separated) * value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readName(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using display name only to check if there is a valid name to read final String displayName = CursorUtils.getString(cursor, StructuredName.DISPLAY_NAME); if (!TextUtils.isEmpty(displayName)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredName._ID); // VCard Helper data type (CAB) final Name name = new Name(); // NAB: Given name -> CAB: First name name.firstname = CursorUtils.getString(cursor, StructuredName.GIVEN_NAME); // NAB: Family name -> CAB: Surname name.surname = CursorUtils.getString(cursor, StructuredName.FAMILY_NAME); // NAB: Prefix -> CAB: Title name.title = CursorUtils.getString(cursor, StructuredName.PREFIX); // NAB: Middle name -> CAB: Middle name name.midname = CursorUtils.getString(cursor, StructuredName.MIDDLE_NAME); // NAB: Suffix -> CAB: Suffixes name.suffixes = CursorUtils.getString(cursor, StructuredName.SUFFIX); // NOTE: Ignoring Phonetics (DATA7, DATA8 and DATA9)! // TODO: Need to get middle name and concatenate into value final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NAME, VCardHelper .makeName(name), ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an nickname detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readNickname(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Nickname.NAME); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Nickname._ID); /* * TODO: Decide what to do with nickname: Can only have one in VF360 * but NAB Allows more than one! */ final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NICKNAME, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an phone detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readPhone(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Phone.NUMBER); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Phone._ID); final int type = CursorUtils.getInt(cursor, Phone.TYPE); int flags = mapFromNabPhoneType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Phone.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // assuming raw value is good enough for us final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_PHONE, value, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an email detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readEmail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Email.DATA); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Email._ID); final int type = CursorUtils.getInt(cursor, Email.TYPE); int flags = mapFromNabEmailType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Email.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // assuming raw value is good enough for us final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_EMAIL, value, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an address detail as a {@link ContactChange} from the provided * cursor. For this type of detail we need to use a VCARD (semicolon * separated) value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readAddress(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using formatted address only to check if there is a valid address to // read final String formattedAddress = CursorUtils.getString(cursor, StructuredPostal.FORMATTED_ADDRESS); if (!TextUtils.isEmpty(formattedAddress)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredPostal._ID); final int type = CursorUtils.getInt(cursor, StructuredPostal.TYPE); int flags = mapFromNabAddressType(type); final boolean isPrimary = CursorUtils.getInt(cursor, StructuredPostal.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } // VCard Helper data type (CAB) final PostalAddress address = new PostalAddress(); // NAB: Street -> CAB: AddressLine1 address.addressLine1 = CursorUtils.getString(cursor, StructuredPostal.STREET); // NAB: PO Box -> CAB: postOfficeBox address.postOfficeBox = CursorUtils.getString(cursor, StructuredPostal.POBOX); // NAB: Neighborhood -> CAB: AddressLine2 address.addressLine2 = CursorUtils.getString(cursor, StructuredPostal.NEIGHBORHOOD); // NAB: City -> CAB: City address.city = CursorUtils.getString(cursor, StructuredPostal.CITY); // NAB: Region -> CAB: County address.county = CursorUtils.getString(cursor, StructuredPostal.REGION); // NAB: Post code -> CAB: Post code address.postCode = CursorUtils.getString(cursor, StructuredPostal.POSTCODE); // NAB: Country -> CAB: Country address.country = CursorUtils.getString(cursor, StructuredPostal.COUNTRY); final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_ADDRESS, VCardHelper .makePostalAddress(address), flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an organization detail as a {@link ContactChange} from the provided * cursor. For this type of detail we need to use a VCARD (semicolon * separated) value. In reality two different changes may be read if a title * is also present. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readOrganization(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final int type = CursorUtils.getInt(cursor, Organization.TYPE); int flags = mapFromNabOrganizationType(type); final boolean isPrimary = CursorUtils.getInt(cursor, Organization.IS_PRIMARY) != 0; if (isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } final long nabDetailId = CursorUtils.getLong(cursor, Organization._ID); if (!mHaveReadOrganization) { // VCard Helper data type (CAB) final Organisation organization = new Organisation(); // Company organization.name = CursorUtils.getString(cursor, Organization.COMPANY); // Department final String department = CursorUtils.getString(cursor, Organization.DEPARTMENT); if (!TextUtils.isEmpty(department)) { organization.unitNames.add(department); } if ((organization.unitNames != null && organization.unitNames.size() > 0) || !TextUtils.isEmpty(organization.name)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_ORG, VCardHelper .makeOrg(organization), flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } // Title final String title = CursorUtils.getString(cursor, Organization.TITLE); if (!TextUtils.isEmpty(title)) { final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_TITLE, title, flags); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); mHaveReadOrganization = true; } } } /** * Reads an Website detail as a {@link ContactChange} from the provided * cursor. diff --git a/src/com/vodafone360/people/engine/contactsync/NativeExporter.java b/src/com/vodafone360/people/engine/contactsync/NativeExporter.java index dbe4964..084be1d 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeExporter.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeExporter.java @@ -1,300 +1,304 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import com.vodafone360.people.engine.contactsync.NativeContactsApi.Account; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; public class NativeExporter { /** * The undefined result when the NativeImporter has not been run yet. * @see #getResult() */ public final static int RESULT_UNDEFINED = -1; /** * The ok result when the NativeImporter has finished successfully. * @see #getResult() */ public final static int RESULT_OK = 0; /** * The undefined result when the NativeImporter has not been run yet. * @see #getResult() */ public final static int RESULT_ERROR = 1; /** * Number of contacts to be processed "per tick". * @see #tick() */ private final static int MAX_CONTACTS_OPERATION_COUNT = 2; /** * Handler to the People Contacts API. */ private PeopleContactsApi mPeopleContactsApi; /** * Handle to the Native Contacts API. */ private NativeContactsApi mNativeContactsApi; /** * Internal state representing the task to perform: gets the list of local contacts IDs to be synced to Native. */ private final static int STATE_GET_CONTACT_IDS = 0; /** * Internal state representing the task to perform: iterates through the list of syncable contacts IDs and sync to Native side. */ private final static int STATE_ITERATE_THROUGH_IDS = 1; /** * Internal state representing the task to perform: final state, nothing else to perform. */ private final static int STATE_DONE = 2; /** * The current state. */ private int mState = STATE_GET_CONTACT_IDS; /** * The list of local IDs from people contacts that need to be synced to Native. */ private long[] mSyncableContactsIds; /** * The index in the current people id. * @see #mSyncableContactsIds */ private int mCurrentSyncableIdIndex = 0; /** * The result status. */ private int mResult = RESULT_UNDEFINED; /** * The total count of IDs to process (Native Database + People Database). */ private int mTotalIds = 0; /** * The current count of processed IDs. */ private int mProcessedIds = 0; /** * The Native Account where to write the Contacts. */ private Account mAccount = null; /** * Constructor. * * @param pca handler to the People Contacts API * @param nca handler to the Native Contacts API */ public NativeExporter(PeopleContactsApi pca, NativeContactsApi nca) { mPeopleContactsApi = pca; mNativeContactsApi = nca; if (VersionUtils.is2XPlatform()) { final Account[] accounts = mNativeContactsApi.getAccountsByType(NativeContactsApi.PEOPLE_ACCOUNT_TYPE); if (accounts != null) { mAccount = accounts[0]; } } } /** * Gets the current position in the list of IDs. * * This can be used to track the current progress. * @see #getCount() * * @return the last processed id position in the list of IDs */ public int getPosition() { return mProcessedIds; } /** * Gets the total number of IDs to process. * * @return the number of IDs to process */ public int getCount() { return mTotalIds; } /** * Sets the internal state to DONE with the provided result status. * * @param result the result status to set */ private void complete(int result) { mState = STATE_DONE; mResult = result; } /** * Tick method to call each time there is time for processing the Native Contacts Import. * * Note: the method will block for some time to process a certain number of Contacts and then will * return. It will have to be called until it returns true meaning that the Import is over. * * @return true when the Import Task is finished, false if not */ public boolean tick() { switch(mState) { case STATE_GET_CONTACT_IDS: getContactIds(); break; case STATE_ITERATE_THROUGH_IDS: iterateThroughSyncableIds(); break; } return mState == STATE_DONE; } /** * Gets the Import result. * * @see #RESULT_OK * @see #RESULT_ERROR * @see #RESULT_UNDEFINED * * @return the Import result */ public int getResult() { return mResult; } /** * Gets the list of local contacts IDs that need to be synced to Native. */ private void getContactIds() { LogUtils.logD("NativeExporter.getIdList()"); mSyncableContactsIds = mPeopleContactsApi.getNativeSyncableContactIds(); // check if we have some work to do if (mSyncableContactsIds != null) { mState = STATE_ITERATE_THROUGH_IDS; } else { complete(RESULT_OK); } } /** * Iterates through the list of syncable contacts IDs and sync to Native side. */ private void iterateThroughSyncableIds() { LogUtils.logD("NativeExporter.iterateThroughSyncableIds()"); final int limit = Math.min(mSyncableContactsIds.length, mCurrentSyncableIdIndex + MAX_CONTACTS_OPERATION_COUNT); while (mCurrentSyncableIdIndex < limit) { final ContactChange[] changes = mPeopleContactsApi.getNativeSyncableContactChanges(mSyncableContactsIds[mCurrentSyncableIdIndex]); if (changes != null) { exportContactChanges(changes); } mCurrentSyncableIdIndex++; } if (mCurrentSyncableIdIndex == mSyncableContactsIds.length) { // Nothing else to do complete(RESULT_OK); } } /** * Exports the contact changes to the native address book. * * @param changes the array of ContactChange that represent a full contact, a deleted contact or an updated contact */ private void exportContactChanges(ContactChange[] changes) { // the ContactChange array that we'll get back from native ContactChange[] nativeResponse = null; switch(changes[0].getType()) { case ContactChange.TYPE_ADD_CONTACT: // add the contact on Native side - nativeResponse = mNativeContactsApi.addContact(mAccount, changes); - // sync back the native IDs on People side - if (!mPeopleContactsApi.syncBackNewNativeContact(changes, nativeResponse)) { - LogUtils.logE("NativeExporter.exportContactChanges() - Add Contact failed!"); + + //the account can be null (theoretically) + if (mAccount != null) { + nativeResponse = mNativeContactsApi.addContact(mAccount, changes); + // sync back the native IDs on People side + if (!mPeopleContactsApi.syncBackNewNativeContact(changes, nativeResponse)) { + LogUtils.logE("NativeExporter.exportContactChanges() - Add Contact failed!"); + } } break; case ContactChange.TYPE_DELETE_CONTACT: // delete the contact on Native side mNativeContactsApi.removeContact(changes[0].getNabContactId()); // acknowledge the people side about deletion if (!mPeopleContactsApi.syncBackDeletedNativeContact(changes[0])) { LogUtils.logE("NativeExporter.exportContactChanges() - Syncing back Contact deletion to Client side failed!"); } break; case ContactChange.TYPE_UPDATE_CONTACT: case ContactChange.TYPE_ADD_DETAIL: case ContactChange.TYPE_DELETE_DETAIL: case ContactChange.TYPE_UPDATE_DETAIL: // update the contact on Native side nativeResponse = mNativeContactsApi.updateContact(changes); // acknowledge People side about deleted details and added details Native IDs if (!mPeopleContactsApi.syncBackUpdatedNativeContact(changes, nativeResponse)) { LogUtils.logE("NativeExporter.exportContactChanges() - Update Contact failed!"); } break; default: LogUtils.logE("NativeExporter.exportContactChanges() - Aborted exporting because of unknown type("+changes[0].getType()+")!"); break; } } }
360/360-Engine-for-Android
455aa353ed0b26934d0bc4282fa0c90ebf6edb6c
New Construtor for ui-refresh [PAND-1864]: [Accounts Tab] Checkbox is visible partially under transparent areas of WLM icon
diff --git a/src/com/vodafone360/people/utils/ThirdPartyAccount.java b/src/com/vodafone360/people/utils/ThirdPartyAccount.java index 4dd909f..8def94d 100644 --- a/src/com/vodafone360/people/utils/ThirdPartyAccount.java +++ b/src/com/vodafone360/people/utils/ThirdPartyAccount.java @@ -1,252 +1,271 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.utils; import android.content.Context; import android.graphics.Bitmap; import com.vodafone360.people.R; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.utils.LogUtils; /** * Holds data about a third party account i.e. facebook, msn, google. */ public class ThirdPartyAccount { private Identity mIdentity; private Bitmap mBitmap; private boolean mIsVerified = false; private boolean mChecked = true; private boolean mShouldBeProcessed = false; private String mDisplayName; /** username */ private String mIdentityID; public static final String SNS_TYPE_FACEBOOK = "facebook"; private static final String SNS_TYPE_MICROSOFT = "microsoft"; private static final String SNS_TYPE_MSN = "msn"; private static final String SNS_TYPE_WINDOWS = "windows"; private static final String SNS_TYPE_LIVE = "live"; public static final String SNS_TYPE_GOOGLE = "google"; public static final String SNS_TYPE_VODAFONE = "vodafone"; private static final String SNS_TYPE_NOWPLUS = "nowplus"; private static final String SNS_TYPE_ZYB = "zyb"; public static final String SNS_TYPE_TWITTER = "twitter"; public static final String SNS_TYPE_HYVES = "hyves"; /** * Create a new third party account object. * * @param userName - the username for the account. * @param identity - Identity details retrieved from server. * @param checkedByDefault - true for the account to be enabled in the list. * @param isVerified - */ public ThirdPartyAccount(String userName, Identity identity, boolean checkedByDefault, boolean isVerified) { mIdentityID = userName; mChecked = checkedByDefault; mIdentity = identity; mIsVerified = isVerified; mDisplayName = identity.mName; } + /** + * Create a new third party account object. + * + * @param userName - the username for the account. + * @param identity - Identity details retrieved from server. + * @param isVerified - + */ + public ThirdPartyAccount(final String userName, final Identity identity, + final boolean isVerified) { + + /**In ui-refresh will not have flag status of mChecked==false. + * Because ui-refresh remove checkBox UI of this flag. + * */ + this(userName, identity, /*checkedByDefault*/true, isVerified); + + /** Always TRUE for UI-Refresh. */ + mShouldBeProcessed = true; + } + /** {@inheritDoc} */ @Override public String toString() { final StringBuffer sb = new StringBuffer("ThirdPartyAccount: \n\tmUsername = "); sb.append(getIdentityID()); sb.append("\n\tmDisplayName = "); sb.append(getDisplayName()); sb.append("\n\tmCheckedByDefault = "); sb.append(isChecked()); sb.append("\n\tmIsVerified = "); sb.append(isVerified()); sb.append("\n\tmShouldBeProcesed = "); sb.append(isShouldBeProcessed()); return sb.toString(); } /* * Checks if the sns string contains text to identify it as Windows live sns * @param sns - the text to check * @return true if this is a Windows Live sns */ public static boolean isWindowsLive(String sns) { String snsLower = sns.toLowerCase(); return (snsLower.contains(SNS_TYPE_MSN) || snsLower.contains(SNS_TYPE_LIVE) || snsLower.contains(SNS_TYPE_MICROSOFT) || snsLower.contains(SNS_TYPE_WINDOWS)); } /* * Checks if the sns string contains text to identify it as Vodafone sns * @param sns - the text to check * @return true if this is a Vodafone sns */ public static boolean isVodafone(String sns) { String snsLower = sns.toLowerCase(); return (snsLower.contains(SNS_TYPE_VODAFONE) || snsLower.contains(SNS_TYPE_NOWPLUS) || snsLower .contains(SNS_TYPE_ZYB)); } /** * Gets the Localised string for the given SNS. * * @param sns - text of the sns type * @return Localised string for the given SNS. */ public static String getSnsString(Context context, String sns) { if (sns == null || isVodafone(sns)) { return context.getString(R.string.Utils_sns_name_vodafone); } else if (sns.contains(SNS_TYPE_FACEBOOK)) { return context.getString(R.string.Utils_sns_name_facebook); } else if (sns.contains(SNS_TYPE_GOOGLE)) { return context.getString(R.string.Utils_sns_name_google); } else if (isWindowsLive(sns)) { return context.getString(R.string.Utils_sns_name_msn); } else if (sns.contains(SNS_TYPE_TWITTER)) { return context.getString(R.string.Utils_sns_name_twitter); } else if (sns.startsWith(SNS_TYPE_HYVES)) { return context.getString(R.string.Utils_sns_name_hyves); } else { LogUtils.logE("SNSIconUtils.getSNSStringResId() SNS String[" + sns + "] is not of a " + "known type, so returning empty string value"); return ""; } } /** * @param mBitmap the mBitmap to set */ public void setBitmap(Bitmap mBitmap) { this.mBitmap = mBitmap; } /** * @return the mBitmap */ public Bitmap getBitmap() { return mBitmap; } /** * @param mIdentity the mIdentity to set */ public void setIdentity(Identity mIdentity) { this.mIdentity = mIdentity; } /** * @return the mIdentity */ public Identity getIdentity() { return mIdentity; } /** * @param mIsVerified the mIsVerified to set */ public void setIsVerified(boolean mIsVerified) { this.mIsVerified = mIsVerified; } /** * @return the mIsVerified */ public boolean isVerified() { return mIsVerified; } /** * @param mDisplayName the mDisplayName to set */ public void setDisplayName(String mDisplayName) { this.mDisplayName = mDisplayName; } /** * @return the mDisplayName */ public String getDisplayName() { return mDisplayName; } /** * @param mIdentityID the mIdentityID to set */ public void setIdentityID(String mIdentityID) { this.mIdentityID = mIdentityID; } /** * @return the mIdentityID */ public String getIdentityID() { return mIdentityID; } /** * @param mChecked the mChecked to set */ public void setChecked(boolean mChecked) { this.mChecked = mChecked; } /** * @return the mChecked */ public boolean isChecked() { return mChecked; } /** * @param mShouldBeProcessed the mShouldBeProcessed to set */ public void setShouldBeProcessed(boolean mShouldBeProcessed) { this.mShouldBeProcessed = mShouldBeProcessed; } /** * @return the mShouldBeProcessed */ public boolean isShouldBeProcessed() { return mShouldBeProcessed; } }
360/360-Engine-for-Android
280d369e7b14872044441fe3587dffa160210217
fixed pand-1721: incomins sms not imported to timeline. problem was that on an htc desire the client got the mailbox notifications with the same ID even if the message was different.
diff --git a/src/com/vodafone360/people/database/tables/ActivitiesTable.java b/src/com/vodafone360/people/database/tables/ActivitiesTable.java index bd271fa..c963585 100644 --- a/src/com/vodafone360/people/database/tables/ActivitiesTable.java +++ b/src/com/vodafone360/people/database/tables/ActivitiesTable.java @@ -421,1301 +421,1297 @@ public abstract class ActivitiesTable { */ public static void getQueryData(final Cursor cursor, final ActivityContact activityContact) { DatabaseHelper.trace(false, "DatabaseHelper.getQueryData()"); /** Populate ActivityContact. **/ activityContact.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); activityContact.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); activityContact.mName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); activityContact.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); activityContact.mNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); activityContact.mAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); activityContact.mAvatarUrl = SqlUtils.setString(cursor, Field.CONTACT_AVATAR_URL.toString()); } /*** * Provides a ContentValues object that can be used to update the table. * * @param item The source activity item * @param contactIdx The index of the contact to use for the update, or null * to exclude contact specific information. * @return ContentValues for use in an SQL update or insert. * @note Items that are NULL will be not modified in the database. */ private static ContentValues fillUpdateData(final ActivityItem item, final Integer contactIdx) { DatabaseHelper.trace(false, "DatabaseHelper.fillUpdateData()"); ContentValues activityItemValues = new ContentValues(); ActivityContact ac = null; if (contactIdx != null) { ac = item.mContactList.get(contactIdx); } activityItemValues.put(Field.ACTIVITY_ID.toString(), item.mActivityId); activityItemValues.put(Field.TIMESTAMP.toString(), item.mTime); if (item.mType != null) { activityItemValues.put(Field.TYPE.toString(), item.mType.getTypeCode()); } if (item.mUri != null) { activityItemValues.put(Field.URI.toString(), item.mUri); } /** TODO: Not sure if we need this. **/ // activityItemValues.put(Field.INCOMING.toString(), false); activityItemValues.put(Field.TITLE.toString(), item.mTitle); activityItemValues.put(Field.DESCRIPTION.toString(), item.mDescription); if (item.mPreviewUrl != null) { activityItemValues.put(Field.PREVIEW_URL.toString(), item.mPreviewUrl); } if (item.mStore != null) { activityItemValues.put(Field.STORE.toString(), item.mStore); } if (item.mActivityFlags != null) { activityItemValues.put(Field.FLAG.toString(), item.mActivityFlags); } if (item.mParentActivity != null) { activityItemValues.put(Field.PARENT_ACTIVITY.toString(), item.mParentActivity); } if (item.mHasChildren != null) { activityItemValues.put(Field.HAS_CHILDREN.toString(), item.mHasChildren); } if (item.mVisibilityFlags != null) { activityItemValues.put(Field.VISIBILITY.toString(), item.mVisibilityFlags); } if (ac != null) { activityItemValues.put(Field.CONTACT_ID.toString(), ac.mContactId); activityItemValues.put(Field.USER_ID.toString(), ac.mUserId); activityItemValues.put(Field.CONTACT_NAME.toString(), ac.mName); activityItemValues.put(Field.LOCAL_CONTACT_ID.toString(), ac.mLocalContactId); if (ac.mNetwork != null) { activityItemValues.put(Field.CONTACT_NETWORK.toString(), ac.mNetwork); } if (ac.mAddress != null) { activityItemValues.put(Field.CONTACT_ADDRESS.toString(), ac.mAddress); } if (ac.mAvatarUrl != null) { activityItemValues.put(Field.CONTACT_AVATAR_URL.toString(), ac.mAvatarUrl); } } return activityItemValues; } /** * Fetches a list of status items from the given time stamp. * * @param timeStamp Time stamp in milliseconds * @param readableDb Readable SQLite database * @return A cursor (use one of the {@link #getQueryData} methods to read * the data) */ public static Cursor fetchStatusEventList(final long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchStatusEventList()"); return readableDb.rawQuery("SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + " & " + ActivityItem.STATUS_ITEM + ") AND " + Field.TIMESTAMP + " > " + timeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); } /** * Returns a list of activity IDs already synced, in reverse chronological * order Fetches from the given timestamp. * * @param actIdList An empty list which will be filled with the result * @param timeStamp The time stamp to start the fetch * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus fetchActivitiesIds(final List<Long> actIdList, final Long timeStamp, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchActivitiesIds()"); Cursor cursor = null; try { long queryTimeStamp; if (timeStamp != null) { queryTimeStamp = timeStamp; } else { queryTimeStamp = 0; } cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.TIMESTAMP + " >= " + queryTimeStamp + " ORDER BY " + Field.TIMESTAMP + " DESC", null); while (cursor.moveToNext()) { actIdList.add(cursor.getLong(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchActivitiesIds()" + "Unable to fetch group list", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Adds a list of activities to table. The activities added will be grouped * in the database, based on local contact Id, name or contact address (see * {@link #removeContactGroup(Long, String, Long, int, * TimelineNativeTypes[], SQLiteDatabase)} * for more information on how the grouping works. * * @param actList The list of activities * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus addActivities(final List<ActivityItem> actList, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addActivities()"); SQLiteStatement statement = ContactsTable.fetchLocalFromServerIdStatement(writableDb); for (ActivityItem activity : actList) { try { writableDb.beginTransaction(); if (activity.mContactList != null) { int clistSize = activity.mContactList.size(); for (int i = 0; i < clistSize; i++) { final ActivityContact activityContact = activity.mContactList.get(i); activityContact.mLocalContactId = ContactsTable.fetchLocalFromServerId( activityContact.mContactId, statement); int latestStatusVal = removeContactGroup( activityContact.mLocalContactId, activityContact.mName, activity.mTime, activity.mActivityFlags, null, writableDb); ContentValues cv = fillUpdateData(activity, i); cv.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); activity.mLocalActivityId = writableDb.insertOrThrow(TABLE_NAME, null, cv); } } else { activity.mLocalActivityId = writableDb.insertOrThrow( TABLE_NAME, null, fillUpdateData(activity, null)); } if (activity.mLocalActivityId < 0) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addActivities() " + "Unable to add activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } if(statement != null) { statement.close(); statement = null; } return ServiceStatus.SUCCESS; } /** * Deletes all activities from the table. * * @param flag Can be a bitmap of: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * <li>NULL - to delete all activities</li> * </ul> * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteActivities(final Integer flag, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteActivities()"); try { String whereClause = null; if (flag != null) { whereClause = Field.FLAG + "&" + flag; } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteActivities() " + "Unable to delete activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } public static ServiceStatus fetchNativeIdsFromLocalContactId(List<Integer > nativeItemIdList, final long localContactId, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNativeIdsFromLocalContactId()"); Cursor cursor = null; try { cursor = readableDb.rawQuery("SELECT " + Field.NATIVE_ITEM_ID + " FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + " = " + localContactId, null); while (cursor.moveToNext()) { nativeItemIdList.add(cursor.getInt(0)); } } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchNativeIdsFromLocalContactId()" + "Unable to fetch list of NativeIds from localcontactId", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(cursor); } return ServiceStatus.SUCCESS; } /** * Deletes specified timeline activity from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivity(final Context context, final TimelineSummaryItem timelineItem, final SQLiteDatabase writableDb, final SQLiteDatabase readableDb) { DatabaseHelper.trace(true, "DatabaseHelper.deleteTimelineActivity()"); try { List<Integer > nativeItemIdList = new ArrayList<Integer>() ; //Delete from Native Database if(timelineItem.mNativeThreadId != null) { //Sms Native Database final Uri smsUri = Uri.parse("content://sms"); context.getContentResolver().delete(smsUri , "thread_id=" + timelineItem.mNativeThreadId, null); //Mms Native Database final Uri mmsUri = Uri.parse("content://mms"); context.getContentResolver().delete(mmsUri, "thread_id=" + timelineItem.mNativeThreadId, null); } else { // For CallLogs if(timelineItem.mLocalContactId != null) { fetchNativeIdsFromLocalContactId(nativeItemIdList, timelineItem.mLocalContactId, readableDb); if(nativeItemIdList.size() > 0) { //CallLog Native Database for(Integer nativeItemId : nativeItemIdList) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=" + nativeItemId, null); } } } else { if(timelineItem.mContactAddress != null) { context.getContentResolver().delete(Calls.CONTENT_URI, Calls.NUMBER + "=" + timelineItem.mContactAddress, null); } } } String whereClause = null; //Delete from People Client database if(timelineItem.mLocalContactId != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } else if(timelineItem.mContactAddress != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } /** * Deletes all the timeline activities for a particular contact from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivities(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.deleteTimelineActivities()"); Cursor cursor = null; try { TimelineNativeTypes[] typeList = null; TimelineSummaryItem timelineItem = null; //For CallLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } //For SmsLog/MmsLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } //For ChatLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }; cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * Fetches timeline events grouped by local contact ID, name or contact * address. Events returned will be in reverse-chronological order. If a * native type list is provided the result will be filtered by the list. * * @param minTimeStamp Only timeline events from this date will be returned * @param nativeTypes A list of native types to filter the result, or null * to return all. * @param readableDb Readable SQLite database * @return A cursor containing the result. The * {@link #getTimelineData(Cursor)} method should be used for * reading the cursor. */ public static Cursor fetchTimelineEventList(final Long minTimeStamp, final TimelineNativeTypes[] nativeTypes, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchTimelineEventList() " + "minTimeStamp[" + minTimeStamp + "]"); try { int andVal = 1; String typesQuery = " AND "; if (nativeTypes != null) { typesQuery += DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), nativeTypes, "OR"); typesQuery += " AND "; andVal = 2; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + Field.TIMESTAMP + " > " + minTimeStamp + " AND (" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") ORDER BY " + Field.TIMESTAMP + " DESC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchLastUpdateTime() " + "Unable to fetch timeline event list", e); return null; } } /** * Adds a list of timeline events to the database. Each event is grouped by * contact and grouped by contact + native type. * * @param itemList List of timeline events * @param isCallLog true to group all activities with call logs, false to * group with messaging * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error */ public static ServiceStatus addTimelineEvents( final ArrayList<TimelineSummaryItem> itemList, final boolean isCallLog, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addTimelineEvents()"); TimelineNativeTypes[] activityTypes; if (isCallLog) { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; } else { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; } for (TimelineSummaryItem item : itemList) { try { writableDb.beginTransaction(); - if (findNativeActivity(item.mNativeItemId, - item.mNativeItemType, writableDb)) { + if (findNativeActivity(item, writableDb)) { continue; } int latestStatusVal = 0; if (item.mContactName != null || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, activityTypes, writableDb); } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM); values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } item.mLocalActivityId = writableDb.insert(TABLE_NAME, null, values); if (item.mLocalActivityId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "ERROR_DATABASE_CORRUPT - Unable to add " + "timeline list to database"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /** * The method returns the ROW_ID i.e. the INTEGER PRIMARY KEY AUTOINCREMENT * field value for the inserted row, i.e. LOCAL_ID. * * @param item TimelineSummaryItem. * @param read - TRUE if the chat message is outgoing or gets into the * timeline history view for a contact with LocalContactId. * @param writableDb Writable SQLite database. * @return LocalContactID or -1 if the row was not inserted. */ public static long addChatTimelineEvent(final TimelineSummaryItem item, final boolean read, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addChatTimelineEvent()"); try { writableDb.beginTransaction(); int latestStatusVal = 0; if (item.mContactName != null || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }, writableDb); } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); /** Chat message body. **/ values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); if (read) { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); } else { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | 0); } values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); /** Conversation ID for chat message. **/ // values.put(Field.URI.toString(), item.conversationId); // 0 for incoming, 1 for outgoing if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } final long itemId = writableDb.insert(TABLE_NAME, null, values); if (itemId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() - " + "Unable to add timeline list to database, index<0:" + itemId); return -1; } writableDb.setTransactionSuccessful(); return itemId; } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return -1; } finally { writableDb.endTransaction(); } } /** * Clears the grouping of an activity in the database, if the given activity * is newer. This is so that only the latest activity is returned for a * particular group. Each activity is associated with two groups: * <ol> * <li>All group - Grouped by contact only</li> * <li>Native group - Grouped by contact and native type (call log or * messaging)</li> * </ol> * The group to be removed is determined by the activityTypes parameter. * Grouping must also work for timeline events that are not associated with * a contact. The following fields are used to do identify a contact for the * grouping (in order of priority): * <ol> * <li>localContactId - If it not null</li> * <li>name - If this is a valid telephone number, the match will be done to * ensure that the same phone number written in different ways will be * included in the group. See {@link #fetchNameWhereClause(Long, String)} * for more information.</li> * </ol> * * @param localContactId Local contact Id or NULL if the activity is not * associated with a contact. * @param name Name of contact or contact address (telephone number, email, * etc). * @param newUpdateTime The time that the given activity has occurred * @param flag Bitmap of types including: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * </ul> * @param activityTypes A list of native types to include in the grouping. * Currently, only two groups are supported (see above). If this * parameter is null the contact will be added to the * "all group", otherwise the contact is added to the native * group. * @param writableDb Writable SQLite database * @return The latest contact status value which should be added to the * current activities grouping. */ private static int removeContactGroup(final Long localContactId, final String name, final Long newUpdateTime, final int flag, final TimelineNativeTypes[] activityTypes, final SQLiteDatabase writableDb) { String whereClause = ""; int andVal = 1; if (activityTypes != null) { whereClause = DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), activityTypes, "OR"); whereClause += " AND "; andVal = 2; } String nameWhereClause = fetchNameWhereClause(localContactId, name); if (nameWhereClause == null) { return 0; } whereClause += nameWhereClause; Long prevTime = null; Long prevLocalId = null; Integer prevLatestContactStatus = null; Cursor cursor = null; try { cursor = writableDb.rawQuery("SELECT " + Field.TIMESTAMP + "," + Field.LOCAL_ACTIVITY_ID + "," + Field.LATEST_CONTACT_STATUS + " FROM " + TABLE_NAME + " WHERE " + whereClause + " AND " + "(" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") AND (" + Field.FLAG + "&" + flag + ") ORDER BY " + Field.TIMESTAMP + " DESC", null); if (cursor.moveToFirst()) { prevTime = cursor.getLong(0); prevLocalId = cursor.getLong(1); prevLatestContactStatus = cursor.getInt(2); } } catch (SQLException e) { return 0; } finally { CloseUtils.close(cursor); } if (prevTime != null && newUpdateTime != null) { if (newUpdateTime >= prevTime) { ContentValues cv = new ContentValues(); cv.put(Field.LATEST_CONTACT_STATUS.toString(), prevLatestContactStatus & (~andVal)); if (writableDb.update(TABLE_NAME, cv, Field.LOCAL_ACTIVITY_ID + "=" + prevLocalId, null) <= 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "Unable to update timeline as the latest"); return 0; } return andVal; } else { return 0; } } return andVal; } /** * Checks if an activity exists in the database. * - * @param nativeId The native ID which links the activity with the record in - * the native table. - * @param type The native type (An ordinal from the #TimelineNativeTypes - * enumeration) - * @param readableDb Readable SQLite database + * @param item The native SMS item to check against our client activities DB table. + * * @return true if the activity was found, false otherwise + * */ - private static boolean findNativeActivity(final int nativeId, - final int type, final SQLiteDatabase readableDb) { + private static boolean findNativeActivity(TimelineSummaryItem item, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.findNativeActivity()"); Cursor cursor = null; boolean result = false; try { final String[] args = { - Integer.toString(nativeId), Integer.toString(type) + Integer.toString(item.mNativeItemId), Integer.toString(item.mNativeItemType), Long.toString(item.mTimestamp) }; - cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID - + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_ID - + "=? AND " + Field.NATIVE_ITEM_TYPE + "=?", args); + cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + + " WHERE " + Field.NATIVE_ITEM_ID + "=? AND " + Field.NATIVE_ITEM_TYPE + "=?" + + " AND " + Field.TIMESTAMP + "=?", args); if (cursor.moveToFirst()) { result = true; } } finally { CloseUtils.close(cursor); } return result; } /** * Returns a string which can be added to the where clause in an SQL query * on the activities table, to filter the result for a specific contact or * name. The clause will prioritise in the following way: * <ol> * <li>Use localContactId - If it not null</li> * <li>Use name - If this is a valid telephone number, the match will be * done to ensure that the same phone number written in different ways will * be included in the group. * </ol> * * @param localContactId The local contact ID, or null if the contact does * not exist in the People database. * @param name A string containing the name, or a telephone number/email * identifying the contact. * @return The where clause string */ private static String fetchNameWhereClause(final Long localContactId, final String name) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNameWhereClause()"); if (localContactId != null) { return Field.LOCAL_CONTACT_ID + "=" + localContactId; } if (name == null) { return null; } final String searchName = DatabaseUtils.sqlEscapeString(name); if (PhoneNumberUtils.isWellFormedSmsAddress(name)) { return "(PHONE_NUMBERS_EQUAL(" + Field.CONTACT_NAME + "," + searchName + ") OR "+ Field.CONTACT_NAME + "=" + searchName+")"; } else { return Field.CONTACT_NAME + "=" + searchName; } } /** * Returns the timeline summary data from the current location of the given * cursor. The cursor can be obtained using * {@link #fetchTimelineEventList(Long, TimelineNativeTypes[], * SQLiteDatabase)} or * {@link #fetchTimelineEventsForContact(Long, Long, String, * TimelineNativeTypes[], SQLiteDatabase)}. * * @param cursor Cursor in the required position. * @return A filled out TimelineSummaryItem object */ public static TimelineSummaryItem getTimelineData(final Cursor cursor) { DatabaseHelper.trace(false, "DatabaseHelper.getTimelineData()"); TimelineSummaryItem item = new TimelineSummaryItem(); item.mLocalActivityId = SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); item.mTimestamp = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); item.mContactName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); if (!cursor.isNull( cursor.getColumnIndex(Field.CONTACT_AVATAR_URL.toString()))) { item.mHasAvatar = true; } item.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); item.mTitle = SqlUtils.setString(cursor, Field.TITLE.toString()); item.mDescription = SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); item.mContactNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); item.mNativeItemType = SqlUtils.setInt(cursor, Field.NATIVE_ITEM_TYPE.toString(), null); item.mNativeItemId = SqlUtils.setInt(cursor, Field.NATIVE_ITEM_ID.toString(), null); item.mType = SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); item.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); item.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); item.mNativeThreadId = SqlUtils.setInt(cursor, Field.NATIVE_THREAD_ID.toString(), null); item.mContactAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); item.mIncoming = SqlUtils.setTimelineSummaryItemType(cursor, Field.INCOMING.toString()); return item; } /** * Fetches timeline events for a specific contact identified by local * contact ID, name or address. Events returned will be in * reverse-chronological order. If a native type list is provided the result * will be filtered by the list. * * @param timeStamp Only events from this time will be returned * @param localContactId The local contact ID if the contact is in the * People database, or null. * @param name The name or address of the contact (required if local contact * ID is NULL). * @param nativeTypes A list of required native types to filter the result, * or null to return all timeline events for the contact. * @param readableDb Readable SQLite database * @param networkName The name of the network the contacts belongs to * (required in order to provide appropriate chat messages * filtering) If the parameter is null messages from all networks * will be returned. The values are the * SocialNetwork.VODAFONE.toString(), * SocialNetwork.GOOGLE.toString(), or * SocialNetwork.MICROSOFT.toString() results. * @return The cursor that can be read using * {@link #getTimelineData(Cursor)}. */ public static Cursor fetchTimelineEventsForContact(final Long timeStamp, final Long localContactId, final String name, final TimelineNativeTypes[] nativeTypes, final String networkName, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "fetchTimelineEventsForContact()"); try { String typesQuery = " AND "; if (nativeTypes.length > 0) { StringBuffer typesQueryBuffer = new StringBuffer(); typesQueryBuffer.append(" AND ("); for (int i = 0; i < nativeTypes.length; i++) { final TimelineNativeTypes type = nativeTypes[i]; typesQueryBuffer.append(Field.NATIVE_ITEM_TYPE + "=" + type.ordinal()); if (i < nativeTypes.length - 1) { typesQueryBuffer.append(" OR "); } } typesQueryBuffer.append(") AND "); typesQuery = typesQueryBuffer.toString(); } /** Filter by account. **/ String networkQuery = ""; String queryNetworkName = networkName; if (queryNetworkName != null) { if (queryNetworkName.equals(SocialNetwork.PC.toString()) || queryNetworkName.equals( SocialNetwork.MOBILE.toString())) { queryNetworkName = SocialNetwork.VODAFONE.toString(); } networkQuery = Field.CONTACT_NETWORK + "='" + queryNetworkName + "' AND "; } String whereAppend; if (localContactId == null) { whereAppend = Field.LOCAL_CONTACT_ID + " IS NULL AND " + fetchNameWhereClause(localContactId, name); if (whereAppend == null) { return null; } } else { whereAppend = Field.LOCAL_CONTACT_ID + "=" + localContactId; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + networkQuery + whereAppend + " ORDER BY " + Field.TIMESTAMP + " ASC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchTimelineEventsForContact() " + "Unable to fetch timeline event for contact list", e); return null; } } /** * Mark the chat timeline events for a given contact as read. * * @param localContactId Local contact ID. * @param networkName Name of the SNS. * @param writableDb Writable SQLite reference. * @return Number of rows affected by database update. */ public static int markChatTimelineEventsForContactAsRead( final Long localContactId, final String networkName, final SQLiteDatabase writableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "fetchTimelineEventsForContact()"); ContentValues values = new ContentValues(); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); String networkQuery = ""; if (networkName != null) { networkQuery = " AND (" + Field.CONTACT_NETWORK + "='" + networkName + "')"; } final String where = Field.LOCAL_CONTACT_ID + "=" + localContactId + " AND " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" /** * If the network is null, set all messages as read for this * contact. */ + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")" + networkQuery; return writableDb.update(TABLE_NAME, values, where, null); } /** * Returns the timestamp for the newest status event for a given server * contact. * * @param local contact id Server contact ID * @param readableDb Readable SQLite database * @return The timestamp in milliseconds, or 0 if not found. */ public static long fetchLatestStatusTimestampForContact(final long localContactId, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "fetchLatestStatusTimestampForContact()"); Cursor cursor = null; try { String query = "SELECT MAX( " + ActivitiesTable.Field.TIMESTAMP + ") FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + " = " + localContactId + " AND " + Field.TYPE + "='" + ActivityItem.Type.CONTACT_SENT_STATUS_UPDATE.toString().toLowerCase() + "'"; cursor = readableDb.rawQuery(query, null); if (cursor.moveToFirst() && !cursor.isNull(0)) { return cursor.getLong(0); } else { return 0; } } finally { CloseUtils.close(cursor); } } /** * Updates timeline when a new contact is added to the People database. * Updates all timeline events that are not associated with a contact and * have a phone number that matches the oldName parameter. * * @param oldName The telephone number (since is the name of an activity * that is not associated with a contact) * @param newName The new name * @param newLocalContactId The local Contact Id for the added contact. * @param newContactId The server Contact Id for the added contact (or null * if the contact has not yet been synced). * @param witeableDb Writable SQLite database */ public static void updateTimelineContactNameAndId(final String oldName, final String newName, final Long newLocalContactId, final Long newContactId, final SQLiteDatabase witeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "updateTimelineContactNameAndId()"); try { ContentValues values = new ContentValues(); if (newName != null) { values.put(Field.CONTACT_NAME.toString(), newName); } else { LogUtils.logE("updateTimelineContactNameAndId() " + "newName should never be null"); } if (newLocalContactId != null) { values.put(Field.LOCAL_CONTACT_ID.toString(), newLocalContactId); } else { LogUtils.logE("updateTimelineContactNameAndId() " + "newLocalContactId should never be null"); } if (newContactId != null) { values.put(Field.CONTACT_ID.toString(), newContactId); } else { /** * newContactId will be null if adding a contact from the UI. */ LogUtils.logI("updateTimelineContactNameAndId() " + "newContactId is null"); /** * We haven't got server Contact it, it means it haven't been * synced yet. */ } String name = ""; if (oldName != null) { name = oldName; LogUtils.logW("ActivitiesTable." + "updateTimelineContactNameAndId() oldName is NULL"); } String[] args = { "2", name }; String whereClause = Field.LOCAL_CONTACT_ID + " IS NULL AND " + Field.FLAG + "=? AND PHONE_NUMBERS_EQUAL(" + Field.CONTACT_ADDRESS + ",?)"; witeableDb.update(TABLE_NAME, values, whereClause, args); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.updateTimelineContactNameAndId() " + "Unable update table", e); throw e; } } /** * Updates the timeline when a contact name is modified in the database. * * @param newName The new name. * @param localContactId Local contact Id which was modified. * @param witeableDb Writable SQLite database */ public static void updateTimelineContactNameAndId(final String newName, final Long localContactId, final SQLiteDatabase witeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "updateTimelineContactNameAndId()"); if (newName == null || localContactId == null) { LogUtils.logE("updateTimelineContactNameAndId() newName or " + "localContactId == null newName(" + newName + ") localContactId(" + localContactId + ")"); return; } try { ContentValues values = new ContentValues(); Long cId = ContactsTable.fetchServerId(localContactId, witeableDb); values.put(Field.CONTACT_NAME.toString(), newName); if (cId != null) { values.put(Field.CONTACT_ID.toString(), cId); } String[] args = { localContactId.toString() }; String whereClause = Field.LOCAL_CONTACT_ID + "=?"; witeableDb.update(TABLE_NAME, values, whereClause, args); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.updateTimelineContactNameAndId()" + " Unable update table", e); } } /** * Updates the timeline entries in the activities table to remove deleted * contact info. * * @param localContactId - the contact id that has been deleted * @param writeableDb - reference to the database */ public static void removeTimelineContactData(final Long localContactId, final SQLiteDatabase writeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "removeTimelineContactData()"); if (localContactId == null) { LogUtils.logE("removeTimelineContactData() localContactId == null " + "localContactId(" + localContactId + ")"); return; } try { //Remove all the Chat Entries removeChatTimelineForContact(localContactId, writeableDb); String[] args = { localContactId.toString() }; String query = "UPDATE " + TABLE_NAME + " SET " + Field.LOCAL_CONTACT_ID + "=NULL, " + Field.CONTACT_ID + "=NULL, " + Field.CONTACT_NAME + "=" + Field.CONTACT_ADDRESS + " WHERE " + Field.LOCAL_CONTACT_ID + "=? AND (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")"; writeableDb.execSQL(query, args); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.removeTimelineContactData() Unable " + "to update table: \n", e); } } /** * Removes all the items from the chat timeline for the given contact. * * @param localContactId Given contact ID. * @param writeableDb Writable SQLite database. */ private static void removeChatTimelineForContact( final Long localContactId, final SQLiteDatabase writeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "removeChatTimelineForContact()"); if (localContactId == null || (localContactId == -1)) { LogUtils.logE("removeChatTimelineForContact() localContactId == " + "null " + "localContactId(" + localContactId + ")"); return; } final String query = Field.LOCAL_CONTACT_ID + "=" + localContactId + " AND (" + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + ")"; try { writeableDb.delete(TABLE_NAME, query, null); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.removeChatTimelineForContact() " + "Unable to update table", e); } } /** * Removes items from the chat timeline that are not for the given contact. * * @param localContactId Given contact ID. * @param writeableDb Writable SQLite database. */ public static void removeChatTimelineExceptForContact( final Long localContactId, final SQLiteDatabase writeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "removeTimelineContactData()"); if (localContactId == null || (localContactId == -1)) { LogUtils.logE("removeTimelineContactData() localContactId == null " + "localContactId(" + localContactId + ")"); return; } try { final long olderThan = System.currentTimeMillis() - Settings.HISTORY_IS_WEEK_LONG; final String query = Field.LOCAL_CONTACT_ID + "!=" + localContactId + " AND (" + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + ") AND (" + Field.TIMESTAMP + "<" + olderThan + ")"; writeableDb.delete(TABLE_NAME, query, null); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.removeTimelineContactData() " + "Unable to update table", e); } } /*** * Returns the number of users have currently have unread chat messages. * * @param readableDb Reference to a readable database. * @return Number of users with unread chat messages. */ public static int getNumberOfUnreadChatUsers( final SQLiteDatabase readableDb) { final String query = "SELECT " + Field.LOCAL_CONTACT_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" /** * This condition below means the timeline is not yet marked * as READ. */ + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; Cursor cursor = null; try { cursor = readableDb.rawQuery(query, null); ArrayList<Long> ids = new ArrayList<Long>(); Long id = null; while (cursor.moveToNext()) { id = cursor.getLong(0); if (!ids.contains(id)) { ids.add(id); } } return ids.size(); } finally { CloseUtils.close(cursor); } } /*** * Returns the number of unread chat messages. * * @param readableDb Reference to a readable database. * @return Number of unread chat messages. */ public static int getNumberOfUnreadChatMessages( final SQLiteDatabase readableDb) { final String query = "SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; Cursor cursor = null; try { cursor = readableDb.rawQuery(query, null); return cursor.getCount(); } finally { CloseUtils.close(cursor); } } /*** * Returns the number of unread chat messages for this contact besides this * network. * * @param localContactId Given contact ID.
360/360-Engine-for-Android
ef21373165d40df0529b7c78620ec858073e8f0c
Changed target value to 200ms and fixed a bug where the import could stop completely on slow devices with low target (since the calculated number of contacts to import would be 0).
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java index c71cb27..13519f9 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java @@ -1,809 +1,808 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import android.text.TextUtils; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.engine.contactsync.NativeContactsApi.Account; import com.vodafone360.people.utils.DynamicArrayLong; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * The NativeImporter class is responsible for importing contacts from the * native address book to the people database. To do so, it compares the native * address book and the people database to find new changes and update the * people database accordingly. Usage: - instantiate the class - call the tick() * method until isDone() returns true - current progress can be obtained via * getPosition() / getCount() - check the getResult() to get a status (OK, * KO...) */ public class NativeImporter { /** * The undefined result when the NativeImporter has not been run yet. * * @see #getResult() */ public final static int RESULT_UNDEFINED = -1; /** * The ok result when the NativeImporter has finished successfully. * * @see #getResult() */ public final static int RESULT_OK = 0; /** * The undefined result when the NativeImporter has not been run yet. * * @see #getResult() */ public final static int RESULT_ERROR = 1; /** * Number of contacts to be processed "per tick". This is the start value * and is adapted to get as close as possible to TARGET_TIME_PER_TICK * * @see #tick() */ private final static float CONTACTS_PER_TICK_START = 2.0F; /** * Ideal processing time per tick in ms */ - private final static float TARGET_TIME_PER_TICK = 1000.0F; + private final static float TARGET_TIME_PER_TICK = 200.0F; /** * Contacts to process in one tick. This float will be rounded. */ private float mContactsPerTick = CONTACTS_PER_TICK_START; /** * Handler to the People Contacts API. */ private PeopleContactsApi mPeopleContactsApi; /** * Handler to the Native Contacts API. */ private NativeContactsApi mNativeContactsApi; /** * Internal state representing the task to perform: gets the list of native * contacts ids and people contacts ids. */ private final static int STATE_GET_IDS_LISTS = 0; /** * Internal state representing the task to perform: iterates through the * list of ids to find differences (i.e. added contact, modified contact, * deleted contact). */ private final static int STATE_ITERATE_THROUGH_IDS = 1; /** * Internal state representing the task to perform: process the list of * deleted contacts (i.e. delete the contacts from the people database). * TODO: remove this state */ private final static int STATE_PROCESS_DELETED = 2; /** * Internal state representing the task to perform: final state, nothing * else to perform. */ private final static int STATE_DONE = 3; /** * The current state. */ private int mState = STATE_GET_IDS_LISTS; /** * The list of native ids from the native side. */ private long[] mNativeContactsIds; /** * The list of native ids from the people side. */ private long[] mPeopleNativeContactsIds; /** * The total count of ids to process (native database + people database). */ private int mTotalIds = 0; /** * The current count of processed ids. */ private int mProcessedIds = 0; /** * The index of the current native id. * * @see #mNativeContactsIds */ private int mCurrentNativeId = 0; /** * The index in the current people id. * * @see #mPeopleNativeContactsIds */ private int mCurrentPeopleId = 0; /** * The index of the current deleted people id. * * @see #mDeletedIds */ private int mCurrentDeletedId = 0; /** * Array to store the people ids of contacts to delete. */ private DynamicArrayLong mDeletedIds = new DynamicArrayLong(10); /** * The result status. */ private int mResult = RESULT_UNDEFINED; /** * Instance of a ContactChange comparator. */ private NCCComparator mNCCC = new NCCComparator(); /** * The array of accounts from where to import the native contacts. Note: if * null, will import from the platform default account. */ private Account[] mAccounts = null; /** * Boolean that tracks if the first time Import for 2.X is ongoing. */ private boolean mIsFirstImportOn2X = false; /** * Constructor. * * @param pca handler to the People contacts Api * @param nca handler to the Native contacts Api * @param firstTimeImport true if we import from native for the first time, * false if not */ public NativeImporter(PeopleContactsApi pca, NativeContactsApi nca, boolean firstTimeImport) { mPeopleContactsApi = pca; mNativeContactsApi = nca; initAccounts(firstTimeImport); } /** * Sets the accounts used to import the native contacs. */ private void initAccounts(boolean firstTimeImport) { /** * In case of Android 2.X, the accounts used are different depending if * it's first time sync or not. On Android 1.X, we can just ignore the * accounts logic as not supported by the platform. At first time sync, * we need to import the native contacts from all the Google accounts. * These native contacts are then stored in the 360 People account and * native changes will be only detected from the 360 People account. */ if (VersionUtils.is2XPlatform()) { // account to import from: 360 account if created, all the google // accounts otherwise if (firstTimeImport) { ArrayList<Account> accountList = new ArrayList<Account>(); Account googleAccounts[] = mNativeContactsApi.getAccountsByType(NativeContactsApi.GOOGLE_ACCOUNT_TYPE); if (googleAccounts!=null ){ for (Account account : googleAccounts) { accountList.add(account); } } Account phoneAccounts[] = mNativeContactsApi.getAccountsByType(NativeContactsApi.PHONE_ACCOUNT_TYPE); if (phoneAccounts!=null){ for (Account account : phoneAccounts) { accountList.add(account); } } mAccounts = accountList.toArray(new Account[0]); } else { mAccounts = mNativeContactsApi .getAccountsByType(NativeContactsApi.PEOPLE_ACCOUNT_TYPE); } if (firstTimeImport) mIsFirstImportOn2X = true; } } /** * Sets the internal state to DONE with the provided result status. * * @param result the result status to set */ private void complete(int result) { mState = STATE_DONE; mResult = result; } /** * Tick method to call each time there is time for processing the native * contacts import. Note: the method will block for some time to process a * certain amount of contact then will return. It will have to be called * until it returns true meaning that the import is over. * * @return true when the import task is finished, false if not */ public boolean tick() { long startTime = System.currentTimeMillis(); switch (mState) { case STATE_GET_IDS_LISTS: getIdsLists(); break; case STATE_ITERATE_THROUGH_IDS: iterateThroughNativeIds(); break; case STATE_PROCESS_DELETED: processDeleted(); break; } long processingTime = System.currentTimeMillis() - startTime; float factor = TARGET_TIME_PER_TICK / processingTime; - - mContactsPerTick = mContactsPerTick * factor; + mContactsPerTick = Math.max(1.0F, mContactsPerTick * factor); LogUtils.logD("NativeImporter.tick(): Tick took " + processingTime + "ms, applying factor "+ factor + ". Contacts per tick: " + mContactsPerTick); return isDone(); } /** * Returns the import state. * * @return true if the import is finished, false if not */ public boolean isDone() { return mState == STATE_DONE; } /** * Gets the import result. * * @see #RESULT_OK * @see #RESULT_ERROR * @see #RESULT_UNDEFINED * @return the import result */ public int getResult() { return mResult; } /** * Gets the current position in the list of ids. This can be used to track * the current progress. * * @see #getCount() * @return the last processed id position in the list of ids */ public int getPosition() { return mProcessedIds; } /** * Gets the total number of ids to process. * * @return the number of ids to process */ public int getCount() { return mTotalIds; } /** * Gets the list of native and people contacts ids. */ private void getIdsLists() { LogUtils.logD("NativeImporter.getIdsLists()"); // Get the list of native ids for the contacts if (mAccounts == null || 0 == mAccounts.length) { // default account LogUtils.logD("NativeImporter.getIdsLists() - using default account"); mNativeContactsIds = mNativeContactsApi.getContactIds(null); } else if (mAccounts.length == 1) { // one account LogUtils.logD("NativeImporter.getIdsLists() - one account found: " + mAccounts[0]); mNativeContactsIds = mNativeContactsApi.getContactIds(mAccounts[0]); } else { // we need to merge the ids from different accounts and sort them final DynamicArrayLong allIds = new DynamicArrayLong(); LogUtils.logD("NativeImporter.getIdsLists() - more than one account found."); for (int i = 0; i < mAccounts.length; i++) { LogUtils.logD("NativeImporter.getIdsLists() - account=" + mAccounts[i]); final long[] ids = mNativeContactsApi.getContactIds(mAccounts[i]); if (ids != null) { allIds.add(ids); } } mNativeContactsIds = allIds.toArray(); // sort the ids // TODO: as the arrays to merge are sorted, consider merging while // keeping the sorting // which is faster than sorting them afterwards if (mNativeContactsIds != null) { Arrays.sort(mNativeContactsIds); } } // check if we have some work to do if (mNativeContactsIds == null) { complete(RESULT_OK); return; } // Get a list of native ids for the contacts we have in the People // database mPeopleNativeContactsIds = mPeopleContactsApi.getNativeContactsIds(); mTotalIds = mNativeContactsIds.length; if (mPeopleNativeContactsIds != null) { mTotalIds += mPeopleNativeContactsIds.length; } mState = STATE_ITERATE_THROUGH_IDS; } /** * Iterates through the list of native and People ids to detect changes. */ private void iterateThroughNativeIds() { LogUtils.logD("NativeImporter.iterateThroughNativeIds()"); final int limit = Math.min(mNativeContactsIds.length, mCurrentNativeId + Math.round(mContactsPerTick)); // TODO: remove the deleted state / queuing to deleted ids array and // loop with while (mProcessedIds < limit) while (mCurrentNativeId < limit) { if (mPeopleNativeContactsIds == null) { // no native contacts on people side, just add it LogUtils.logD("NativeImporter.iterateThroughNativeIds(): found a new contact"); addNewContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; } else { // both ids lists are ordered by ascending ids so // every people ids that are before the current native ids // are simply deleted contacts while ((mCurrentPeopleId < mPeopleNativeContactsIds.length) && (mPeopleNativeContactsIds[mCurrentPeopleId] < mNativeContactsIds[mCurrentNativeId])) { LogUtils .logD("NativeImporter.iterateThroughNativeIds(): found a contact to delete"); mDeletedIds.add(mPeopleNativeContactsIds[mCurrentPeopleId++]); } if (mCurrentPeopleId == mPeopleNativeContactsIds.length || mPeopleNativeContactsIds[mCurrentPeopleId] > mNativeContactsIds[mCurrentNativeId]) { // has to be a new contact LogUtils.logD("NativeImporter.iterateThroughNativeIds(): found a new contact"); addNewContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; } else { // has to be an existing contact or one that will be deleted LogUtils .logD("NativeImporter.iterateThroughNativeIds(): check existing contact"); checkExistingContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; mCurrentPeopleId++; } } mCurrentNativeId++; } // check if we are done with ids list from native if (mCurrentNativeId == mNativeContactsIds.length) { // we've gone through the native list, any remaining ids from the // people list are deleted ones if (mPeopleNativeContactsIds != null) { while (mCurrentPeopleId < mPeopleNativeContactsIds.length) { LogUtils .logD("NativeImporter.iterateThroughNativeIds(): found a contact to delete"); mDeletedIds.add(mPeopleNativeContactsIds[mCurrentPeopleId++]); } } if (mDeletedIds.size() != 0) { // Some deleted contacts to handle mState = STATE_PROCESS_DELETED; } else { // Nothing else to do complete(RESULT_OK); } } } /** * Deletes the contacts that were added the deleted array. */ private void processDeleted() { LogUtils.logD("NativeImporter.processDeleted()"); final int limit = Math.min(mDeletedIds.size(), mCurrentDeletedId + Math.round(mContactsPerTick)); while (mCurrentDeletedId < limit) { // we now delete the contacts on people client side // on the 2.X platform, the contact deletion has to be synced back // to native once completed because the // contact is still there on native, just marked as deleted and // waiting for its explicit removal mPeopleContactsApi.deleteNativeContact(mDeletedIds.get(mCurrentDeletedId++), VersionUtils.is2XPlatform()); mProcessedIds++; } if (mCurrentDeletedId == mDeletedIds.size()) { complete(RESULT_OK); } } /** * Adds a new contact to the people database. */ private void addNewContact(long nativeId) { // get the contact data final ContactChange[] contactChanges = mNativeContactsApi.getContact(nativeId); if (contactChanges != null) { if (mIsFirstImportOn2X) { // Override the nativeContactId with an invalid id if we are on // 2.X // and we are doing a first time import because the native id // does not correspond // to the id from the 360 People account where we will export. removeNativeIds(contactChanges); } else { // Force a nativeDetailId to details that have none so that the // comparison // later can be made (see computeDelta method). forceNabDetailId(contactChanges); } // add the contact to the People database if (!mPeopleContactsApi.addNativeContact(contactChanges)) { // TODO: Handle the error case !!! Well how should we handle it: // fail for all remaining contacts or skip the failing contact? LogUtils .logE("NativeImporter.addNewContact() - failed to import native contact id=" + nativeId); } } } /** * Check changes between an existing contact on both native and people * database. * * @param nativeId the native id of the contact to check */ private void checkExistingContact(long nativeId) { // get the native version of that contact final ContactChange[] nativeContact = mNativeContactsApi.getContact(nativeId); // get the people version of that contact final ContactChange[] peopleContact = mPeopleContactsApi.getContact((int)nativeId); if (peopleContact == null) { // we shouldn't be in that situation but nothing to do about it // this means that there were some changes in the meantime between // getting the ids list and now return; } else if (nativeContact == null) { LogUtils .logD("NativeImporter.checkExistingContact(): found a contact marked as deleted"); // this is a 2.X specific case meaning that the contact is marked as // deleted on native side // and waiting for the "syncAdapter" to perform a real delete mDeletedIds.add(nativeId); } else { // general case, find the delta final ContactChange[] delta = computeDelta(peopleContact, nativeContact); if (delta != null) { // update CAB with delta changes mPeopleContactsApi.updateNativeContact(delta); } } } /** * Native ContactChange Comparator class. This class compares ContactChange * and tells which one is greater depending on the key and then the native * detail id. */ private static class NCCComparator implements Comparator<ContactChange> { @Override public int compare(ContactChange change1, ContactChange change2) { // an integer < 0 if object1 is less than object2, 0 if they are // equal, and > 0 if object1 is greater than object2. final int key1 = change1.getKey(); final int key2 = change2.getKey(); if (key1 < key2) { return -1; } else if (key1 > key2) { return 1; } else { // the keys are identical, check the native ids final long id1 = change1.getNabDetailId(); final long id2 = change2.getNabDetailId(); if (id1 < id2) { return -1; } else if (id1 > id2) { return 1; } else { return 0; } } } } /** * Sorts the provided array of ContactChange by key and native id. Note: the * method will rearrange the provided array. * * @param changes the ContactChange array to sort */ private void sortContactChanges(ContactChange[] changes) { if ((changes != null) && (changes.length > 1)) { Arrays.sort(changes, mNCCC); } } /** * Computes the difference between the provided arrays of ContactChange. The * delta are the changes to apply to the master ContactChange array to make * it similar to the new changes ContactChange array. (i.e. delete details, * add details or modify details) NOTE: to help the GC, some provided * ContactChange may be modified and returned by the method instead of * creating new ones. * * @param masterChanges the master array of ContactChange (i.e. the original * one) * @param newChanges the new ContactChange array (i.e. contains the new * version of a contact) * @return null if there are no changes or the contact is being deleted, an * array for ContactChange to apply to the master contact if * differences where found */ private ContactChange[] computeDelta(ContactChange[] masterChanges, ContactChange[] newChanges) { LogUtils.logD("NativeImporter.computeDelta()"); // set the native contact id to details that don't have a native detail // id for the comparison as // this is also done on people database side forceNabDetailId(newChanges); // sort the changes by key then native detail id sortContactChanges(masterChanges); sortContactChanges(newChanges); // if the master contact is being deleted, ignore new changes if ((masterChanges[0].getType() & ContactChange.TYPE_DELETE_CONTACT) == ContactChange.TYPE_DELETE_CONTACT) { return null; } // details comparison, skip deleted master details final ContactChange[] deltaChanges = new ContactChange[masterChanges.length + newChanges.length]; int deltaIndex = 0; int masterIndex = 0; int newIndex = 0; while (newIndex < newChanges.length) { while ((masterIndex < masterChanges.length) && (mNCCC.compare(masterChanges[masterIndex], newChanges[newIndex]) < 0)) { final ContactChange masterChange = masterChanges[masterIndex]; if ((masterChange.getType() & ContactChange.TYPE_DELETE_DETAIL) != ContactChange.TYPE_DELETE_DETAIL && (masterChange.getNabDetailId() != ContactChange.INVALID_ID) && (isContactChangeKeySupported(masterChange))) { // this detail does not exist anymore, is not being deleted // and was synced to native // check if it can be deleted (or has to be updated) setDetailForDeleteOrUpdate(masterChanges, masterIndex); deltaChanges[deltaIndex++] = masterChanges[masterIndex]; } masterIndex++; } if ((masterIndex < masterChanges.length) && (mNCCC.compare(newChanges[newIndex], masterChanges[masterIndex]) == 0)) { // similar key and id, check for differences at value level and // flags final ContactChange masterDetail = masterChanges[masterIndex]; final ContactChange newDetail = newChanges[newIndex]; boolean different = false; if (masterDetail.getFlags() != newDetail.getFlags()) { different = true; } if (!areContactChangeValuesEqualsPlusFix(masterChanges, masterIndex, newChanges, newIndex)) { different = true; } if (different) { // found a detail to update LogUtils.logD("NativeImporter.computeDelta() - found a detail to update"); newDetail.setType(ContactChange.TYPE_UPDATE_DETAIL); newDetail.setInternalContactId(masterDetail.getInternalContactId()); newDetail.setInternalDetailId(masterDetail.getInternalDetailId()); deltaChanges[deltaIndex++] = newDetail; } masterIndex++; } else { LogUtils.logD("NativeImporter.computeDelta() - found a detail to add"); // this is a new detail newChanges[newIndex].setType(ContactChange.TYPE_ADD_DETAIL); newChanges[newIndex].setInternalContactId(masterChanges[0].getInternalContactId()); deltaChanges[deltaIndex++] = newChanges[newIndex]; } newIndex++; } while (masterIndex < masterChanges.length) { final ContactChange masterChange = masterChanges[masterIndex]; if ((masterChange.getType() & ContactChange.TYPE_DELETE_DETAIL) != ContactChange.TYPE_DELETE_DETAIL && (masterChange.getNabDetailId() != ContactChange.INVALID_ID) && (isContactChangeKeySupported(masterChange))) { // this detail does not exist anymore, is not being deleted and // was synced to native // check if it can be deleted (or has to be updated) setDetailForDeleteOrUpdate(masterChanges, masterIndex); deltaChanges[deltaIndex++] = masterChanges[masterIndex]; } masterIndex++; } if (deltaIndex == 0) { // the contact has not changed return null; } else if (deltaChanges.length == deltaIndex) { // give the detail changes return deltaChanges; } else { // give the detail changes but need to trim final ContactChange[] trim = new ContactChange[deltaIndex]; System.arraycopy(deltaChanges, 0, trim, 0, deltaIndex); return trim; } } /** * Removes the native ids in case of a first time import on the Android 2.X * platform. * * @param contact the contact to clear from native ids */ private void removeNativeIds(ContactChange[] contact) { if (contact != null) { final int count = contact.length; for (int i = 0; i < count; i++) { final ContactChange change = contact[i]; change.setNabContactId(ContactChange.INVALID_ID); change.setNabDetailId(ContactChange.INVALID_ID); } } } /** * Forces a native detail id onto a detail that does not have one by setting * it to be the native contact id.
360/360-Engine-for-Android
64adb77d6433120cd732fa48b197cdbfae80703c
Now adapting the number of contacts processed per tick to match a specified amount of processing time, so that the speed adapts to the device. We still need to figure out the ideal target time.
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java index f11b205..c71cb27 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java @@ -1,948 +1,968 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import android.text.TextUtils; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.engine.contactsync.NativeContactsApi.Account; import com.vodafone360.people.utils.DynamicArrayLong; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * The NativeImporter class is responsible for importing contacts from the * native address book to the people database. To do so, it compares the native * address book and the people database to find new changes and update the * people database accordingly. Usage: - instantiate the class - call the tick() * method until isDone() returns true - current progress can be obtained via * getPosition() / getCount() - check the getResult() to get a status (OK, * KO...) */ public class NativeImporter { /** * The undefined result when the NativeImporter has not been run yet. * * @see #getResult() */ public final static int RESULT_UNDEFINED = -1; /** * The ok result when the NativeImporter has finished successfully. * * @see #getResult() */ public final static int RESULT_OK = 0; /** * The undefined result when the NativeImporter has not been run yet. * * @see #getResult() */ public final static int RESULT_ERROR = 1; /** - * Number of contacts to be processed "per tick". + * Number of contacts to be processed "per tick". This is the start value + * and is adapted to get as close as possible to TARGET_TIME_PER_TICK * * @see #tick() */ - private final static int MAX_CONTACTS_OPERATION_COUNT = 2; + private final static float CONTACTS_PER_TICK_START = 2.0F; + + /** + * Ideal processing time per tick in ms + */ + private final static float TARGET_TIME_PER_TICK = 1000.0F; + + /** + * Contacts to process in one tick. This float will be rounded. + */ + private float mContactsPerTick = CONTACTS_PER_TICK_START; /** * Handler to the People Contacts API. */ private PeopleContactsApi mPeopleContactsApi; /** * Handler to the Native Contacts API. */ private NativeContactsApi mNativeContactsApi; /** * Internal state representing the task to perform: gets the list of native * contacts ids and people contacts ids. */ private final static int STATE_GET_IDS_LISTS = 0; /** * Internal state representing the task to perform: iterates through the * list of ids to find differences (i.e. added contact, modified contact, * deleted contact). */ private final static int STATE_ITERATE_THROUGH_IDS = 1; /** * Internal state representing the task to perform: process the list of * deleted contacts (i.e. delete the contacts from the people database). * TODO: remove this state */ private final static int STATE_PROCESS_DELETED = 2; /** * Internal state representing the task to perform: final state, nothing * else to perform. */ private final static int STATE_DONE = 3; /** * The current state. */ private int mState = STATE_GET_IDS_LISTS; /** * The list of native ids from the native side. */ private long[] mNativeContactsIds; /** * The list of native ids from the people side. */ private long[] mPeopleNativeContactsIds; /** * The total count of ids to process (native database + people database). */ private int mTotalIds = 0; /** * The current count of processed ids. */ private int mProcessedIds = 0; /** * The index of the current native id. * * @see #mNativeContactsIds */ private int mCurrentNativeId = 0; /** * The index in the current people id. * * @see #mPeopleNativeContactsIds */ private int mCurrentPeopleId = 0; /** * The index of the current deleted people id. * * @see #mDeletedIds */ private int mCurrentDeletedId = 0; /** * Array to store the people ids of contacts to delete. */ private DynamicArrayLong mDeletedIds = new DynamicArrayLong(10); /** * The result status. */ private int mResult = RESULT_UNDEFINED; /** * Instance of a ContactChange comparator. */ private NCCComparator mNCCC = new NCCComparator(); /** * The array of accounts from where to import the native contacts. Note: if * null, will import from the platform default account. */ private Account[] mAccounts = null; /** * Boolean that tracks if the first time Import for 2.X is ongoing. */ private boolean mIsFirstImportOn2X = false; /** * Constructor. * * @param pca handler to the People contacts Api * @param nca handler to the Native contacts Api * @param firstTimeImport true if we import from native for the first time, * false if not */ public NativeImporter(PeopleContactsApi pca, NativeContactsApi nca, boolean firstTimeImport) { mPeopleContactsApi = pca; mNativeContactsApi = nca; initAccounts(firstTimeImport); } /** * Sets the accounts used to import the native contacs. */ private void initAccounts(boolean firstTimeImport) { /** * In case of Android 2.X, the accounts used are different depending if * it's first time sync or not. On Android 1.X, we can just ignore the * accounts logic as not supported by the platform. At first time sync, * we need to import the native contacts from all the Google accounts. * These native contacts are then stored in the 360 People account and * native changes will be only detected from the 360 People account. */ if (VersionUtils.is2XPlatform()) { // account to import from: 360 account if created, all the google // accounts otherwise if (firstTimeImport) { ArrayList<Account> accountList = new ArrayList<Account>(); Account googleAccounts[] = mNativeContactsApi.getAccountsByType(NativeContactsApi.GOOGLE_ACCOUNT_TYPE); if (googleAccounts!=null ){ for (Account account : googleAccounts) { accountList.add(account); } } Account phoneAccounts[] = mNativeContactsApi.getAccountsByType(NativeContactsApi.PHONE_ACCOUNT_TYPE); if (phoneAccounts!=null){ for (Account account : phoneAccounts) { accountList.add(account); } } mAccounts = accountList.toArray(new Account[0]); } else { mAccounts = mNativeContactsApi .getAccountsByType(NativeContactsApi.PEOPLE_ACCOUNT_TYPE); } if (firstTimeImport) mIsFirstImportOn2X = true; } } /** * Sets the internal state to DONE with the provided result status. * * @param result the result status to set */ private void complete(int result) { mState = STATE_DONE; mResult = result; } /** * Tick method to call each time there is time for processing the native * contacts import. Note: the method will block for some time to process a * certain amount of contact then will return. It will have to be called * until it returns true meaning that the import is over. * * @return true when the import task is finished, false if not */ public boolean tick() { + + long startTime = System.currentTimeMillis(); switch (mState) { case STATE_GET_IDS_LISTS: getIdsLists(); break; case STATE_ITERATE_THROUGH_IDS: iterateThroughNativeIds(); break; case STATE_PROCESS_DELETED: processDeleted(); break; } + + long processingTime = System.currentTimeMillis() - startTime; + float factor = TARGET_TIME_PER_TICK / processingTime; + + mContactsPerTick = mContactsPerTick * factor; + + LogUtils.logD("NativeImporter.tick(): Tick took " + processingTime + "ms, applying factor "+ factor + ". Contacts per tick: " + mContactsPerTick); return isDone(); } /** * Returns the import state. * * @return true if the import is finished, false if not */ public boolean isDone() { return mState == STATE_DONE; } /** * Gets the import result. * * @see #RESULT_OK * @see #RESULT_ERROR * @see #RESULT_UNDEFINED * @return the import result */ public int getResult() { return mResult; } /** * Gets the current position in the list of ids. This can be used to track * the current progress. * * @see #getCount() * @return the last processed id position in the list of ids */ public int getPosition() { return mProcessedIds; } /** * Gets the total number of ids to process. * * @return the number of ids to process */ public int getCount() { return mTotalIds; } /** * Gets the list of native and people contacts ids. */ private void getIdsLists() { LogUtils.logD("NativeImporter.getIdsLists()"); // Get the list of native ids for the contacts if (mAccounts == null || 0 == mAccounts.length) { // default account LogUtils.logD("NativeImporter.getIdsLists() - using default account"); mNativeContactsIds = mNativeContactsApi.getContactIds(null); } else if (mAccounts.length == 1) { // one account LogUtils.logD("NativeImporter.getIdsLists() - one account found: " + mAccounts[0]); mNativeContactsIds = mNativeContactsApi.getContactIds(mAccounts[0]); } else { // we need to merge the ids from different accounts and sort them final DynamicArrayLong allIds = new DynamicArrayLong(); LogUtils.logD("NativeImporter.getIdsLists() - more than one account found."); for (int i = 0; i < mAccounts.length; i++) { LogUtils.logD("NativeImporter.getIdsLists() - account=" + mAccounts[i]); final long[] ids = mNativeContactsApi.getContactIds(mAccounts[i]); if (ids != null) { allIds.add(ids); } } mNativeContactsIds = allIds.toArray(); // sort the ids // TODO: as the arrays to merge are sorted, consider merging while // keeping the sorting // which is faster than sorting them afterwards if (mNativeContactsIds != null) { Arrays.sort(mNativeContactsIds); } } // check if we have some work to do if (mNativeContactsIds == null) { complete(RESULT_OK); return; } // Get a list of native ids for the contacts we have in the People // database mPeopleNativeContactsIds = mPeopleContactsApi.getNativeContactsIds(); mTotalIds = mNativeContactsIds.length; if (mPeopleNativeContactsIds != null) { mTotalIds += mPeopleNativeContactsIds.length; } mState = STATE_ITERATE_THROUGH_IDS; } /** * Iterates through the list of native and People ids to detect changes. */ private void iterateThroughNativeIds() { LogUtils.logD("NativeImporter.iterateThroughNativeIds()"); final int limit = Math.min(mNativeContactsIds.length, mCurrentNativeId - + MAX_CONTACTS_OPERATION_COUNT); + + Math.round(mContactsPerTick)); // TODO: remove the deleted state / queuing to deleted ids array and // loop with while (mProcessedIds < limit) while (mCurrentNativeId < limit) { if (mPeopleNativeContactsIds == null) { // no native contacts on people side, just add it LogUtils.logD("NativeImporter.iterateThroughNativeIds(): found a new contact"); addNewContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; } else { // both ids lists are ordered by ascending ids so // every people ids that are before the current native ids // are simply deleted contacts while ((mCurrentPeopleId < mPeopleNativeContactsIds.length) && (mPeopleNativeContactsIds[mCurrentPeopleId] < mNativeContactsIds[mCurrentNativeId])) { LogUtils .logD("NativeImporter.iterateThroughNativeIds(): found a contact to delete"); mDeletedIds.add(mPeopleNativeContactsIds[mCurrentPeopleId++]); } if (mCurrentPeopleId == mPeopleNativeContactsIds.length || mPeopleNativeContactsIds[mCurrentPeopleId] > mNativeContactsIds[mCurrentNativeId]) { // has to be a new contact LogUtils.logD("NativeImporter.iterateThroughNativeIds(): found a new contact"); addNewContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; } else { // has to be an existing contact or one that will be deleted LogUtils .logD("NativeImporter.iterateThroughNativeIds(): check existing contact"); checkExistingContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; mCurrentPeopleId++; } } mCurrentNativeId++; } // check if we are done with ids list from native if (mCurrentNativeId == mNativeContactsIds.length) { // we've gone through the native list, any remaining ids from the // people list are deleted ones if (mPeopleNativeContactsIds != null) { while (mCurrentPeopleId < mPeopleNativeContactsIds.length) { LogUtils .logD("NativeImporter.iterateThroughNativeIds(): found a contact to delete"); mDeletedIds.add(mPeopleNativeContactsIds[mCurrentPeopleId++]); } } if (mDeletedIds.size() != 0) { // Some deleted contacts to handle mState = STATE_PROCESS_DELETED; } else { // Nothing else to do complete(RESULT_OK); } } } /** * Deletes the contacts that were added the deleted array. */ private void processDeleted() { LogUtils.logD("NativeImporter.processDeleted()"); final int limit = Math.min(mDeletedIds.size(), mCurrentDeletedId - + MAX_CONTACTS_OPERATION_COUNT); + + Math.round(mContactsPerTick)); while (mCurrentDeletedId < limit) { // we now delete the contacts on people client side // on the 2.X platform, the contact deletion has to be synced back // to native once completed because the // contact is still there on native, just marked as deleted and // waiting for its explicit removal mPeopleContactsApi.deleteNativeContact(mDeletedIds.get(mCurrentDeletedId++), VersionUtils.is2XPlatform()); mProcessedIds++; } if (mCurrentDeletedId == mDeletedIds.size()) { complete(RESULT_OK); } } /** * Adds a new contact to the people database. */ private void addNewContact(long nativeId) { // get the contact data final ContactChange[] contactChanges = mNativeContactsApi.getContact(nativeId); if (contactChanges != null) { if (mIsFirstImportOn2X) { // Override the nativeContactId with an invalid id if we are on // 2.X // and we are doing a first time import because the native id // does not correspond // to the id from the 360 People account where we will export. removeNativeIds(contactChanges); } else { // Force a nativeDetailId to details that have none so that the // comparison // later can be made (see computeDelta method). forceNabDetailId(contactChanges); } // add the contact to the People database if (!mPeopleContactsApi.addNativeContact(contactChanges)) { // TODO: Handle the error case !!! Well how should we handle it: // fail for all remaining contacts or skip the failing contact? LogUtils .logE("NativeImporter.addNewContact() - failed to import native contact id=" + nativeId); } } } /** * Check changes between an existing contact on both native and people * database. * * @param nativeId the native id of the contact to check */ private void checkExistingContact(long nativeId) { // get the native version of that contact final ContactChange[] nativeContact = mNativeContactsApi.getContact(nativeId); // get the people version of that contact final ContactChange[] peopleContact = mPeopleContactsApi.getContact((int)nativeId); if (peopleContact == null) { // we shouldn't be in that situation but nothing to do about it // this means that there were some changes in the meantime between // getting the ids list and now return; } else if (nativeContact == null) { LogUtils .logD("NativeImporter.checkExistingContact(): found a contact marked as deleted"); // this is a 2.X specific case meaning that the contact is marked as // deleted on native side // and waiting for the "syncAdapter" to perform a real delete mDeletedIds.add(nativeId); } else { // general case, find the delta final ContactChange[] delta = computeDelta(peopleContact, nativeContact); if (delta != null) { // update CAB with delta changes mPeopleContactsApi.updateNativeContact(delta); } } } /** * Native ContactChange Comparator class. This class compares ContactChange * and tells which one is greater depending on the key and then the native * detail id. */ private static class NCCComparator implements Comparator<ContactChange> { @Override public int compare(ContactChange change1, ContactChange change2) { // an integer < 0 if object1 is less than object2, 0 if they are // equal, and > 0 if object1 is greater than object2. final int key1 = change1.getKey(); final int key2 = change2.getKey(); if (key1 < key2) { return -1; } else if (key1 > key2) { return 1; } else { // the keys are identical, check the native ids final long id1 = change1.getNabDetailId(); final long id2 = change2.getNabDetailId(); if (id1 < id2) { return -1; } else if (id1 > id2) { return 1; } else { return 0; } } } } /** * Sorts the provided array of ContactChange by key and native id. Note: the * method will rearrange the provided array. * * @param changes the ContactChange array to sort */ private void sortContactChanges(ContactChange[] changes) { if ((changes != null) && (changes.length > 1)) { Arrays.sort(changes, mNCCC); } } /** * Computes the difference between the provided arrays of ContactChange. The * delta are the changes to apply to the master ContactChange array to make * it similar to the new changes ContactChange array. (i.e. delete details, * add details or modify details) NOTE: to help the GC, some provided * ContactChange may be modified and returned by the method instead of * creating new ones. * * @param masterChanges the master array of ContactChange (i.e. the original * one) * @param newChanges the new ContactChange array (i.e. contains the new * version of a contact) * @return null if there are no changes or the contact is being deleted, an * array for ContactChange to apply to the master contact if * differences where found */ private ContactChange[] computeDelta(ContactChange[] masterChanges, ContactChange[] newChanges) { LogUtils.logD("NativeImporter.computeDelta()"); // set the native contact id to details that don't have a native detail // id for the comparison as // this is also done on people database side forceNabDetailId(newChanges); // sort the changes by key then native detail id sortContactChanges(masterChanges); sortContactChanges(newChanges); // if the master contact is being deleted, ignore new changes if ((masterChanges[0].getType() & ContactChange.TYPE_DELETE_CONTACT) == ContactChange.TYPE_DELETE_CONTACT) { return null; } // details comparison, skip deleted master details final ContactChange[] deltaChanges = new ContactChange[masterChanges.length + newChanges.length]; int deltaIndex = 0; int masterIndex = 0; int newIndex = 0; while (newIndex < newChanges.length) { while ((masterIndex < masterChanges.length) && (mNCCC.compare(masterChanges[masterIndex], newChanges[newIndex]) < 0)) { final ContactChange masterChange = masterChanges[masterIndex]; if ((masterChange.getType() & ContactChange.TYPE_DELETE_DETAIL) != ContactChange.TYPE_DELETE_DETAIL && (masterChange.getNabDetailId() != ContactChange.INVALID_ID) && (isContactChangeKeySupported(masterChange))) { // this detail does not exist anymore, is not being deleted // and was synced to native // check if it can be deleted (or has to be updated) setDetailForDeleteOrUpdate(masterChanges, masterIndex); deltaChanges[deltaIndex++] = masterChanges[masterIndex]; } masterIndex++; } if ((masterIndex < masterChanges.length) && (mNCCC.compare(newChanges[newIndex], masterChanges[masterIndex]) == 0)) { // similar key and id, check for differences at value level and // flags final ContactChange masterDetail = masterChanges[masterIndex]; final ContactChange newDetail = newChanges[newIndex]; boolean different = false; if (masterDetail.getFlags() != newDetail.getFlags()) { different = true; } if (!areContactChangeValuesEqualsPlusFix(masterChanges, masterIndex, newChanges, newIndex)) { different = true; } if (different) { // found a detail to update LogUtils.logD("NativeImporter.computeDelta() - found a detail to update"); newDetail.setType(ContactChange.TYPE_UPDATE_DETAIL); newDetail.setInternalContactId(masterDetail.getInternalContactId()); newDetail.setInternalDetailId(masterDetail.getInternalDetailId()); deltaChanges[deltaIndex++] = newDetail; } masterIndex++; } else { LogUtils.logD("NativeImporter.computeDelta() - found a detail to add"); // this is a new detail newChanges[newIndex].setType(ContactChange.TYPE_ADD_DETAIL); newChanges[newIndex].setInternalContactId(masterChanges[0].getInternalContactId()); deltaChanges[deltaIndex++] = newChanges[newIndex]; } newIndex++; } while (masterIndex < masterChanges.length) { final ContactChange masterChange = masterChanges[masterIndex]; if ((masterChange.getType() & ContactChange.TYPE_DELETE_DETAIL) != ContactChange.TYPE_DELETE_DETAIL && (masterChange.getNabDetailId() != ContactChange.INVALID_ID) && (isContactChangeKeySupported(masterChange))) { // this detail does not exist anymore, is not being deleted and // was synced to native // check if it can be deleted (or has to be updated) setDetailForDeleteOrUpdate(masterChanges, masterIndex); deltaChanges[deltaIndex++] = masterChanges[masterIndex]; } masterIndex++; } if (deltaIndex == 0) { // the contact has not changed return null; } else if (deltaChanges.length == deltaIndex) { // give the detail changes return deltaChanges; } else { // give the detail changes but need to trim final ContactChange[] trim = new ContactChange[deltaIndex]; System.arraycopy(deltaChanges, 0, trim, 0, deltaIndex); return trim; } } /** * Removes the native ids in case of a first time import on the Android 2.X * platform. * * @param contact the contact to clear from native ids */ private void removeNativeIds(ContactChange[] contact) { if (contact != null) { final int count = contact.length; for (int i = 0; i < count; i++) { final ContactChange change = contact[i]; change.setNabContactId(ContactChange.INVALID_ID); change.setNabDetailId(ContactChange.INVALID_ID); } } } /** * Forces a native detail id onto a detail that does not have one by setting * it to be the native contact id. * * @param contact the contact to fix */ private void forceNabDetailId(ContactChange[] contact) { if (contact != null && contact.length > 0) { final long nativeContactId = contact[0].getNabContactId(); final int count = contact.length; for (int i = 0; i < count; i++) { final ContactChange change = contact[i]; if (change.getNabDetailId() == ContactChange.INVALID_ID) { change.setNabDetailId(nativeContactId); } } } } /* * Below this point, all the defined methods where added to support the * specific case of KEY_VCARD_ORG on Android 1.X platform. KEY_VCARD_ORG is * defined as followed: "company;department1;department2;...;departmentX" It * is a special case because this VCard key on its own is not fully * supported on the Android 1.X platform: only "company" information is. */ /** * Tells whether or not a master change is equal to a new change and * performs some modifications on the provided new change in the specific * case of KEY_VCARD_ORG on Android 1.X. * * @param masterChanges the array of master changes * @param masterIndex the index of the change within the array of master * changes * @param newChanges the array of new changes * @param newIndex the index of the change within the array of new changes * @return true if the changes are equals, false otherwise */ private boolean areContactChangeValuesEqualsPlusFix(ContactChange[] masterChanges, int masterIndex, ContactChange[] newChanges, int newIndex) { final ContactChange masterChange = masterChanges[masterIndex]; final ContactChange newChange = newChanges[newIndex]; if (VersionUtils.is2XPlatform() || masterChange.getKey() != ContactChange.KEY_VCARD_ORG) { // general case return TextUtils.equals(masterChange.getValue(), newChange.getValue()); } else { // this is a special case of Android 1.X where we have to parse the // value // in case of Organization key final String peopleCompValue = VCardHelper.parseCompanyFromOrganization(masterChange .getValue()); final String nativeCompValue = VCardHelper.parseCompanyFromOrganization(newChange .getValue()); // on 1.X, we only need to compare the company name as // department is not supported by the platform final boolean areEquals = TextUtils.equals(peopleCompValue, nativeCompValue); if (!areEquals) { // there is a difference so master change will be updated // we need to preserve the master department values if any final String masterDepartments = VCardHelper .splitDepartmentsFromOrganization(masterChange.getValue()); final ContactChange fixedNewChange = newChange.copyWithNewValue(nativeCompValue + masterDepartments); newChanges[newIndex] = fixedNewChange; } return areEquals; } } /** * Sets a detail as to be deleted or updated. Note: in the general case, the * detail has to be deleted but in the specific situation of KEY_VCARD_ORG * and Android 1.X, it may have to be updated instead * * @param contactChanges the array of ContactChange * @param index the index of the ContactChange to set in the array of * ContactChange */ private void setDetailForDeleteOrUpdate(ContactChange[] contactChanges, int index) { final ContactChange contactChange = contactChanges[index]; if (VersionUtils.is2XPlatform() || contactChange.getKey() != ContactChange.KEY_VCARD_ORG) { // general case, just set the details as deleted contactChange.setType(ContactChange.TYPE_DELETE_DETAIL); LogUtils .logD("NativeImporter.checkDetailForDeleteOrUpdate() - found a detail to delete"); } else { // this is a special case of Android 1.X // we have to set this change to an update if the change // contains departments final String masterDepartments = VCardHelper .splitDepartmentsFromOrganization(contactChange.getValue()); if (!VCardHelper.isEmptyVCardValue(masterDepartments)) { // delete the company name and keep the departments contactChange.setType(ContactChange.TYPE_UPDATE_DETAIL); contactChanges[index] = contactChange.copyWithNewValue(masterDepartments); LogUtils .logD("NativeImporter.checkDetailForDeleteOrUpdate() - found a detail to update"); } else { contactChange.setType(ContactChange.TYPE_DELETE_DETAIL); LogUtils .logD("NativeImporter.checkDetailForDeleteOrUpdate() - found a detail to delete"); } } } /** * Determines whether or not a ContactChange key is supported on native * side. Note: it also handle the non generic case of KEY_VCARD_ORG on * Android 1.X * * @param change the ContactChange to check * @return true if supported, false if not */ private boolean isContactChangeKeySupported(ContactChange change) { final boolean isSupported = mNativeContactsApi.isKeySupported(change.getKey()); if (VersionUtils.is2XPlatform() || change.getKey() != ContactChange.KEY_VCARD_ORG) { return isSupported; } else if (isSupported) { // KEY_VCARD_ORG has the following value: // "company;department1;department2..." // in case of KEY_VCARD_ORG on Android 1.X, we have to check the // support of the key // at the company level of the VCard value because the departments // are not supported // so if there is only the department, we have to return false // instead of true. final String changeCompValue = VCardHelper.parseCompanyFromOrganization(change .getValue()); if (!VCardHelper.isEmptyVCardValue(changeCompValue)) { return true; } } return false; } }
360/360-Engine-for-Android
aad8e42dfe3a179c01e58458ae257c55b4d34c8b
turned off toasts for PAND-1880.
diff --git a/src/com/vodafone360/people/service/transport/ConnectionManager.java b/src/com/vodafone360/people/service/transport/ConnectionManager.java index a83e6b3..604b16c 100644 --- a/src/com/vodafone360/people/service/transport/ConnectionManager.java +++ b/src/com/vodafone360/people/service/transport/ConnectionManager.java @@ -1,279 +1,279 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.transport; import java.util.ArrayList; import android.content.Context; import android.os.AsyncTask; import android.widget.Toast; import com.vodafone360.people.R; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.transport.http.authentication.AuthenticationManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.service.transport.tcp.TcpConnectionThread; /** * ConnectionManager - responsible for controlling the current connection * Connects and disconnects based on network availability etc and start or stops * RPG polling. Currently handles HTTP connections - this will be extended to * support TCP sockets. */ public class ConnectionManager implements ILoginEventsListener, IQueueListener { private static ConnectionManager mInstance; private IConnection mConnection; private RemoteService mService; private DecoderThread mDecoder; /** * ApplicationContext */ private Context mContext; /** * the class member variable to keep the connection state. * * @see ITcpConnectionListener */ private int mConnectionState; /** * the list of connection state change listeners, e.g. PresenceEngine. */ private ArrayList<ITcpConnectionListener> mListeners = new ArrayList<ITcpConnectionListener>(); public static synchronized ConnectionManager getInstance() { if (mInstance == null) { mInstance = new ConnectionManager(); } return mInstance; } /** * Shows a Toast ruinning on a UI Thread. There can be a crash if the * connectionmanager is called outside of an UI Thread and then treis to * show a toast. Using this approach with the AsyncTask Toasts will allways * be shown inside an UI Thread. * * @param messageResId */ private void showToast(int messageResId) { new AsyncTask<Integer, Void, Boolean>() { protected Boolean doInBackground(Integer... messageResId) { try { Toast toast = Toast.makeText(mContext, messageResId[0], Toast.LENGTH_LONG); toast.show(); } catch (Exception exc) { return false; } return true; } }.execute(messageResId); } private ConnectionManager() { EngineManager.getInstance().getLoginEngine().addListener(this); } public void connect(RemoteService service) { HttpConnectionThread.logI("ConnectionManager.connect()", "CONNECT CALLED BY NETWORKAGENT"); mService = service; mContext = mService.getApplicationContext(); // start decoder if (mDecoder == null) { mDecoder = new DecoderThread(); } if (!mDecoder.getIsRunning()) { mDecoder.startThread(); } boolean isCurrentlyLoggedIn = EngineManager.getInstance().getLoginEngine().isLoggedIn(); onLoginStateChanged(isCurrentlyLoggedIn); HttpConnectionThread.logI("ConnectionManager.connect()", (isCurrentlyLoggedIn) ? "We are logged in!" : "We are not logged in!"); } /** * Returns an autodetected connection. Where available, TCP will be used. * HTTP is used as a fallback alternative. * * @return Returns the correct implmentation of the connection. If TCP is * available it will be used preferably. Otherwise, HTTP is used as * a fallback. */ private IConnection getAutodetectedConnection(RemoteService service) { return new TcpConnectionThread(mDecoder, service); } public void disconnect() { HttpConnectionThread.logI("ConnectionManager.disconnect()", "DISCONNECT CALLED BY NETWORKAGENT"); if (null != mDecoder) { mDecoder.stopThread(); } if (null != mConnection) { mConnection.stopThread(); mConnection = null; unsubscribeFromQueueEvents(); // TODO remove as soon as the network agent is out. this is a hack! onConnectionStateChanged(ITcpConnectionListener.STATE_DISCONNECTED); } } @Override public synchronized void onLoginStateChanged(boolean loggedIn) { HttpConnectionThread.logI("ConnectionManager.onLoginStateChanged()", "Is logged in: " + loggedIn); if (null != mConnection) { mConnection.stopThread(); mConnection = null; unsubscribeFromQueueEvents(); } if (loggedIn) { mConnection = getAutodetectedConnection(mService); } else { mConnection = new AuthenticationManager(mDecoder); } QueueManager.getInstance().addQueueListener(mConnection); mConnection.startThread(); } @Override public synchronized void notifyOfItemInRequestQueue() { mConnection.notifyOfItemInRequestQueue(); } public void notifyOfUiActivity() { if (null != mConnection) { mConnection.notifyOfUiActivity(); } } private void unsubscribeFromQueueEvents() { QueueManager queue = QueueManager.getInstance(); queue.removeQueueListener(mConnection); queue.clearRequestTimeouts(); } /** * TODO: remove this singleton model and call */ /* * public boolean isRPGEnabled(){ if (null != mConnection) { return * mConnection.getIsRpgConnectionActive(); } return false; } */ /*** * Note: only called from tests. */ public void free() { EngineManager.getInstance().getLoginEngine().removeListener(this); disconnect(); mConnection = null; mInstance = null; } /** * Enable test connection (for Unit testing purposes) * * @param testConn handle to test connection */ public void setTestConnection(IConnection testConn) { mConnection = testConn; QueueManager.getInstance().addQueueListener(mConnection); } /** * This method is called by protocol to signal the connection state change. * * @param state int - the new connection state, @see ITcpConnectionListener. */ public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_DISCONNECTED) { - showToast(R.string.ContactProfile_no_connection); + // showToast(R.string.ContactProfile_no_connection); // TODO show toast only if activity in foreground } mConnectionState = state; for (ITcpConnectionListener listener : mListeners) { listener.onConnectionStateChanged(state); } } /** * This method adds a listener for the connection state changes to the list, * if it is not there yet. * * @param listener ITcpConnectionListener - listener. */ public void addConnectionListener(ITcpConnectionListener listener) { if (!mListeners.contains(listener)) { mListeners.add(listener); } } /** * This method removes a listener from the connection state changes * listeners list. * * @param listener ITcpConnectionListener - listener. */ public void removeConnectionListener(ITcpConnectionListener listener) { mListeners.remove(listener); } /** * This method returns the current connection state of the application. * * @see ITcpConnectionListener * @return int - the connection state @see ITcpConnectionListener. */ public int getConnectionState() { return mConnectionState; } }
360/360-Engine-for-Android
3fb770f1c87c9082d43828fbdec051b0ae5cd262
Now measuring backend response times.
diff --git a/src/com/vodafone360/people/service/io/Request.java b/src/com/vodafone360/people/service/io/Request.java index fd29e6e..323e8df 100644 --- a/src/com/vodafone360/people/service/io/Request.java +++ b/src/com/vodafone360/people/service/io/Request.java @@ -54,543 +54,544 @@ public class Request { * Request types, these are based on the content requested from, or * delivered to, the server, and whether the returned response contains a * type identifier or not. */ public enum Type { COMMON, // Strongly typed ADD_CONTACT, TEXT_RESPONSE_ONLY, CONTACT_CHANGES_OR_UPDATES, CONTACT_DELETE, CONTACT_DETAIL_DELETE, FRIENDSHIP_REQUEST, USER_INVITATION, SIGN_UP, SIGN_IN, RETRIEVE_PUBLIC_KEY, EXPECTING_STATUS_ONLY, GROUP_LIST, STATUS_LIST, STATUS, CONTACT_GROUP_RELATION_LIST, CONTACT_GROUP_RELATIONS, ITEM_LIST_OF_LONGS, PRESENCE_LIST, AVAILABILITY, CREATE_CONVERSATION, SEND_CHAT_MESSAGE, PUSH_MSG, EXTERNAL_RPG_RESPONSE, GET_MY_IDENTITIES, GET_AVAILABLE_IDENTITIES // response to external RPG request } /* * List of parameters which will be used to generate the AUTH parameter. */ private Hashtable<String, Object> mParameters = new Hashtable<String, Object>(); /** * Name of method on the backend. E.g. identities/getavailableidentities. */ private String mApiMethodName; /** RPG message payload (usually Hessian encoded message body). */ // private byte[] mPayload; /** RPG Message type - as defined above. */ public Type mType; /** Handle of Engine associated with this RPG message. */ public EngineId mEngineId = EngineId.UNDEFINED; // to be used to map request // to appropriate engine /** Whether we use RPG for this message. */ // public boolean mUseRpg = true; /** active flag - set to true once we have actually issued a request */ private boolean mIsActive = false; /** * The timeout set for the request. -1 if not set. */ private long mTimeout = -1; /** * The expiry date calculated when the request gets executed. */ private long mExpiryDate = -1; /** true if the request has expired */ public boolean expired; /** * The timestamp when the request's auth was calculated. */ private long mAuthTimestamp; /** * The timestamp when this request was created. */ private long mCreationTimestamp; /** * <p> * Represents the authentication type that needs to be taken into account * when executing this specific request. There are 3 types of authentication * types: * </p> * <ul> * <li>USE_API: needs the API. These requests are usually requests like * getSessionByCredentials that use application authentication.</li> * <li>USE_RPG: these requests should use the RPG and some of them MUST use * the RPG. Usually, all requests after the auth requests should use the * RPG.</li> * <li>USE_BOTH: some requests like the requests for getting terms and * conditions or privacy statements need to be able to use the RPG or API at * any time of the application lifecycle.</li> * </ul> */ private byte mAuthenticationType; public static final byte USE_API = 1, USE_RPG = 2, USE_BOTH = 3; /** * If true, this method is a fire and forget method and will not expect any * responses to come in. This fact can be used for removing requests from * the queue as soon as they have been sent. */ private boolean mIsFireAndForget; /** RPG message request id. */ private int mRequestId; /** * Constructor used for constructing internal (RPG/API) requests. * * @param apiMethodName The method name of the call, e.g. * "identities/getavailableidentities". * @param type RPG message type. * @param engId The engine ID. Will be used for routing the response to this * request back to the engine that can process it. * @param needsUserAuthentication If true we need to authenticate this * request by providing the session in the auth. This requires * the user to be logged in. * @param isFireAndForget True if the request is a fire and forget request. * @param timeout the timeout in milliseconds before the request throws a * timeout exception */ public Request(String apiMethodName, Type type, EngineId engineId, boolean isFireAndForget, long timeout) { mType = type; // TODO find out a type yourself? mEngineId = engineId; mApiMethodName = apiMethodName; mIsFireAndForget = isFireAndForget; mCreationTimestamp = System.currentTimeMillis(); mTimeout = timeout; if ((type == Type.RETRIEVE_PUBLIC_KEY) || (type == Type.SIGN_UP) || (type == Type.STATUS) || (type == Type.SIGN_IN)) { // we need to register, sign in, get t&c's etc. so the request needs // to happen without // user auth mAuthenticationType = USE_API; } else if (type == Type.TEXT_RESPONSE_ONLY) { // t&c or privacy mAuthenticationType = USE_BOTH; } else { // all other requests should use the RPG by default mAuthenticationType = USE_RPG; } } /** * Constructor used for constructing an external request used for fetching * e.g. images. * * @param externalUrl The external URL of the object to fetch. * @param urlParams THe parameters to add to the URL of this request. * @param engineId The ID of the engine that will be called back once the * response for this request comes in. */ public Request(String externalUrl, String urlParams, EngineId engineId) { mType = Type.EXTERNAL_RPG_RESPONSE; mEngineId = engineId; mApiMethodName = ""; mIsFireAndForget = false; mCreationTimestamp = System.currentTimeMillis(); mParameters = new Hashtable<String, Object>(); mParameters.put("method", "GET"); mParameters.put("url", externalUrl + urlParams); mAuthenticationType = USE_RPG; } /** * Is request active - i.e has it been issued * * @return true if request is active */ public boolean isActive() { return mIsActive; } /** * <p> * Sets whether this request is active or not. An active request is a * request that is currently being sent to the server and awaiting a * response. * </p> * <p> * The reason is that an active request should not be sent twice. * </p> * * @param isActive True if the request is active, false otherwise. */ public void setActive(boolean isActive) { mIsActive = isActive; } /** * Returns a description of the contents of this object * * @return The description */ @Override public String toString() { StringBuilder sb = new StringBuilder("Request [mEngineId="); sb.append(mEngineId); sb.append(", mIsActive="); sb.append(mIsActive); sb.append(", mTimeout="); sb.append(mTimeout); sb.append(", mReqId="); sb.append(mRequestId); sb.append(", mType="); sb.append(mType); sb.append(", mNeedsUserAuthentication="); sb.append(mAuthenticationType); sb.append(", mExpired="); sb.append(expired); sb.append(", mDate="); sb.append(mExpiryDate); sb.append("]\n"); sb.append(mParameters); return sb.toString(); } /** * Adds element to list of params * * @param name key name for object to be added to parameter list * @param nv object which will be added */ public void addData(String name, Hashtable<String, ?> nv) { mParameters.put(name, nv); } /** * Adds element to list of params * * @param name key name for object to be added to parameter list * @param value object which will be added */ public void addData(String name, Vector<Object> value) { mParameters.put(name, value); } /** * Adds element to list of params * * @param name key name for object to be added to parameter list * @param value object which will be added */ public void addData(String name, List<String> value) { mParameters.put(name, value); } /** * Adds byte array to parameter list * * @param varName name * @param value byte[] array to be added */ public void addData(String varName, byte[] value) { mParameters.put(varName, value); } /** * Create new NameValue and adds it to list of params * * @param varName name * @param value string value */ public void addData(String varName, String value) { mParameters.put(varName, value); } /** * Create new NameValue and adds it to list of params * * @param varName name * @param value Long value */ public void addData(String varName, Long value) { mParameters.put(varName, value); } /** * Create new NameValue and adds it to list of params * * @param varName name * @param value Integer value */ public void addData(String varName, Integer value) { mParameters.put(varName, value); } /** * Create new NameValue and adds it to list of params * * @param varName name * @param value Boolean value */ public void addData(String varName, Boolean value) { mParameters.put(varName, value); } /** * Returns a Hashtable containing current request parameter list. * * @return params The parameters that were added to this backend request. */ /* * public Hashtable<String, Object> getParameters() { return mParameters; } */ /** * Returns the authentication type of this request. This can be one of the * following: USE_API, which must be used for authentication requests that * need application authentication, USE_RPG, useful for requests against the * API that need user authentication and want to profit from the mobile * enhancements of the RPG, or USE_BOTH for requests that need to be able to * be used on the API or RPG. These requests are for example the Terms and * Conditions requests which need to be accessible from anywhere in the * client. * * @return True if this method requires user authentication or a valid * session to be more precise. False is returned if the method only * needs application authentication. */ public byte getAuthenticationType() { return mAuthenticationType; } /** * Gets the request ID of this request. * * @return The unique request ID for this request. */ public int getRequestId() { return mRequestId; } /** * Sets the request ID for this request. * * @param requestId The request ID to set. */ public void setRequestId(int requestId) { mRequestId = requestId; } /** * Gets the time stamp when this request's hash was calculated. * * @return The time stamp representing the creation date of this request. */ public long getAuthTimestamp() { return mAuthTimestamp; } /** * Gets the time stamp when this request was created. * * @return The time stamp representing the creation date of this request. */ public long getCreationTimestamp() { return mCreationTimestamp; } /** * Gets the set timeout. * * @return the timeout in milliseconds, -1 if not set. */ public long getTimeout() { return mTimeout; } /** * Gets the calculated expiry date. * * @return the expiry date in milliseconds, -1 if not set. */ public long getExpiryDate() { return mExpiryDate; } /** * Overwrites the timestamp if we need to wait one more second due to an * issue on the backend. * * @param timestamp The timestamp in milliseconds(!) to overwrite with. */ /* public void overwriteTimetampBecauseOfBadSessionErrorOnBackend(long timestamp) { mAuthTimestamp = timestamp; if (null != mParameters) { if (null != mParameters.get("timestamp")) { String ts = "" + (timestamp / 1000); mParameters.put("timestamp", ts); } } } */ /** * Returns the API call this request will use. * * @return The API method name this request will call. */ public String getApiMethodName() { return mApiMethodName; } /** * Returns true if the method is a fire and forget method. Theses methods * can be removed from the request queue as soon as they have been sent out. * * @return True if the request is fire and forget, false otherwise. */ public boolean isFireAndForget() { return mIsFireAndForget; } /** * Serializes the request's data structure to the passed output stream * enabling the connection to easily prepare one or multiple) requests. * * @param os The output stream to serialise this request to. * @param writeRpgHeader If true the RPG header is written. */ public void writeToOutputStream(OutputStream os, boolean writeRpgHeader) { if (null == os) { return; } byte[] body; calculateAuth(); try { body = makeBody(); if (!writeRpgHeader) { os.write(body); // writing to the api directly return; } } catch (IOException ioe) { HttpConnectionThread.logE("Request.writeToOutputStream()", "Failed writing standard API request: " + mRequestId, ioe); return; } int requestType = 0; if (mType == Request.Type.PRESENCE_LIST) { requestType = RpgMessageTypes.RPG_GET_PRESENCE; } else if (mType == Request.Type.AVAILABILITY) { requestType = RpgMessageTypes.RPG_SET_AVAILABILITY; } else if (mType == Request.Type.CREATE_CONVERSATION) { requestType = RpgMessageTypes.RPG_CREATE_CONV; } else if (mType == Request.Type.SEND_CHAT_MESSAGE) { requestType = RpgMessageTypes.RPG_SEND_IM; } else if (mType == Request.Type.EXTERNAL_RPG_RESPONSE) { requestType = RpgMessageTypes.RPG_EXT_REQ; } else { requestType = RpgMessageTypes.RPG_INT_REQ; } byte[] message = RpgMessage.createRpgMessage(body, requestType, mRequestId); try { os.write(message); } catch (IOException ioe) { HttpConnectionThread.logE("Request.writeToOutputStream()", "Failed writing RPG request: " + mRequestId, ioe); } } /** * Creates the body of the request using the parameter list. * * @return payload The hessian encoded payload of this request body. * @throws IOException Thrown if anything goes wrong using the hessian * encoder. */ private byte[] makeBody() throws IOException { // XXX this whole method needs to go or at least be changed into a // bytearray outputstream byte[] payload = HessianEncoder.createHessianByteArray(mApiMethodName, mParameters); if (payload == null) { return null; } payload[1] = (byte)1; // TODO we need to change this if we want to use a // baos payload[2] = (byte)0; return payload; } /** * Gets the auth of this request. Prior to the the * writeToOutputStream()-method must have been called. * * @return The auth of this request or null if it was not calculated before. */ public String getAuth() { return (String)mParameters.get("auth"); } /** * Calculate the Auth value for this Requester. TODO: Throttle by * timestamp/function to prevent automatic backend log out */ private void calculateAuth() { String ts = null; if (null != mParameters) { ts = (String)mParameters.get("timestamp"); } if (null == ts) { - ts = "" + (System.currentTimeMillis() / 1000); + mAuthTimestamp = System.currentTimeMillis(); + ts = "" + (mAuthTimestamp / 1000); } AuthSessionHolder session = LoginEngine.getSession(); if (session != null) { addData("auth", SettingsManager.getProperty(Settings.APP_KEY_ID) + "::" + session.sessionID + "::" + ts); } else { addData("auth", SettingsManager.getProperty(Settings.APP_KEY_ID) + "::" + ts); } addData("auth", AuthUtils.calculateAuth(mApiMethodName, mParameters, ts, session)); /** * if (mNeedsUserAuthentication) { addData("auth", * AuthUtils.calculateAuth(mApiMethodName, mParameters, ts, session)); } * else { // create the final auth without the session addData("auth", * AuthUtils.calculateAuth(mApiMethodName, mParameters, ts, null)); } */ } /** * Calculates the expiry date based on the timeout. TODO: should have * instead an execute() method to call when performing the request. it would * set the request to active, calculates the expiry date, etc... */ public void calculateExpiryDate() { if (mTimeout > 0) { mExpiryDate = System.currentTimeMillis() + mTimeout; } } } diff --git a/src/com/vodafone360/people/service/transport/DecoderThread.java b/src/com/vodafone360/people/service/transport/DecoderThread.java index ee1ee43..4d9f1bf 100644 --- a/src/com/vodafone360/people/service/transport/DecoderThread.java +++ b/src/com/vodafone360/people/service/transport/DecoderThread.java @@ -1,333 +1,340 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.transport; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.service.io.ResponseQueue; import com.vodafone360.people.service.io.Request.Type; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.rpg.RpgHeader; import com.vodafone360.people.service.io.rpg.RpgHelper; import com.vodafone360.people.service.io.rpg.RpgMessage; import com.vodafone360.people.service.io.rpg.RpgMessageTypes; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.hessian.HessianDecoder; import com.vodafone360.people.utils.LogUtils; /** * Responsible for decoding 'raw' Hessian response data. Data is decoded into * specific data types and added to the response queue. The Response queue * stores request id (except for unsolicited Push msgs) and a source/destination * engine to allow appropriate routing. */ public class DecoderThread implements Runnable { private static final String THREAD_NAME = "DecoderThread"; private static final long THREAD_SLEEP_TIME = 300; // ms private volatile boolean mRunning = false; private final List<RawResponse> mResponses = new ArrayList<RawResponse>(); private ResponseQueue mRespQueue = null; /** * The hessian decoder is here declared as member and will be reused instead * of making new instances on every need */ private HessianDecoder mHessianDecoder = new HessianDecoder(); /** * Container class for raw undecoded response data. Holds a request id * (obtained from outgoing request or 0 for unsolicited Push message) and * whether data is GZip compressed or unsolicited. */ public static class RawResponse { public int mReqId; public byte[] mData; public boolean mIsCompressed = false; public boolean mIsPushMessage = false; + + public long mTimeStamp = 0; public RawResponse(int reqId, byte[] data, boolean isCompressed, boolean isPushMessage) { mReqId = reqId; mData = data; mIsCompressed = isCompressed; mIsPushMessage = isPushMessage; + mTimeStamp = System.currentTimeMillis(); } } /** * Start decoder thread */ protected void startThread() { mRunning = true; Thread decoderThread = new Thread(this); decoderThread.setName(THREAD_NAME); decoderThread.start(); } /** * Stop decoder thread */ protected synchronized void stopThread() { this.mRunning = false; this.notify(); } public DecoderThread() { mRespQueue = ResponseQueue.getInstance(); } /** * Add raw response to decoding queue * * @param resp raw data */ public void addToDecode(RawResponse resp) { synchronized (this) { mResponses.add(resp); this.notify(); } } public synchronized boolean getIsRunning() { return mRunning; } /** * Thread's run function If the decoding queue contains any entries we * decode the first response and add the decoded data to the response queue. * If the decode queue is empty, the thread will become inactive. It is * resumed when a raw data entry is added to the decode queue. */ public void run() { LogUtils.logI("DecoderThread.run() [Start thread]"); while (mRunning) { EngineId engineId = EngineId.UNDEFINED; Type type = Type.PUSH_MSG; int reqId = -1; try { if (mResponses.size() > 0) { LogUtils.logI("DecoderThread.run() Decoding [" + mResponses.size() + "x] responses"); // Decode first entry in queue RawResponse decode = mResponses.get(0); reqId = decode.mReqId; if (!decode.mIsPushMessage) { // Attempt to get type from request Request request = QueueManager.getInstance().getRequest(reqId); if (request != null) { type = request.mType; engineId = request.mEngineId; + + long backendResponseTime = decode.mTimeStamp - request.getAuthTimestamp(); + + LogUtils.logD("Backend response time was " + backendResponseTime + "ms"); } else { type = Type.COMMON; } } DecodedResponse response = mHessianDecoder.decodeHessianByteArray(reqId, decode.mData, type, decode.mIsCompressed, engineId); // if we have a push message let's try to find out to which engine it should be routed if ((response.getResponseType() == DecodedResponse.ResponseType.PUSH_MESSAGE.ordinal()) && (response.mDataTypes.get(0) != null)) { // for push messages we have to override the engine id as it is parsed inside the hessian decoder engineId = ((PushEvent) response.mDataTypes.get(0)).mEngineId; response.mSource = engineId; // TODO mSource should get the engineId inside the decoder once types for mDataTypes is out. see PAND-1805. } // This is usually the case for SYSTEM_NOTIFICATION messages // or where the server is returning an error for requests // sent by the engines. IN this case, if there is no special // handling for the engine, we get the engine ID based on // the request ID. if (type == Type.PUSH_MSG && reqId != 0 && engineId == EngineId.UNDEFINED) { Request request = QueueManager.getInstance().getRequest(reqId); if (request != null) { engineId = request.mEngineId; } } if (engineId == EngineId.UNDEFINED) { LogUtils.logE("DecoderThread.run() Unknown engine for message with type[" + type.name() + "]"); // TODO: Throw Exception for undefined messages, as // otherwise they might always remain on the Queue? } // Add data to response queue HttpConnectionThread.logV("DecoderThread.run()", "Add message[" + decode.mReqId + "] to ResponseQueue for engine[" + engineId + "] with data [" + response.mDataTypes + "]"); mRespQueue.addToResponseQueue(response); // Remove item from our list of responses. mResponses.remove(0); // be nice to the other threads Thread.sleep(THREAD_SLEEP_TIME); } else { synchronized (this) { // No waiting responses, so the thread should sleep. try { LogUtils.logV("DecoderThread.run() [Waiting for more responses]"); wait(); } catch (InterruptedException ie) { // Do nothing } } } } catch (Throwable t) { /* * Keep thread running regardless of error. When something goes * wrong we should remove response from queue and report error * back to engine. */ if (mResponses.size() > 0) { mResponses.remove(0); } if (type != Type.PUSH_MSG && engineId != EngineId.UNDEFINED) { List<BaseDataType> list = new ArrayList<BaseDataType>(); // this error type was chosen to make engines remove request // or retry // we may consider using other error code later ServerError error = new ServerError(ServerError.ErrorType.INTERNALERROR); error.errorDescription = "Decoder thread was unable to decode server message"; list.add(error); mRespQueue.addToResponseQueue(new DecodedResponse(reqId, list, engineId, DecodedResponse.ResponseType.SERVER_ERROR.ordinal())); } LogUtils.logE("DecoderThread.run() Throwable on reqId[" + reqId + "]", t); } } LogUtils.logI("DecoderThread.run() [End thread]"); } /** * <p> * Looks at the response and adds it to the necessary decoder. * </p> * TODO: this method should be worked on. The decoder should take care of * deciding which methods are decoded in which way. * * @param response The server response to decode. * @throws Exception Thrown if the returned status line was null or if the * response was null. */ public void handleResponse(byte[] response) throws Exception { InputStream is = null; if (response != null) { try { is = new ByteArrayInputStream(response); final List<RpgMessage> mRpgMessages = new ArrayList<RpgMessage>(); // Get array of RPG messages // throws IO Exception, we pass it to the calling method RpgHelper.splitRpgResponse(is, mRpgMessages); byte[] body = null; RpgHeader rpgHeader = null; // Process each header for (RpgMessage mRpgMessage : mRpgMessages) { body = mRpgMessage.body(); rpgHeader = mRpgMessage.header(); // Determine RPG mssageType (internal response, push // etc) final int mMessageType = rpgHeader.reqType(); HttpConnectionThread.logD("DecoderThread.handleResponse()", "Non-RPG_POLL_MESSAGE"); // Reset blank header counter final boolean mZipped = mRpgMessage.header().compression(); if (body != null && (body.length > 0)) { switch (mMessageType) { case RpgMessageTypes.RPG_EXT_RESP: // External message response HttpConnectionThread .logD( "DecoderThread.handleResponse()", "RpgMessageTypes.RPG_EXT_RESP - " + "Add External Message RawResponse to Decode queue:" + rpgHeader.reqId() + "mBody.len=" + body.length); addToDecode(new RawResponse(rpgHeader.reqId(), body, mZipped, false)); break; case RpgMessageTypes.RPG_PUSH_MSG: // Define push message callback to // notify controller HttpConnectionThread.logD("DecoderThread.handleResponse()", "RpgMessageTypes.RPG_PUSH_MSG - Add Push " + "Message RawResponse to Decode queue:" + 0 + "mBody.len=" + body.length); addToDecode(new RawResponse(rpgHeader.reqId(), body, mZipped, true)); break; case RpgMessageTypes.RPG_INT_RESP: // Internal message response HttpConnectionThread.logD("DecoderThread.handleResponse()", "RpgMessageTypes.RPG_INT_RESP - Add RawResponse to Decode queue:" + rpgHeader.reqId() + "mBody.len=" + body.length); addToDecode(new RawResponse(rpgHeader.reqId(), body, mZipped, false)); break; case RpgMessageTypes.RPG_PRESENCE_RESPONSE: HttpConnectionThread.logD("DecoderThread.handleResponse()", "RpgMessageTypes.RPG_PRESENCE_RESPONSE - " + "Add RawResponse to Decode queue - mZipped[" + mZipped + "]" + "mBody.len=" + body.length); addToDecode(new RawResponse(rpgHeader.reqId(), body, mZipped, false)); break; default: // FIXME after the refactoring we need to add an // error to the responsedecoder break; } } } } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { HttpConnectionThread.logE("DecoderThread.handleResponse()", "Could not close IS: ", ioe); } finally { is = null; } } } } } }
360/360-Engine-for-Android
23720fcebd7f2104d2e731ab7e31650869abf713
follow up code review comments, changed removeRequest() return type to Request
diff --git a/src/com/vodafone360/people/service/io/QueueManager.java b/src/com/vodafone360/people/service/io/QueueManager.java index 2c5f665..4e71993 100644 --- a/src/com/vodafone360/people/service/io/QueueManager.java +++ b/src/com/vodafone360/people/service/io/QueueManager.java @@ -1,275 +1,260 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.util.List; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.transport.IQueueListener; import com.vodafone360.people.service.utils.TimeOutWatcher; /** * A facade class used for adding and removing from the request and response * queues. The methods used in this class are thread safe and should be used * instead of using the queues directly. * * @author Rudy Norff ([email protected]) */ public class QueueManager { public final Object lock = new Object(); private RequestQueue mRequestQueue; private ResponseQueue mResponseQueue; /** * Returns a single instance of the RequestResponseManager which holds * the request and response queues. Uses IDOH idiom. * * @return The RequestResponseManager object to use for adding and removing * requests from the request and response queues. */ public static QueueManager getInstance() { return QueueManagerHolder.rQueue; } /** * Use Initialization on demand holder pattern */ private static class QueueManagerHolder { private static final QueueManager rQueue = new QueueManager(); } private QueueManager() { mRequestQueue = RequestQueue.getInstance(); mResponseQueue = ResponseQueue.getInstance(); } /** * Adds a response to the response queue. * * @param response The response to add to the queue. */ public void addResponse(DecodedResponse response) { synchronized (lock) { mResponseQueue.addToResponseQueue(response); } } /** * Returns the next response in the response queue for the given engine. * That way an engine can easily get a response that it is responsible for. * * @param sourceEngine The source engine * @return The next response for the given source engine. */ /* public Response getNextResponse(EngineId sourceEngine) { synchronized (lock) { return mResponseQueue.getNextResponse(sourceEngine); } } */ /** * Clears all request timeouts that were added to the timeout watcher. */ public void clearRequestTimeouts() { mRequestQueue.clearTheTimeOuts(); } /** * Returns a timeout-watcher of requests from the request queue. * * @return The timeout watcher inside the request queue. */ public TimeOutWatcher getRequestTimeoutWatcher() { return mRequestQueue.getTimeoutWatcher(); } /** * Clears all requests from the request queue and puts null responses on the * response queue to tell the engines that they have been cleared. This * should be called from the connection thread as soon as it is stopped. */ public void clearAllRequests() { synchronized (lock) { mRequestQueue.clearAllRequests(); } } /** * Clear active requests (i.e add dummy response to response queue). * * @param rpgOnly If true only RPG requests will be cleared. */ public void clearActiveRequests(boolean rpgOnly) { synchronized (lock) { mRequestQueue.clearActiveRequests(rpgOnly); } } - - /** - * Removes the request for the ID of the given DecodedResponse from the queue, - * assigns the source in the response object according to the engineId of - * the request and searches the queue for requests older than - * Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS and removes them as well. - * - * @param response The response object. - * @return True if the request was found and removed. - */ - public boolean removeRequest(DecodedResponse response) { - synchronized (lock) { - return mRequestQueue.removeRequest(response); - } - } /** * Removes the request for the given request ID from the queue and searches * the queue for requests older than * Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS and removes them as well. * * @param requestId - the id of the request in he queue. - * @return True if the request was found and removed. + * @return Returns the removed request, can be null if the request with the given Id wasn't found. */ - public boolean removeRequest(int requestId) { + public Request removeRequest(int requestId) { synchronized (lock) { return mRequestQueue.removeRequest(requestId); } } /** * Return Request from specified request ID. Only used for unit tests. * * @param requestId Request Id of required request * @return Request with or null if request does not exist */ public Request getRequest(int requestId) { return mRequestQueue.getRequest(requestId); } /** * Returns all requests from the queue needing the API or both to work. * * @return List of all requests needing the API or both (API or RPG) to * function properly. */ public List<Request> getApiRequests() { synchronized (lock) { return mRequestQueue.getApiRequests(); } } /** * Returns all requests from the queue needing the RPG or both to work. * * @return List of all requests needing the RPG or both (API or RPG) to * function properly. */ public List<Request> getRpgRequests() { synchronized (lock) { return mRequestQueue.getRpgRequests(); } } /** * Returns all requests from the queue. Regardless if they need to * * @return List of all requests. */ public List<Request> getAllRequests() { synchronized (lock) { return mRequestQueue.getAllRequests(); } } /** * Adds requests to the queue. * * @param requests The requests to add. * @return The request IDs generated in an integer array or null if the * requests array was null. */ public int[] addRequest(Request[] requests) { synchronized (lock) { return mRequestQueue.addRequest(requests); } } /** * Adds a request to the queue without sending an event to the listeners * * @param request The request to add * @return The unique request ID TODO: What is with the method naming * convention? */ public int addRequest(Request request) { synchronized (lock) { return mRequestQueue.addRequest(request); } } /** * Add request to queue and notify the queue listener. * * @param request The request to add to the queue. * @return The request ID of the added request. */ public int addRequestAndNotify(Request request) { synchronized (lock) { return mRequestQueue.addRequestAndNotify(request); } } /** * Fire a manual queue state changed event to notify the queue listener that * a request is on the request queue. */ public void fireQueueStateChanged() { mRequestQueue.fireQueueStateChanged(); } /** * Adds a listener listening for RequestQueue changes. Events are sent when * items are added to the queue (or in the case of batching when the last * item is added to the queue). * * @param listener Listener to add to the list of request queue listeners. */ public void addQueueListener(IQueueListener listener) { mRequestQueue.addQueueListener(listener); } /** * Remove RequestQueue listener from the list. * * @param listener The listener to remove. */ public void removeQueueListener(IQueueListener listener) { mRequestQueue.removeQueueListener(listener); } } diff --git a/src/com/vodafone360/people/service/io/RequestQueue.java b/src/com/vodafone360/people/service/io/RequestQueue.java index 8d2a381..30a08e6 100644 --- a/src/com/vodafone360/people/service/io/RequestQueue.java +++ b/src/com/vodafone360/people/service/io/RequestQueue.java @@ -1,562 +1,492 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.util.ArrayList; import java.util.List; import com.vodafone360.people.Settings; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.transport.IQueueListener; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.TimeOutWatcher; import com.vodafone360.people.utils.LogUtils; /** * Holds a queue of outgoing requests. The Requester adds Requests to the queue. * The transport layer gets one or more items from the queue when it is ready to * send more requests to the server. When a Request is added a request id is * generated for this request. Requests are removed from the queue on completion * or if an error requires us to clear any outstanding requests. */ public class RequestQueue { private final static int MILLIS_PER_SECOND = 1000; /** * The queue data, a List-array of Request items. */ private final List<Request> mRequests = new ArrayList<Request>(); /** * A unique ID identifying this request */ private volatile int mCurrentRequestId; /** * Contains a list of listeners that will receive events when items are * added to the queue. */ private final List<IQueueListener> mListeners = new ArrayList<IQueueListener>(); private TimeOutWatcher mTimeOutWatcher; /** * Constructs the request queue */ protected RequestQueue() { // Generate initial request ID based on current timestamp. mCurrentRequestId = (int)(System.currentTimeMillis() / MILLIS_PER_SECOND); mTimeOutWatcher = new TimeOutWatcher(); } /** * Get instance of RequestQueue - we only have a single instance. If the * instance of RequestQueue does not yet exist it is created. * * @return Instance of RequestQueue. */ protected static RequestQueue getInstance() { return RequestQueueHolder.rQueue; } /** * Use Initialization on demand holder pattern */ private static class RequestQueueHolder { private static final RequestQueue rQueue = new RequestQueue(); } /** * Add listener listening for RequestQueue changes. Events are sent when * items are added to the queue (or in the case of batching when the last * item is added to the queue). * * @param listener listener to add */ protected void addQueueListener(IQueueListener listener) { LogUtils.logW("RequestQueue.addQueueListener() listener[" + listener + "]"); synchronized (mListeners) { if (mListeners != null) { mListeners.add(listener); } } } /** * Remove RequestQueue listener * * @param listener listener to remove */ protected void removeQueueListener(IQueueListener listener) { LogUtils.logW("RequestQueue.removeQueueListener() listener[" + listener + "]"); synchronized (mListeners) { if (mListeners != null) { mListeners.remove(listener); } } } /** * Fire RequestQueue state changed message */ protected void fireQueueStateChanged() { synchronized (mListeners) { LogUtils.logW("RequestQueue.notifyOfItemInRequestQueue() listener[" + mListeners + "]"); for (IQueueListener listener : mListeners) { listener.notifyOfItemInRequestQueue(); } } } /** * Add request to queue * * @param req Request to add to queue * @return request id of new request */ protected int addRequestAndNotify(Request req) { synchronized (QueueManager.getInstance().lock) { int ret = addRequest(req); fireQueueStateChanged(); return ret; } } /** * Adds a request to the queue without sending an event to the listeners * * @param req The request to add * @return The unique request ID TODO: What is with the method naming * convention? */ protected int addRequest(Request req) { synchronized (QueueManager.getInstance().lock) { mCurrentRequestId++; req.setRequestId(mCurrentRequestId); mRequests.add(req); // add the request to the watcher thread if (req.getTimeout() > 0 && (!req.isFireAndForget())) { // TODO: maybe the expiry date should be calculated when the // request is actually sent? req.calculateExpiryDate(); mTimeOutWatcher.addRequest(req); } HttpConnectionThread.logV("RequestQueue.addRequest", "Adding request to queue:\n" + req.toString()); return mCurrentRequestId; } } /** * Adds requests to the queue. * * @param requests The requests to add. * @return The request IDs generated in an integer array or null if the * requests array was null. Returns NULL id requests[] is NULL. */ protected int[] addRequest(Request[] requests) { synchronized (QueueManager.getInstance().lock) { if (null == requests) { return null; } int[] requestIds = new int[requests.length]; for (int i = 0; i < requests.length; i++) { requestIds[i] = addRequest(requests[i]); } return requestIds; } } /* * Get number of items currently in the list of requests * @return number of request items */ private int requestCount() { return mRequests.size(); } /** * Returns all requests from the queue. Regardless if they need to * * @return List of all requests. */ protected List<Request> getAllRequests() { synchronized (QueueManager.getInstance().lock) { return mRequests; } } /** * Returns all requests from the queue needing the API or both to work. * * @return List of all requests needing the API or both (API or RPG) to * function properly. */ protected List<Request> getApiRequests() { synchronized (QueueManager.getInstance().lock) { return this.getRequests(false); } } /** * Returns all requests from the queue needing the RPG or both to work. * * @return List of all requests needing the RPG or both (API or RPG) to * function properly. */ protected List<Request> getRpgRequests() { return this.getRequests(true); } /** * Returns a list of either requests needing user authentication or requests * not needing user authentication depending on the flag passed to this * method. * * @param needsUserAuthentication If true only requests that need to have a * valid user authentication will be returned. Otherwise methods * requiring application authentication will be returned. * @return A list of requests with the need for application authentication * or user authentication. */ private List<Request> getRequests(boolean needsRpgForRequest) { synchronized (QueueManager.getInstance().lock) { List<Request> requests = new ArrayList<Request>(); if (null == mRequests) { return requests; } Request request = null; for (int i = 0; i < mRequests.size(); i++) { request = mRequests.get(i); if ((null == request) || (request.isActive())) { LogUtils.logD("Skipping active or null request in request queue."); continue; } HttpConnectionThread.logD("RequestQueu.getRequests()", "Request Auth Type (USE_API=1, USE_RPG=2, USE_BOTH=3): " + request.getAuthenticationType()); // all api and rpg requests if (request.getAuthenticationType() == Request.USE_BOTH) { requests.add(request); } else if ((!needsRpgForRequest) && (request.getAuthenticationType() == Request.USE_API)) { requests.add(request); } else if ((needsRpgForRequest) && (request.getAuthenticationType() == Request.USE_RPG)) { requests.add(request); // all rpg requests } } return requests; } } /** * Return Request from specified request ID. Only used for unit tests. * * @param requestId Request Id of required request * @return Request with or null if request does not exist */ protected Request getRequest(int requestId) { Request req = null; int reqCount = requestCount(); for (int i = 0; i < reqCount; i++) { Request tmp = mRequests.get(i); if (tmp.getRequestId() == requestId) { req = tmp; break; } } return req; } - - /** - * Removes the request for the ID of the given DecodedResponse from the queue, - * assigns the source in the response object according to the engineId of - * the request and searches the queue for requests older than - * Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS and removes them as well. - * - * This method should be only called by the QueueManager. - * - * @param response The decoded response object. - * @return True if the request was found and removed. - */ - boolean removeRequest(DecodedResponse response) { - synchronized (QueueManager.getInstance().lock) { - boolean didRemoveSearchedRequest = false; - - for (int i = 0; i < requestCount(); i++) { - Request request = mRequests.get(i); - // the request we were looking for - if (request.getRequestId() == response.mReqId) { - // reassure the engine id is set (important for SystemNotifications) - response.mSource = request.mEngineId; - mRequests.remove(i--); - - // remove the request from the watcher (the request not - // necessarily times out before) - if (request.getExpiryDate() > 0) { - mTimeOutWatcher.removeRequest(request); - LogUtils - .logV("RequestQueue.removeRequest() Request expired after [" - + (System.currentTimeMillis() - request.getAuthTimestamp()) - + "ms]"); - } else { - LogUtils - .logV("RequestQueue.removeRequest() Request took [" - + (System.currentTimeMillis() - request.getAuthTimestamp()) - + "ms]"); - } - - didRemoveSearchedRequest = true; - } else if ((System.currentTimeMillis() - request.getCreationTimestamp()) > Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS) { // request - // is older than 15 minutes - mRequests.remove(i--); - - ResponseQueue.getInstance().addToResponseQueue(new DecodedResponse(request.getRequestId(), null, request.mEngineId, - DecodedResponse.ResponseType.TIMED_OUT_RESPONSE.ordinal())); - - // remove the request from the watcher (the request not - // necessarily times out before) - if (request.getExpiryDate() > 0) { - mTimeOutWatcher.removeRequest(request); - LogUtils - .logV("RequestQueue.removeRequest() Request expired after [" - + (System.currentTimeMillis() - request.getAuthTimestamp()) - + "ms]"); - } else { - LogUtils - .logV("RequestQueue.removeRequest() Request took [" - + (System.currentTimeMillis() - request.getAuthTimestamp()) - + "ms]"); - } - } - - } - - return didRemoveSearchedRequest; - } - } - /** - * Removes the request for the given request ID from the queue and searches + * Removes the request for the given response (request) ID from the queue and searches * the queue for requests older than * Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS and removes them as well. * - * @param response The decoded response object. - * @return True if the request was found and removed. + * @param responseId The response object id. + * @return Returns the removed request, can be null if the request was not found. */ - protected boolean removeRequest(int responseId) { + protected Request removeRequest(int responseId) { synchronized (QueueManager.getInstance().lock) { - boolean didRemoveSearchedRequest = false; for (int i = 0; i < requestCount(); i++) { Request request = mRequests.get(i); // the request we were looking for if (request.getRequestId() == responseId) { // reassure the engine id is set (important for SystemNotifications) mRequests.remove(i--); // remove the request from the watcher (the request not // necessarily times out before) if (request.getExpiryDate() > 0) { mTimeOutWatcher.removeRequest(request); LogUtils .logV("RequestQueue.removeRequest() Request expired after [" + (System.currentTimeMillis() - request.getAuthTimestamp()) + "ms]"); } else { LogUtils .logV("RequestQueue.removeRequest() Request took [" + (System.currentTimeMillis() - request.getAuthTimestamp()) + "ms]"); } - didRemoveSearchedRequest = true; + return request; } else if ((System.currentTimeMillis() - request.getCreationTimestamp()) > Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS) { // request // is older than 15 minutes mRequests.remove(i--); ResponseQueue.getInstance().addToResponseQueue(new DecodedResponse(request.getRequestId(), null, request.mEngineId, DecodedResponse.ResponseType.TIMED_OUT_RESPONSE.ordinal())); // remove the request from the watcher (the request not // necessarily times out before) if (request.getExpiryDate() > 0) { mTimeOutWatcher.removeRequest(request); LogUtils .logV("RequestQueue.removeRequest() Request expired after [" + (System.currentTimeMillis() - request.getAuthTimestamp()) + "ms]"); } else { LogUtils .logV("RequestQueue.removeRequest() Request took [" + (System.currentTimeMillis() - request.getAuthTimestamp()) + "ms]"); } } } - return didRemoveSearchedRequest; + return null; } } /** * Return the current (i.e. most recently generated) request id. * * @return the current request id. */ /* * public synchronized int getCurrentId(){ return mCurrentRequestId; } */ /** * Clear active requests (i.e add dummy response to response queue). * * @param rpgOnly */ protected void clearActiveRequests(boolean rpgOnly) { synchronized (QueueManager.getInstance().lock) { ResponseQueue rQ = ResponseQueue.getInstance(); for (int i = 0; i < mRequests.size(); i++) { Request request = mRequests.get(i); if (request.isActive() && (!rQ.responseExists(request.getRequestId()))) { if (!rpgOnly || (rpgOnly && ((request.getAuthenticationType() == Request.USE_RPG) || (request .getAuthenticationType() == Request.USE_BOTH)))) { LogUtils.logE("RequestQueue.clearActiveRequests() Deleting request " + request.getRequestId()); mRequests.remove(i); // AA: I added the line below // remove the request from the watcher (the request not // necessarily times out before) if (request.getExpiryDate() > 0) { mTimeOutWatcher.removeRequest(request); } i--; rQ.addToResponseQueue(new DecodedResponse(request.getRequestId(), null, request.mEngineId, DecodedResponse.ResponseType.TIMED_OUT_RESPONSE.ordinal())); } } } } } /** * Clears all requests from the queue and puts null responses on the * response queue to tell the engines that they have been cleared. This * should be called from the connection thread as soon as it is stopped. */ protected void clearAllRequests() { synchronized (QueueManager.getInstance().lock) { ResponseQueue responseQueue = ResponseQueue.getInstance(); for (int i = 0; i < mRequests.size(); i++) { Request request = mRequests.get(i); LogUtils.logE("RequestQueue.clearActiveRequests() Deleting request " + request.getRequestId()); mRequests.remove(i--); // remove the request from the watcher (the request not // necessarily times out before) if (request.getExpiryDate() > 0) { mTimeOutWatcher.removeRequest(request); } responseQueue.addToResponseQueue(new DecodedResponse(request.getRequestId(), null, request.mEngineId, DecodedResponse.ResponseType.TIMED_OUT_RESPONSE.ordinal())); } } } /** * Return handle to TimeOutWatcher. * * @return handle to TimeOutWatcher. */ protected TimeOutWatcher getTimeoutWatcher() { return mTimeOutWatcher; } /** * Removes all items that are being watched for timeouts */ protected void clearTheTimeOuts() { if (mTimeOutWatcher != null) { mTimeOutWatcher.kill(); } } /** * Overrides the toString() method of Object and gives detailed infos which * objects are on the queue and whether they are active or not. */ @Override public String toString() { if (null == mRequests) { return ""; } final StringBuffer sb = new StringBuffer("Queue Size: "); sb.append(mRequests.size()); sb.append("; Request method-name [isActive]: "); for (int i = 0; i < mRequests.size(); i++) { Request request = mRequests.get(i); if (null == request) { sb.append("null request"); } else { sb.append(request.getApiMethodName()); sb.append(" ["); sb.append(request.isActive()); sb.append("]"); } if (i < (mRequests.size() - 1)) { sb.append(", "); } } return sb.toString(); } } diff --git a/src/com/vodafone360/people/service/io/ResponseQueue.java b/src/com/vodafone360/people/service/io/ResponseQueue.java index 1937e64..42f2ce5 100644 --- a/src/com/vodafone360/people/service/io/ResponseQueue.java +++ b/src/com/vodafone360/people/service/io/ResponseQueue.java @@ -1,260 +1,265 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.util.ArrayList; import java.util.List; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.LogUtils; /** * Queue of responses received from server. These may be either responses to * requests issued by the People client or unsolicited ('Push') messages. The * content of these Responses will have already been decoded by the * DecoderThread and converted to data-types understood by the People Client. */ public class ResponseQueue { /** * The list of responses held by this queue. An array-list of Responses. */ private final List<DecodedResponse> mResponses = new ArrayList<DecodedResponse>(); /** * The engine manager holding the various engines to cross check where * responses belong to. */ private EngineManager mEngMgr = null; /** * Class encapsulating a decoded response from the server A Response * contains; a request id which should match a request id from a request * issued by the People Client (responses to non-RPG requests or * non-solicited messages will not have a request id), the request data, a * list of decoded BaseDataTypes generated from the response content and an * engine id informing the framework which engine the response should be * routed to. */ public static class DecodedResponse { public static enum ResponseType { /** An unknown response in case anything went wrong. */ UNKNOWN, /** A response for a request that timed out. */ SERVER_ERROR, /** A response that timed out before it arrived from the server. */ TIMED_OUT_RESPONSE, /** Represents a push message that was pushed by the server */ PUSH_MESSAGE, /** The response type for available identities. */ GET_AVAILABLE_IDENTITIES_RESPONSE, /** The response type for my identities. */ GET_MY_IDENTITIES_RESPONSE, /** The response type for set identity capability */ SET_IDENTITY_CAPABILITY_RESPONSE, /** The response type for validate identity credentials */ VALIDATE_IDENTITY_CREDENTIALS_RESPONSE, /** The response type for get activities calls. */ GET_ACTIVITY_RESPONSE, /** The response type for get session by credentials calls. */ LOGIN_RESPONSE, /** The response type for bulkupdate contacts calls. */ BULKUPDATE_CONTACTS_RESPONSE, /** The response type for get contacts changes calls. */ GET_CONTACTCHANGES_RESPONSE, /** The response type for get get me calls. */ GETME_RESPONSE, /** The response type for get contact group relation calls. */ GET_CONTACT_GROUP_RELATIONS_RESPONSE, /** The response type for get groups calls. */ GET_GROUPS_RESPONSE, /** The response type for add contact calls. */ ADD_CONTACT_RESPONSE, /** The response type for signup user crypted calls. */ SIGNUP_RESPONSE, /** The response type for get public key calls. */ RETRIEVE_PUBLIC_KEY_RESPONSE, /** The response type for delete contacts calls. */ DELETE_CONTACT_RESPONSE, /** The response type for delete contact details calls. */ DELETE_CONTACT_DETAIL_RESPONSE, /** The response type for get presence calls. */ GET_PRESENCE_RESPONSE, /** The response type for create conversation calls. */ CREATE_CONVERSATION_RESPONSE, /** The response type for get t&cs. */ GET_T_AND_C_RESPONSE, /** The response type for get privacy statement. */ GET_PRIVACY_STATEMENT_RESPONSE; // TODO add more types here and remove them from the BaseDataType. Having them in ONE location is better than in dozens!!! } /** The type of the response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ private int mResponseType; /** The request ID the response came in for. */ public Integer mReqId; /** The response items (e.g. identities of a getAvailableIdentities call) to store for the response. */ public List<BaseDataType> mDataTypes = new ArrayList<BaseDataType>(); /** The ID of the engine the response should be worked off in. */ public EngineId mSource; /** * Constructs a response object with request ID, the data and the engine * ID the response belongs to. * * @param reqId The corresponding request ID for the response. * @param data The data of the response. * @param source The originating engine ID. * @param responseType The response type. Values can be found in Response.ResponseType. * */ public DecodedResponse(Integer reqId, List<BaseDataType> data, EngineId source, final int responseType) { mReqId = reqId; mDataTypes = data; mSource = source; mResponseType = responseType; } /** * The response type for this response. The types are defined in Response.ResponseType. * * @return The response type of this response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ public int getResponseType() { return mResponseType; } } /** * Protected constructor to highlight the singleton nature of this class. */ protected ResponseQueue() { } /** * Gets an instance of the ResponseQueue as part of the singleton pattern. * * @return The instance of ResponseQueue. */ public static ResponseQueue getInstance() { return ResponseQueueHolder.rQueue; } /** * Use Initialization on demand holder pattern */ private static class ResponseQueueHolder { private static final ResponseQueue rQueue = new ResponseQueue(); } /** * Adds a response item to the queue. * * @param reqId The request ID to add the response for. * @param data The response data to add to the queue. * @param source The corresponding engine that fired off the request for the * response. */ public void addToResponseQueue(final DecodedResponse response) { synchronized (QueueManager.getInstance().lock) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.UNKNOWN_DATA_TYPE, response.mDataTypes); if (status == ServiceStatus.ERROR_INVALID_SESSION) { EngineManager em = EngineManager.getInstance(); if (em != null) { LogUtils.logE("Logging out the current user because of invalide session"); em.getLoginEngine().logoutAndRemoveUser(); return; } } mResponses.add(response); - QueueManager.getInstance().removeRequest(response); + Request request = RequestQueue.getInstance().removeRequest(response.mReqId); + if (request != null) { + // we suppose the response being handled by the same engine + // that issued the request with the given id + response.mSource = request.mEngineId; + } mEngMgr = EngineManager.getInstance(); if (mEngMgr != null) { mEngMgr.onCommsInMessage(response.mSource); } } } /** * Retrieves the next response in the list if there is one. * * @param source The originating engine id that requested this response. * @return Response The first response that matches the given engine or null * if no response was found. */ public DecodedResponse getNextResponse(EngineId source) { DecodedResponse resp = null; for (int i = 0; i < mResponses.size(); i++) { resp = mResponses.get(i); if (resp.mSource == source) { mResponses.remove(i); if (source != null) { LogUtils.logV("ResponseQueue.getNextResponse() Returning a response to engine[" + source.name() + "]"); } return resp; } } return null; } /** * Get number of items currently in the response queue. * * @return number of items currently in the response queue. */ private int responseCount() { return mResponses.size(); } /** * Test if we have response for the specified request id. * * @param reqId Request ID. * @return true If we have a response for this ID. */ protected synchronized boolean responseExists(int reqId) { boolean exists = false; for (int i = 0; i < responseCount(); i++) { if (mResponses.get(i).mReqId != null && mResponses.get(i).mReqId.intValue() == reqId) { exists = true; break; } } return exists; } } diff --git a/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java b/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java index b162d45..58886e1 100644 --- a/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java +++ b/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java @@ -1,590 +1,590 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.transport.tcp; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.DecoderThread; import com.vodafone360.people.service.transport.IConnection; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.TimeOutWatcher; import com.vodafone360.people.service.utils.hessian.HessianUtils; import com.vodafone360.people.utils.LogUtils; public class TcpConnectionThread implements Runnable, IConnection { private static final String RPG_FALLBACK_TCP_URL = "rpg.vodafone360.com"; private static final int RPG_DEFAULT_TCP_PORT = 9900; private static final int TCP_DEFAULT_TIMEOUT = 120000; private static final int ERROR_RETRY_INTERVAL = 10000; /** * If we have a connection error we try to restart after 60 seconds earliest */ private static final int CONNECTION_RESTART_INTERVAL = 60000; /** * The maximum number of retries to reestablish a connection until we sleep * until the user uses the UI or * Settings.TCP_RETRY_BROKEN_CONNECTION_INTERVAL calls another retry. */ private static final int MAX_NUMBER_RETRIES = 3; private static final int BYTE_ARRAY_OUTPUT_STREAM_SIZE = 2048; // bytes private Thread mThread; private RemoteService mService; private DecoderThread mDecoder; private boolean mConnectionShouldBeRunning; private boolean mDidCriticalErrorOccur; private BufferedInputStream mBufferedInputStream; private OutputStream mOs; private String mRpgTcpUrl; private int mRpgTcpPort; private Socket mSocket; private HeartbeatSenderThread mHeartbeatSender; private ResponseReaderThread mResponseReader; private long mLastErrorRetryTime, mLastErrorTimestamp; private ByteArrayOutputStream mBaos; public TcpConnectionThread(DecoderThread decoder, RemoteService service) { mSocket = new Socket(); mBaos = new ByteArrayOutputStream(BYTE_ARRAY_OUTPUT_STREAM_SIZE); mConnectionShouldBeRunning = true; mDecoder = decoder; mService = service; mLastErrorRetryTime = System.currentTimeMillis(); mLastErrorTimestamp = 0; try { mRpgTcpUrl = SettingsManager.getProperty(Settings.TCP_RPG_URL_KEY); mRpgTcpPort = Integer.parseInt(SettingsManager.getProperty(Settings.TCP_RPG_PORT_KEY)); } catch (Exception e) { HttpConnectionThread.logE("TcpConnectionThread()", "Could not parse URL or Port!", e); mRpgTcpUrl = RPG_FALLBACK_TCP_URL; mRpgTcpPort = RPG_DEFAULT_TCP_PORT; } } public void run() { -// QueueManager requestQueue = QueueManager.getInstance(); + QueueManager queueManager = QueueManager.getInstance(); mDidCriticalErrorOccur = false; try { // start the initial connection reconnectSocket(); HeartbeatSenderThread hbSender = new HeartbeatSenderThread(this, mService, mSocket); hbSender.setOutputStream(mOs); hbSender.sendHeartbeat(); hbSender = null; // TODO run this when BE supports it but keep HB in front! /* * ConnectionTester connTester = new ConnectionTester(mIs, mOs); if * (connTester.runTest()) { } else {} */ startHelperThreads(); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTED); } catch (IOException e) { haltAndRetryConnection(1); } catch (Exception e) { haltAndRetryConnection(1); } while (mConnectionShouldBeRunning) { try { if ((null != mOs) && (!mDidCriticalErrorOccur)) { List<Request> reqs = QueueManager.getInstance().getRpgRequests(); int reqNum = reqs.size(); List<Integer> reqIdList = null; if (Settings.ENABLED_TRANSPORT_TRACE || Settings.sEnableSuperExpensiveResponseFileLogging) { reqIdList = new ArrayList<Integer>(); } if (reqNum > 0) { mBaos.reset(); // batch payloads for (int i = 0; i < reqNum; i++) { Request req = reqs.get(i); if ((null == req) || (req.getAuthenticationType() == Request.USE_API)) { HttpConnectionThread.logV("TcpConnectionThread.run()", "Ignoring non-RPG method"); continue; } HttpConnectionThread.logD("TcpConnectionThread.run()", "Preparing [" + req.getRequestId() + "] for sending via RPG..."); req.setActive(true); req.writeToOutputStream(mBaos, true); if (req.isFireAndForget()) { // f-a-f, no response, // remove from queue HttpConnectionThread.logD("TcpConnectionThread.run()", "Removed F&F-Request: " + req.getRequestId()); - QueueManager.getInstance().removeRequest(req.getRequestId()); + queueManager.removeRequest(req.getRequestId()); } if (Settings.ENABLED_TRANSPORT_TRACE) { reqIdList.add(req.getRequestId()); HttpConnectionThread.logD("HttpConnectionThread.run()", "Req ID: " + req.getRequestId() + " <-> Auth: " + req.getAuth()); } } mBaos.flush(); byte[] payload = mBaos.toByteArray(); if (null != payload) { // log file containing response to SD card if (Settings.sEnableSuperExpensiveResponseFileLogging) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < reqIdList.size(); i++) { sb.append(reqIdList.get(i)); sb.append("_"); } LogUtils.logE("XXXXXXYYYXXXXXX Do not Remove this!"); LogUtils.logToFile(payload, "people_" + reqIdList.get(0) + "_" + System.currentTimeMillis() + "_req_" + ((int)payload[2]) // message // type + ".txt"); } // end log file containing response to SD card if (Settings.ENABLED_TRANSPORT_TRACE) { Long userID = null; AuthSessionHolder auth = LoginEngine.getSession(); if (auth != null) { userID = auth.userID; } HttpConnectionThread.logI("TcpConnectionThread.run()", "\n > Sending request(s) " + reqIdList.toString() + ", for user ID " + userID + " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + HessianUtils.getInHessian( new ByteArrayInputStream(payload), true) + "\n "); } try { synchronized (mOs) { mOs.write(payload); mOs.flush(); } } catch (IOException ioe) { HttpConnectionThread.logE("TcpConnectionThread.run()", "Could not send request", ioe); notifyOfNetworkProblems(); } payload = null; } } } synchronized (this) { if (!mDidCriticalErrorOccur) { wait(); } else { while (mDidCriticalErrorOccur) { // loop until a retry // succeeds HttpConnectionThread.logI("TcpConnectionThread.run()", "Wait() for next connection retry has started."); wait(Settings.TCP_RETRY_BROKEN_CONNECTION_INTERVAL); if (mConnectionShouldBeRunning) { haltAndRetryConnection(1); } } } } } catch (Throwable t) { // FlurryAgent.onError("ERROR_TCP_THREAD_CRASHED", "run()", // "TcpConnectionThread"); HttpConnectionThread.logE("TcpConnectionThread.run()", "Unknown Error: ", t); } } stopConnection(); } /** * Gets notified whenever the user is using the UI. In this special case * whenever an error occured with the connection and this method was not * called a short time before */ @Override public void notifyOfUiActivity() { if (mDidCriticalErrorOccur) { if ((System.currentTimeMillis() - mLastErrorRetryTime) >= CONNECTION_RESTART_INTERVAL) { synchronized (this) { notify(); } mLastErrorRetryTime = System.currentTimeMillis(); } } } @Override public void notifyOfRegainedNetworkCoverage() { synchronized (this) { notify(); } } /** * Called back by the response reader, which should notice network problems * first */ protected void notifyOfNetworkProblems() { HttpConnectionThread.logE("TcpConnectionThread.notifyOfNetworkProblems()", "Houston, we have a network problem!", null); haltAndRetryConnection(1); } /** * Attempts to reconnect the socket if it has been closed for some reason. * * @throws IOException Thrown if something goes wrong while reconnecting the * socket. */ private void reconnectSocket() throws IOException { HttpConnectionThread.logI("TcpConnectionThread.reconnectSocket()", "Reconnecting Socket on " + mRpgTcpUrl + ":" + mRpgTcpPort); mSocket = null; mSocket = new Socket(); mSocket.connect(new InetSocketAddress(mRpgTcpUrl, mRpgTcpPort), TCP_DEFAULT_TIMEOUT); mBufferedInputStream = new BufferedInputStream(mSocket.getInputStream()); mOs = mSocket.getOutputStream(); HttpConnectionThread.logI("TcpConnectionThread.reconnectSocket()", "Socket started: " + mRpgTcpUrl + ":" + mRpgTcpPort); } /** * <p> * Retries to establish a network connection after a network error has * occurred or the coverage of the network was lost. The amount of retries * depends on MAX_NUMBER_RETRIES. * </p> * <p> * A new retry is carried out each time an exception is thrown until the * limit of retries has been reached. * </p> * * @param numberOfRetries The amount of retries carried out until the * connection is given up. */ synchronized private void haltAndRetryConnection(int numberOfRetries) { HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "\n \n \nRETRYING CONNECTION: " + numberOfRetries + " tries."); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTING); if (!mConnectionShouldBeRunning) { // connection was killed by service // agent HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "Connection " + "was disconnected by Service Agent. Stopping retries!"); return; } stopConnection(); // stop to kill anything that might cause further IOEs // if we retried enough, we just return and end further retries if (numberOfRetries > MAX_NUMBER_RETRIES) { invalidateRequests(); mDidCriticalErrorOccur = true; mLastErrorTimestamp = System.currentTimeMillis(); /* * FlurryAgent.onError("ERROR_TCP_FAILED", * "Failed reconnecting for the 3rd time. Stopping!" + * mLastErrorTimestamp, "TcpConnectionThread"); */ synchronized (this) { notify(); // notify as we might be currently blocked on a // request's wait() } ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_DISCONNECTED); return; } try { // sleep a while to let the connection recover int sleepVal = (ERROR_RETRY_INTERVAL / 2) * numberOfRetries; Thread.sleep(sleepVal); } catch (InterruptedException ie) { } if (!mConnectionShouldBeRunning) { return; } try { reconnectSocket(); // TODO switch this block with the test connection block below // once the RPG implements this correctly. HeartbeatSenderThread hbSender = new HeartbeatSenderThread(this, mService, mSocket); hbSender.setOutputStream(mOs); hbSender.sendHeartbeat(); hbSender = null; mDidCriticalErrorOccur = false; if (!mConnectionShouldBeRunning) { return; } startHelperThreads(); // restart our connections // TODO add this once the BE supports it! /* * ConnectionTester connTester = new ConnectionTester(mIs, mOs); if * (connTester.runTest()) { mDidCriticalErrorOccur = false; * startHelperThreads(); // restart our connections Map<String, * String> map = new HashMap<String, String>(); * map.put("Last Error Timestamp", "" + mLastErrorTimestamp); * map.put("Last Error Retry Timestamp", "" + mLastErrorRetryTime); * map.put("Current Timestamp", "" + System.currentTimeMillis()); * map.put("Number of Retries", "" + numberOfRetries); * FlurryAgent.onEvent("RecoveredFromTCPError", map); } else { * HttpConnectionThread * .log("TcpConnectionThread.haltAndRetryConnection()", * "Could not receive TCP test response. need to retry..."); * haltAndRetryConnection(++numberOfRetries); } */ Map<String, String> map = new HashMap<String, String>(); map.put("Last Error Timestamp", "" + mLastErrorTimestamp); map.put("Last Error Retry Timestamp", "" + mLastErrorRetryTime); map.put("Current Timestamp", "" + System.currentTimeMillis()); map.put("Number of Retries", "" + numberOfRetries); // FlurryAgent.onEvent("RecoveredFromTCPError", map); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTED); } catch (IOException ioe) { HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "Failed sending heartbeat. Need to retry..."); haltAndRetryConnection(++numberOfRetries); } catch (Exception e) { HttpConnectionThread.logE("TcpConnectionThread.haltAndRetryConnection()", "An unknown error occured: ", e); haltAndRetryConnection(++numberOfRetries); } } /** * Invalidates all the requests so that the engines can either resend or * post an error message for the user. */ private void invalidateRequests() { QueueManager reqQueue = QueueManager.getInstance(); if (null != reqQueue) { TimeOutWatcher timeoutWatcher = reqQueue.getRequestTimeoutWatcher(); if (null != timeoutWatcher) { timeoutWatcher.invalidateAllRequests(); } } } @Override public void startThread() { if ((null != mThread) && (mThread.isAlive()) && (mConnectionShouldBeRunning)) { HttpConnectionThread.logI("TcpConnectionThread.startThread()", "No need to start Thread. " + "Already there. Returning"); return; } mConnectionShouldBeRunning = true; mThread = new Thread(this); mThread.start(); } @Override public void stopThread() { HttpConnectionThread.logI("TcpConnectionThread.stopThread()", "Stop Thread was called!"); mConnectionShouldBeRunning = false; stopConnection(); synchronized (this) { notify(); } } /** * Starts the helper threads in order to be able to read responses and send * heartbeats and passes them the needed input and output streams. */ private void startHelperThreads() { HttpConnectionThread.logI("TcpConnectionThread.startHelperThreads()", "STARTING HELPER THREADS."); if (null == mHeartbeatSender) { mHeartbeatSender = new HeartbeatSenderThread(this, mService, mSocket); HeartbeatSenderThread.mCurrentThread = mHeartbeatSender; } else { HttpConnectionThread.logE("TcpConnectionThread.startHelperThreads()", "HeartbeatSenderThread was not null!", null); } if (null == mResponseReader) { mResponseReader = new ResponseReaderThread(this, mDecoder, mSocket); ResponseReaderThread.mCurrentThread = mResponseReader; } else { HttpConnectionThread.logE("TcpConnectionThread.startHelperThreads()", "ResponseReaderThread was not null!", null); } mHeartbeatSender.setOutputStream(mOs); mResponseReader.setInputStream(mBufferedInputStream); if (!mHeartbeatSender.getIsActive()) { mHeartbeatSender.startConnection(); mResponseReader.startConnection(); } } /** * Stops the helper threads and closes the input and output streams. As the * response reader is at this point in time probably in a blocking * read()-state an IOException will need to be caught. */ private void stopHelperThreads() { HttpConnectionThread.logI("TcpConnectionThread.stopHelperThreads()", "STOPPING HELPER THREADS: " + ((null != mHeartbeatSender) ? mHeartbeatSender.getIsActive() : false)); if (null != mResponseReader) { mResponseReader.stopConnection(); } if (null != mHeartbeatSender) { mHeartbeatSender.stopConnection(); } mOs = null; mBufferedInputStream = null; mHeartbeatSender = null; mResponseReader = null; } /** * Stops the connection and its underlying socket implementation. Keeps the * thread running to allow further logins from the user. */ synchronized private void stopConnection() { HttpConnectionThread.logI("TcpConnectionThread.stopConnection()", "Closing socket..."); stopHelperThreads(); if (null != mSocket) { try { mSocket.close(); } catch (IOException ioe) { HttpConnectionThread.logE("TcpConnectionThread.stopConnection()", "Could not close Socket!", ioe); } finally { mSocket = null; } } QueueManager.getInstance().clearAllRequests(); } @Override public void notifyOfItemInRequestQueue() { HttpConnectionThread.logV("TcpConnectionThread.notifyOfItemInRequestQueue()", "NEW REQUEST AVAILABLE!"); synchronized (this) { notify(); } } @Override public boolean getIsConnected() { return mConnectionShouldBeRunning; } @Override public boolean getIsRpgConnectionActive() { if ((null != mHeartbeatSender) && (mHeartbeatSender.getIsActive())) { return true; } return false; } @Override public void onLoginStateChanged(boolean isLoggedIn) { } }
360/360-Engine-for-Android
4e84ada8552e252aa7d1bf7ec943af2f903e7d97
fix PAND-1828-thumbnails-not-loading
diff --git a/src/com/vodafone360/people/Settings.java b/src/com/vodafone360/people/Settings.java index ba89fc3..5ee7747 100644 --- a/src/com/vodafone360/people/Settings.java +++ b/src/com/vodafone360/people/Settings.java @@ -1,294 +1,293 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; /** * All application settings. */ public final class Settings { /* * LogCat. */ /** LogCat TAG prefix. **/ public static final String LOG_TAG = "People_"; /* * Transport. */ /** Milliseconds until HTTP connection will time out. */ public static final int HTTP_CONNECTION_TIMEOUT = 30000; /** Maximum number of HTTP connection attempts. */ public static final int HTTP_MAX_RETRY_COUNT = 3; /** HTTP header content type. */ public static final String HTTP_HEADER_CONTENT_TYPE = "application/binary"; /** Number of empty RPG poll responses before stopping RPG poll. */ public static final int BLANK_RPG_HEADER_COUNT = 4; /** TCP Heartbeat interval (10 seconds). */ public static final long TCP_VF_HEARTBEAT_INTERVAL = 10 * 60 * 1000; /** TCP retry interval if we have lost the connection (30 seconds). */ public static final long TCP_RETRY_BROKEN_CONNECTION_INTERVAL = 30 * 60 * 1000; /** TCP socket read time out for the read-operation. */ public static final int TCP_SOCKET_READ_TIMEOUT = 10 * 60 * 1000; /* * Notifications. */ /** LED colour. */ public static final int NOTIFICATION_LED_COLOR = 0xff00ff00; // Green /** LED on time. */ public static final int NOTIFICATION_LED_OFF_TIME = 300; /** LED on time. */ public static final int NOTIFICATION_LED_ON_TIME = 1000; /* * Upgrade Engine */ /** * See UpdateSettingsActivity.FREQUENCY_SETTING_LONG array for meaning (i.e. * Every 6 hours) */ public static final int PREFS_CHECK_FREQUENCY_DEFAULT = 3; /** Show the upgrade dialog box every 10 minutes. */ public static final int DIALOG_CHECK_FREQUENCY_MILLIS = 10 * 60 * 1000; /** * Component trace flags (always checked in as false, not part of build * script). */ /** Trace output for engine components. **/ public static final boolean ENABLED_ENGINE_TRACE = false; /** Trace output for database components. **/ public static final boolean ENABLED_DATABASE_TRACE = false; /** Trace output for transport (i.e. network IO) components. **/ public static final boolean ENABLED_TRANSPORT_TRACE = false; /** Trace output for contact synchronisation components. **/ public static final boolean ENABLED_CONTACTS_SYNC_TRACE = false; /** Log engine runtime information to file for profiling. **/ public static final boolean ENABLED_PROFILE_ENGINES = false; /** * This is a list of strings containing the names of engines to be * deactivated in the build. A de-activated engine is constructed but will * never be run (nor will onCreate or onDestroy be called). Any UI requests * will be automatically completed by the framework with a * ServiceStatus.ERROR_NOT_IMPLEMENTED error. */ public static final String DEACTIVATE_ENGINE_LIST_KEY = "deactivated-engines-list"; /* * Hard coded settings */ /** Enable dialler cheat code. **/ public static final boolean DIALER_CHEATCODES_ENABLED = true; /** Enable SMS account activation. **/ public static final boolean ENABLE_ACTIVATION = false; /** * Enable SIM inserted check. Always set to TRUE. Makes the application * unusable if there is no valid SIM card inserted into the device. */ public static final boolean ENABLE_SIM_CHECK = true; /** Enable fetching native contacts. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS = true; /** Enable fetching native contacts on change. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS_ON_CHANGE = true; /** Enable ME profile synchronisation. **/ public static final boolean ENABLE_ME_PROFILE_SYNC = true; /** Enable server contact synchronisation. **/ public static final boolean ENABLE_SERVER_CONTACT_SYNC = true; /** Enable server thumbnail synchronisation. **/ public static final boolean ENABLE_THUMBNAIL_SYNC = true; /** Enable update native contacts synchronisation. **/ public static final boolean ENABLE_UPDATE_NATIVE_CONTACTS = true; /** Enable hiding of connected friends group. **/ public static final boolean HIDE_CONNECTED_FRIENDS_GROUP = true; /* * Keys for properties that can be changed at build time. */ /** Key for application ID setting. **/ public static final String APP_KEY_ID = "app-key-id"; /** Key for application secret key setting. **/ public static final String APP_SECRET_KEY = "app-secret-key"; /** Key for enable logging setting. **/ protected static final String ENABLE_LOGCAT_KEY = "enable-logcat"; /** Key for enable RPG setting. **/ public static final String ENABLE_RPG_KEY = "use-rpg"; /** Key for enable SNS resource icon setting. **/ public static final String ENABLE_SNS_RESOURCE_ICON_KEY = "enable-sns-resource-icon"; /** Key for RPG server URL setting. **/ public static final String RPG_SERVER_KEY = "rpg-url"; /** Key for Hessian URL setting. **/ public static final String SERVER_URL_HESSIAN_KEY = "hessian-url"; /* * Keys without defaults. */ /** Key for TCP server URL setting. **/ public static final String TCP_RPG_URL_KEY = "rpg-tcp-url"; /** Key for TCP port setting. **/ public static final String TCP_RPG_PORT_KEY = "rpg-tcp-port"; /** Key for upgrade check URL setting. **/ public static final String UPGRADE_CHECK_URL_KEY = "upgrade-url"; /* * Default for properties that can be changed at build time. */ /** Default for logging enabled setting. **/ protected static final String DEFAULT_ENABLE_LOGCAT = "true"; /** Default for RPG enabled setting. **/ protected static final String DEFAULT_ENABLE_RPG = "true"; /** Default for SNS resource icon setting. **/ protected static final String DEFAULT_ENABLE_SNS_RESOURCE_ICON = "true"; /** Default for RPG server URL setting. **/ protected static final String DEFAULT_RPG_SERVER = "http://rpg.vodafone360.com/rpg/mcomet/"; /** Default for Hessian URL setting. **/ protected static final String DEFAULT_SERVER_URL_HESSIAN = "http://api.vodafone360.com/services/hessian/"; /* * Request timeouts for all engines and requests, except for fire and * forget calls to RPG: SET_AVAILABILITY and SEND_CHAT_MSG. */ /** Do not handle timeouts for this API. **/ private static final long DONT_HANDLE_TIMEOUTS = -1; /** Generic timeout for requests. **/ private static final long ALL_ENGINES_REQUESTS_TIMEOUT = 60000; /** Timeout for all presence API requests. **/ private static final long PRESENCE_ENGINE_REQUESTS_TIMEOUT = 120000; /** Number of milliseconds in a week. **/ public static final long HISTORY_IS_WEEK_LONG = 7 * 24 * 60 * 60 * 1000; /** Timeout for request waiting in queue. **/ public static final long REMOVE_REQUEST_FROM_QUEUE_MILLIS = 15 * 60 * 1000; /* * The timeouts in milliseconds for the different APIs. */ /** Timeout for activities API. **/ public static final long API_REQUESTS_TIMEOUT_ACTIVITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for authentication API. **/ public static final long API_REQUESTS_TIMEOUT_AUTH = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat create conversation API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_CREATE_CONV = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat send message API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_SEND_MESSAGE = DONT_HANDLE_TIMEOUTS; /** Timeout for contacts API. **/ public static final long API_REQUESTS_TIMEOUT_CONTACTS = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for group privacy API. **/ public static final long API_REQUESTS_TIMEOUT_GROUP_PRIVACY = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for identities API. **/ public static final long API_REQUESTS_TIMEOUT_IDENTITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for presence list API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_LIST = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Timeout for presence set availability API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Enable Facebook chat. **/ public static boolean sEnableFacebookChat = true; /** * Danger! Only set to true if you know what you are doing! This logs each * response no matter if gzipped or not to the SD card under the given * request ID. */ public static boolean sEnableSuperExpensiveResponseFileLogging = false; /** * Private constructor to prevent instantiation. */ private Settings() { - // Do nothing. } } \ No newline at end of file diff --git a/src/com/vodafone360/people/service/io/QueueManager.java b/src/com/vodafone360/people/service/io/QueueManager.java index e7b61fe..2c5f665 100644 --- a/src/com/vodafone360/people/service/io/QueueManager.java +++ b/src/com/vodafone360/people/service/io/QueueManager.java @@ -1,260 +1,275 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.util.List; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.transport.IQueueListener; import com.vodafone360.people.service.utils.TimeOutWatcher; /** * A facade class used for adding and removing from the request and response * queues. The methods used in this class are thread safe and should be used * instead of using the queues directly. * * @author Rudy Norff ([email protected]) */ public class QueueManager { public final Object lock = new Object(); private RequestQueue mRequestQueue; private ResponseQueue mResponseQueue; /** * Returns a single instance of the RequestResponseManager which holds * the request and response queues. Uses IDOH idiom. * * @return The RequestResponseManager object to use for adding and removing * requests from the request and response queues. */ public static QueueManager getInstance() { return QueueManagerHolder.rQueue; } /** * Use Initialization on demand holder pattern */ private static class QueueManagerHolder { private static final QueueManager rQueue = new QueueManager(); } private QueueManager() { mRequestQueue = RequestQueue.getInstance(); mResponseQueue = ResponseQueue.getInstance(); } /** * Adds a response to the response queue. * * @param response The response to add to the queue. */ public void addResponse(DecodedResponse response) { synchronized (lock) { mResponseQueue.addToResponseQueue(response); } } /** * Returns the next response in the response queue for the given engine. * That way an engine can easily get a response that it is responsible for. * * @param sourceEngine The source engine * @return The next response for the given source engine. */ /* public Response getNextResponse(EngineId sourceEngine) { synchronized (lock) { return mResponseQueue.getNextResponse(sourceEngine); } } */ /** * Clears all request timeouts that were added to the timeout watcher. */ public void clearRequestTimeouts() { mRequestQueue.clearTheTimeOuts(); } /** * Returns a timeout-watcher of requests from the request queue. * * @return The timeout watcher inside the request queue. */ public TimeOutWatcher getRequestTimeoutWatcher() { return mRequestQueue.getTimeoutWatcher(); } /** * Clears all requests from the request queue and puts null responses on the * response queue to tell the engines that they have been cleared. This * should be called from the connection thread as soon as it is stopped. */ public void clearAllRequests() { synchronized (lock) { mRequestQueue.clearAllRequests(); } } /** * Clear active requests (i.e add dummy response to response queue). * * @param rpgOnly If true only RPG requests will be cleared. */ public void clearActiveRequests(boolean rpgOnly) { synchronized (lock) { mRequestQueue.clearActiveRequests(rpgOnly); } } + /** + * Removes the request for the ID of the given DecodedResponse from the queue, + * assigns the source in the response object according to the engineId of + * the request and searches the queue for requests older than + * Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS and removes them as well. + * + * @param response The response object. + * @return True if the request was found and removed. + */ + public boolean removeRequest(DecodedResponse response) { + synchronized (lock) { + return mRequestQueue.removeRequest(response); + } + } + /** * Removes the request for the given request ID from the queue and searches * the queue for requests older than * Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS and removes them as well. * - * @param requestId The ID of the request to remove. + * @param requestId - the id of the request in he queue. * @return True if the request was found and removed. */ public boolean removeRequest(int requestId) { synchronized (lock) { return mRequestQueue.removeRequest(requestId); } } /** * Return Request from specified request ID. Only used for unit tests. * * @param requestId Request Id of required request * @return Request with or null if request does not exist */ public Request getRequest(int requestId) { return mRequestQueue.getRequest(requestId); } /** * Returns all requests from the queue needing the API or both to work. * * @return List of all requests needing the API or both (API or RPG) to * function properly. */ public List<Request> getApiRequests() { synchronized (lock) { return mRequestQueue.getApiRequests(); } } /** * Returns all requests from the queue needing the RPG or both to work. * * @return List of all requests needing the RPG or both (API or RPG) to * function properly. */ public List<Request> getRpgRequests() { synchronized (lock) { return mRequestQueue.getRpgRequests(); } } /** * Returns all requests from the queue. Regardless if they need to * * @return List of all requests. */ public List<Request> getAllRequests() { synchronized (lock) { return mRequestQueue.getAllRequests(); } } /** * Adds requests to the queue. * * @param requests The requests to add. * @return The request IDs generated in an integer array or null if the * requests array was null. */ public int[] addRequest(Request[] requests) { synchronized (lock) { return mRequestQueue.addRequest(requests); } } /** * Adds a request to the queue without sending an event to the listeners * * @param request The request to add * @return The unique request ID TODO: What is with the method naming * convention? */ public int addRequest(Request request) { synchronized (lock) { return mRequestQueue.addRequest(request); } } /** * Add request to queue and notify the queue listener. * * @param request The request to add to the queue. * @return The request ID of the added request. */ public int addRequestAndNotify(Request request) { synchronized (lock) { return mRequestQueue.addRequestAndNotify(request); } } /** * Fire a manual queue state changed event to notify the queue listener that * a request is on the request queue. */ public void fireQueueStateChanged() { mRequestQueue.fireQueueStateChanged(); } /** * Adds a listener listening for RequestQueue changes. Events are sent when * items are added to the queue (or in the case of batching when the last * item is added to the queue). * * @param listener Listener to add to the list of request queue listeners. */ public void addQueueListener(IQueueListener listener) { mRequestQueue.addQueueListener(listener); } /** * Remove RequestQueue listener from the list. * * @param listener The listener to remove. */ public void removeQueueListener(IQueueListener listener) { mRequestQueue.removeQueueListener(listener); } } diff --git a/src/com/vodafone360/people/service/io/RequestQueue.java b/src/com/vodafone360/people/service/io/RequestQueue.java index 07394fc..8d2a381 100644 --- a/src/com/vodafone360/people/service/io/RequestQueue.java +++ b/src/com/vodafone360/people/service/io/RequestQueue.java @@ -1,491 +1,562 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.util.ArrayList; import java.util.List; import com.vodafone360.people.Settings; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.transport.IQueueListener; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.TimeOutWatcher; import com.vodafone360.people.utils.LogUtils; /** * Holds a queue of outgoing requests. The Requester adds Requests to the queue. * The transport layer gets one or more items from the queue when it is ready to * send more requests to the server. When a Request is added a request id is * generated for this request. Requests are removed from the queue on completion * or if an error requires us to clear any outstanding requests. */ public class RequestQueue { private final static int MILLIS_PER_SECOND = 1000; /** * The queue data, a List-array of Request items. */ private final List<Request> mRequests = new ArrayList<Request>(); /** * A unique ID identifying this request */ private volatile int mCurrentRequestId; /** * Contains a list of listeners that will receive events when items are * added to the queue. */ private final List<IQueueListener> mListeners = new ArrayList<IQueueListener>(); private TimeOutWatcher mTimeOutWatcher; /** * Constructs the request queue */ protected RequestQueue() { // Generate initial request ID based on current timestamp. mCurrentRequestId = (int)(System.currentTimeMillis() / MILLIS_PER_SECOND); mTimeOutWatcher = new TimeOutWatcher(); } /** * Get instance of RequestQueue - we only have a single instance. If the * instance of RequestQueue does not yet exist it is created. * * @return Instance of RequestQueue. */ protected static RequestQueue getInstance() { return RequestQueueHolder.rQueue; } /** * Use Initialization on demand holder pattern */ private static class RequestQueueHolder { private static final RequestQueue rQueue = new RequestQueue(); } /** * Add listener listening for RequestQueue changes. Events are sent when * items are added to the queue (or in the case of batching when the last * item is added to the queue). * * @param listener listener to add */ protected void addQueueListener(IQueueListener listener) { LogUtils.logW("RequestQueue.addQueueListener() listener[" + listener + "]"); synchronized (mListeners) { if (mListeners != null) { mListeners.add(listener); } } } /** * Remove RequestQueue listener * * @param listener listener to remove */ protected void removeQueueListener(IQueueListener listener) { LogUtils.logW("RequestQueue.removeQueueListener() listener[" + listener + "]"); synchronized (mListeners) { if (mListeners != null) { mListeners.remove(listener); } } } /** * Fire RequestQueue state changed message */ protected void fireQueueStateChanged() { synchronized (mListeners) { LogUtils.logW("RequestQueue.notifyOfItemInRequestQueue() listener[" + mListeners + "]"); for (IQueueListener listener : mListeners) { listener.notifyOfItemInRequestQueue(); } } } /** * Add request to queue * * @param req Request to add to queue * @return request id of new request */ protected int addRequestAndNotify(Request req) { synchronized (QueueManager.getInstance().lock) { int ret = addRequest(req); fireQueueStateChanged(); return ret; } } /** * Adds a request to the queue without sending an event to the listeners * * @param req The request to add * @return The unique request ID TODO: What is with the method naming * convention? */ protected int addRequest(Request req) { synchronized (QueueManager.getInstance().lock) { mCurrentRequestId++; req.setRequestId(mCurrentRequestId); mRequests.add(req); // add the request to the watcher thread if (req.getTimeout() > 0 && (!req.isFireAndForget())) { // TODO: maybe the expiry date should be calculated when the // request is actually sent? req.calculateExpiryDate(); mTimeOutWatcher.addRequest(req); } HttpConnectionThread.logV("RequestQueue.addRequest", "Adding request to queue:\n" + req.toString()); return mCurrentRequestId; } } /** * Adds requests to the queue. * * @param requests The requests to add. * @return The request IDs generated in an integer array or null if the * requests array was null. Returns NULL id requests[] is NULL. */ protected int[] addRequest(Request[] requests) { synchronized (QueueManager.getInstance().lock) { if (null == requests) { return null; } int[] requestIds = new int[requests.length]; for (int i = 0; i < requests.length; i++) { requestIds[i] = addRequest(requests[i]); } return requestIds; } } /* * Get number of items currently in the list of requests * @return number of request items */ private int requestCount() { return mRequests.size(); } /** * Returns all requests from the queue. Regardless if they need to * * @return List of all requests. */ protected List<Request> getAllRequests() { synchronized (QueueManager.getInstance().lock) { return mRequests; } } /** * Returns all requests from the queue needing the API or both to work. * * @return List of all requests needing the API or both (API or RPG) to * function properly. */ protected List<Request> getApiRequests() { synchronized (QueueManager.getInstance().lock) { return this.getRequests(false); } } /** * Returns all requests from the queue needing the RPG or both to work. * * @return List of all requests needing the RPG or both (API or RPG) to * function properly. */ protected List<Request> getRpgRequests() { return this.getRequests(true); } /** * Returns a list of either requests needing user authentication or requests * not needing user authentication depending on the flag passed to this * method. * * @param needsUserAuthentication If true only requests that need to have a * valid user authentication will be returned. Otherwise methods * requiring application authentication will be returned. * @return A list of requests with the need for application authentication * or user authentication. */ private List<Request> getRequests(boolean needsRpgForRequest) { synchronized (QueueManager.getInstance().lock) { List<Request> requests = new ArrayList<Request>(); if (null == mRequests) { return requests; } Request request = null; for (int i = 0; i < mRequests.size(); i++) { request = mRequests.get(i); if ((null == request) || (request.isActive())) { LogUtils.logD("Skipping active or null request in request queue."); continue; } HttpConnectionThread.logD("RequestQueu.getRequests()", "Request Auth Type (USE_API=1, USE_RPG=2, USE_BOTH=3): " + request.getAuthenticationType()); // all api and rpg requests if (request.getAuthenticationType() == Request.USE_BOTH) { requests.add(request); } else if ((!needsRpgForRequest) && (request.getAuthenticationType() == Request.USE_API)) { requests.add(request); } else if ((needsRpgForRequest) && (request.getAuthenticationType() == Request.USE_RPG)) { requests.add(request); // all rpg requests } } return requests; } } /** * Return Request from specified request ID. Only used for unit tests. * * @param requestId Request Id of required request * @return Request with or null if request does not exist */ protected Request getRequest(int requestId) { Request req = null; int reqCount = requestCount(); for (int i = 0; i < reqCount; i++) { Request tmp = mRequests.get(i); if (tmp.getRequestId() == requestId) { req = tmp; break; } } return req; } + /** + * Removes the request for the ID of the given DecodedResponse from the queue, + * assigns the source in the response object according to the engineId of + * the request and searches the queue for requests older than + * Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS and removes them as well. + * + * This method should be only called by the QueueManager. + * + * @param response The decoded response object. + * @return True if the request was found and removed. + */ + boolean removeRequest(DecodedResponse response) { + synchronized (QueueManager.getInstance().lock) { + boolean didRemoveSearchedRequest = false; + + for (int i = 0; i < requestCount(); i++) { + Request request = mRequests.get(i); + // the request we were looking for + if (request.getRequestId() == response.mReqId) { + // reassure the engine id is set (important for SystemNotifications) + response.mSource = request.mEngineId; + mRequests.remove(i--); + + // remove the request from the watcher (the request not + // necessarily times out before) + if (request.getExpiryDate() > 0) { + mTimeOutWatcher.removeRequest(request); + LogUtils + .logV("RequestQueue.removeRequest() Request expired after [" + + (System.currentTimeMillis() - request.getAuthTimestamp()) + + "ms]"); + } else { + LogUtils + .logV("RequestQueue.removeRequest() Request took [" + + (System.currentTimeMillis() - request.getAuthTimestamp()) + + "ms]"); + } + + didRemoveSearchedRequest = true; + } else if ((System.currentTimeMillis() - request.getCreationTimestamp()) > Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS) { // request + // is older than 15 minutes + mRequests.remove(i--); + + ResponseQueue.getInstance().addToResponseQueue(new DecodedResponse(request.getRequestId(), null, request.mEngineId, + DecodedResponse.ResponseType.TIMED_OUT_RESPONSE.ordinal())); + + // remove the request from the watcher (the request not + // necessarily times out before) + if (request.getExpiryDate() > 0) { + mTimeOutWatcher.removeRequest(request); + LogUtils + .logV("RequestQueue.removeRequest() Request expired after [" + + (System.currentTimeMillis() - request.getAuthTimestamp()) + + "ms]"); + } else { + LogUtils + .logV("RequestQueue.removeRequest() Request took [" + + (System.currentTimeMillis() - request.getAuthTimestamp()) + + "ms]"); + } + } + + } + + return didRemoveSearchedRequest; + } + } + + /** * Removes the request for the given request ID from the queue and searches * the queue for requests older than * Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS and removes them as well. * - * @param requestId The ID of the request to remove. + * @param response The decoded response object. * @return True if the request was found and removed. */ - protected boolean removeRequest(int requestId) { + protected boolean removeRequest(int responseId) { synchronized (QueueManager.getInstance().lock) { boolean didRemoveSearchedRequest = false; for (int i = 0; i < requestCount(); i++) { Request request = mRequests.get(i); - - if (request.getRequestId() == requestId) { // the request we - // were looking for + // the request we were looking for + if (request.getRequestId() == responseId) { + // reassure the engine id is set (important for SystemNotifications) mRequests.remove(i--); // remove the request from the watcher (the request not // necessarily times out before) if (request.getExpiryDate() > 0) { mTimeOutWatcher.removeRequest(request); LogUtils .logV("RequestQueue.removeRequest() Request expired after [" + (System.currentTimeMillis() - request.getAuthTimestamp()) + "ms]"); } else { LogUtils .logV("RequestQueue.removeRequest() Request took [" + (System.currentTimeMillis() - request.getAuthTimestamp()) + "ms]"); } didRemoveSearchedRequest = true; } else if ((System.currentTimeMillis() - request.getCreationTimestamp()) > Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS) { // request // is older than 15 minutes mRequests.remove(i--); ResponseQueue.getInstance().addToResponseQueue(new DecodedResponse(request.getRequestId(), null, request.mEngineId, - DecodedResponse.ResponseType.TIMED_OUT_RESPONSE.ordinal())); + DecodedResponse.ResponseType.TIMED_OUT_RESPONSE.ordinal())); // remove the request from the watcher (the request not // necessarily times out before) if (request.getExpiryDate() > 0) { mTimeOutWatcher.removeRequest(request); LogUtils .logV("RequestQueue.removeRequest() Request expired after [" + (System.currentTimeMillis() - request.getAuthTimestamp()) + "ms]"); } else { LogUtils .logV("RequestQueue.removeRequest() Request took [" + (System.currentTimeMillis() - request.getAuthTimestamp()) + "ms]"); } } } return didRemoveSearchedRequest; } } + + /** * Return the current (i.e. most recently generated) request id. * * @return the current request id. */ /* * public synchronized int getCurrentId(){ return mCurrentRequestId; } */ /** * Clear active requests (i.e add dummy response to response queue). * * @param rpgOnly */ protected void clearActiveRequests(boolean rpgOnly) { synchronized (QueueManager.getInstance().lock) { ResponseQueue rQ = ResponseQueue.getInstance(); for (int i = 0; i < mRequests.size(); i++) { Request request = mRequests.get(i); if (request.isActive() && (!rQ.responseExists(request.getRequestId()))) { if (!rpgOnly || (rpgOnly && ((request.getAuthenticationType() == Request.USE_RPG) || (request .getAuthenticationType() == Request.USE_BOTH)))) { LogUtils.logE("RequestQueue.clearActiveRequests() Deleting request " + request.getRequestId()); mRequests.remove(i); // AA: I added the line below // remove the request from the watcher (the request not // necessarily times out before) if (request.getExpiryDate() > 0) { mTimeOutWatcher.removeRequest(request); } i--; rQ.addToResponseQueue(new DecodedResponse(request.getRequestId(), null, request.mEngineId, DecodedResponse.ResponseType.TIMED_OUT_RESPONSE.ordinal())); } } } } } /** * Clears all requests from the queue and puts null responses on the * response queue to tell the engines that they have been cleared. This * should be called from the connection thread as soon as it is stopped. */ protected void clearAllRequests() { synchronized (QueueManager.getInstance().lock) { ResponseQueue responseQueue = ResponseQueue.getInstance(); for (int i = 0; i < mRequests.size(); i++) { Request request = mRequests.get(i); LogUtils.logE("RequestQueue.clearActiveRequests() Deleting request " + request.getRequestId()); mRequests.remove(i--); // remove the request from the watcher (the request not // necessarily times out before) if (request.getExpiryDate() > 0) { mTimeOutWatcher.removeRequest(request); } responseQueue.addToResponseQueue(new DecodedResponse(request.getRequestId(), null, request.mEngineId, DecodedResponse.ResponseType.TIMED_OUT_RESPONSE.ordinal())); } } } /** * Return handle to TimeOutWatcher. * * @return handle to TimeOutWatcher. */ protected TimeOutWatcher getTimeoutWatcher() { return mTimeOutWatcher; } /** * Removes all items that are being watched for timeouts */ protected void clearTheTimeOuts() { if (mTimeOutWatcher != null) { mTimeOutWatcher.kill(); } } /** * Overrides the toString() method of Object and gives detailed infos which * objects are on the queue and whether they are active or not. */ @Override public String toString() { if (null == mRequests) { return ""; } final StringBuffer sb = new StringBuffer("Queue Size: "); sb.append(mRequests.size()); sb.append("; Request method-name [isActive]: "); for (int i = 0; i < mRequests.size(); i++) { Request request = mRequests.get(i); if (null == request) { sb.append("null request"); } else { sb.append(request.getApiMethodName()); sb.append(" ["); sb.append(request.isActive()); sb.append("]"); } if (i < (mRequests.size() - 1)) { sb.append(", "); } } return sb.toString(); } } diff --git a/src/com/vodafone360/people/service/io/ResponseQueue.java b/src/com/vodafone360/people/service/io/ResponseQueue.java index ecde2f4..1937e64 100644 --- a/src/com/vodafone360/people/service/io/ResponseQueue.java +++ b/src/com/vodafone360/people/service/io/ResponseQueue.java @@ -1,259 +1,260 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.util.ArrayList; import java.util.List; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.LogUtils; /** * Queue of responses received from server. These may be either responses to * requests issued by the People client or unsolicited ('Push') messages. The * content of these Responses will have already been decoded by the * DecoderThread and converted to data-types understood by the People Client. */ public class ResponseQueue { /** * The list of responses held by this queue. An array-list of Responses. */ private final List<DecodedResponse> mResponses = new ArrayList<DecodedResponse>(); /** * The engine manager holding the various engines to cross check where * responses belong to. */ private EngineManager mEngMgr = null; /** * Class encapsulating a decoded response from the server A Response * contains; a request id which should match a request id from a request * issued by the People Client (responses to non-RPG requests or * non-solicited messages will not have a request id), the request data, a * list of decoded BaseDataTypes generated from the response content and an * engine id informing the framework which engine the response should be * routed to. */ public static class DecodedResponse { public static enum ResponseType { /** An unknown response in case anything went wrong. */ UNKNOWN, /** A response for a request that timed out. */ SERVER_ERROR, /** A response that timed out before it arrived from the server. */ TIMED_OUT_RESPONSE, /** Represents a push message that was pushed by the server */ PUSH_MESSAGE, /** The response type for available identities. */ GET_AVAILABLE_IDENTITIES_RESPONSE, /** The response type for my identities. */ GET_MY_IDENTITIES_RESPONSE, /** The response type for set identity capability */ SET_IDENTITY_CAPABILITY_RESPONSE, /** The response type for validate identity credentials */ VALIDATE_IDENTITY_CREDENTIALS_RESPONSE, /** The response type for get activities calls. */ GET_ACTIVITY_RESPONSE, /** The response type for get session by credentials calls. */ LOGIN_RESPONSE, /** The response type for bulkupdate contacts calls. */ BULKUPDATE_CONTACTS_RESPONSE, /** The response type for get contacts changes calls. */ GET_CONTACTCHANGES_RESPONSE, /** The response type for get get me calls. */ GETME_RESPONSE, /** The response type for get contact group relation calls. */ GET_CONTACT_GROUP_RELATIONS_RESPONSE, /** The response type for get groups calls. */ GET_GROUPS_RESPONSE, /** The response type for add contact calls. */ ADD_CONTACT_RESPONSE, /** The response type for signup user crypted calls. */ SIGNUP_RESPONSE, /** The response type for get public key calls. */ RETRIEVE_PUBLIC_KEY_RESPONSE, /** The response type for delete contacts calls. */ DELETE_CONTACT_RESPONSE, /** The response type for delete contact details calls. */ DELETE_CONTACT_DETAIL_RESPONSE, /** The response type for get presence calls. */ GET_PRESENCE_RESPONSE, /** The response type for create conversation calls. */ CREATE_CONVERSATION_RESPONSE, /** The response type for get t&cs. */ GET_T_AND_C_RESPONSE, /** The response type for get privacy statement. */ GET_PRIVACY_STATEMENT_RESPONSE; // TODO add more types here and remove them from the BaseDataType. Having them in ONE location is better than in dozens!!! } /** The type of the response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ private int mResponseType; /** The request ID the response came in for. */ public Integer mReqId; /** The response items (e.g. identities of a getAvailableIdentities call) to store for the response. */ public List<BaseDataType> mDataTypes = new ArrayList<BaseDataType>(); /** The ID of the engine the response should be worked off in. */ public EngineId mSource; /** * Constructs a response object with request ID, the data and the engine * ID the response belongs to. * * @param reqId The corresponding request ID for the response. * @param data The data of the response. * @param source The originating engine ID. * @param responseType The response type. Values can be found in Response.ResponseType. * */ public DecodedResponse(Integer reqId, List<BaseDataType> data, EngineId source, final int responseType) { mReqId = reqId; mDataTypes = data; mSource = source; mResponseType = responseType; } /** * The response type for this response. The types are defined in Response.ResponseType. * * @return The response type of this response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ public int getResponseType() { return mResponseType; } } /** * Protected constructor to highlight the singleton nature of this class. */ protected ResponseQueue() { } /** * Gets an instance of the ResponseQueue as part of the singleton pattern. * * @return The instance of ResponseQueue. */ public static ResponseQueue getInstance() { return ResponseQueueHolder.rQueue; } /** * Use Initialization on demand holder pattern */ private static class ResponseQueueHolder { private static final ResponseQueue rQueue = new ResponseQueue(); } /** * Adds a response item to the queue. * * @param reqId The request ID to add the response for. * @param data The response data to add to the queue. * @param source The corresponding engine that fired off the request for the * response. */ public void addToResponseQueue(final DecodedResponse response) { synchronized (QueueManager.getInstance().lock) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.UNKNOWN_DATA_TYPE, response.mDataTypes); if (status == ServiceStatus.ERROR_INVALID_SESSION) { EngineManager em = EngineManager.getInstance(); if (em != null) { LogUtils.logE("Logging out the current user because of invalide session"); em.getLoginEngine().logoutAndRemoveUser(); return; } } mResponses.add(response); - final RequestQueue rQ = RequestQueue.getInstance(); - rQ.removeRequest(response.mReqId); + + QueueManager.getInstance().removeRequest(response); + mEngMgr = EngineManager.getInstance(); if (mEngMgr != null) { mEngMgr.onCommsInMessage(response.mSource); } } } /** * Retrieves the next response in the list if there is one. * * @param source The originating engine id that requested this response. * @return Response The first response that matches the given engine or null * if no response was found. */ public DecodedResponse getNextResponse(EngineId source) { DecodedResponse resp = null; for (int i = 0; i < mResponses.size(); i++) { resp = mResponses.get(i); if (resp.mSource == source) { mResponses.remove(i); if (source != null) { LogUtils.logV("ResponseQueue.getNextResponse() Returning a response to engine[" + source.name() + "]"); } return resp; } } return null; } /** * Get number of items currently in the response queue. * * @return number of items currently in the response queue. */ private int responseCount() { return mResponses.size(); } /** * Test if we have response for the specified request id. * * @param reqId Request ID. * @return true If we have a response for this ID. */ protected synchronized boolean responseExists(int reqId) { boolean exists = false; for (int i = 0; i < responseCount(); i++) { if (mResponses.get(i).mReqId != null && mResponses.get(i).mReqId.intValue() == reqId) { exists = true; break; } } return exists; } } diff --git a/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java b/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java index 42e4aa0..b162d45 100644 --- a/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java +++ b/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java @@ -1,590 +1,590 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.transport.tcp; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.DecoderThread; import com.vodafone360.people.service.transport.IConnection; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.TimeOutWatcher; import com.vodafone360.people.service.utils.hessian.HessianUtils; import com.vodafone360.people.utils.LogUtils; public class TcpConnectionThread implements Runnable, IConnection { private static final String RPG_FALLBACK_TCP_URL = "rpg.vodafone360.com"; private static final int RPG_DEFAULT_TCP_PORT = 9900; private static final int TCP_DEFAULT_TIMEOUT = 120000; private static final int ERROR_RETRY_INTERVAL = 10000; /** * If we have a connection error we try to restart after 60 seconds earliest */ private static final int CONNECTION_RESTART_INTERVAL = 60000; /** * The maximum number of retries to reestablish a connection until we sleep * until the user uses the UI or * Settings.TCP_RETRY_BROKEN_CONNECTION_INTERVAL calls another retry. */ private static final int MAX_NUMBER_RETRIES = 3; private static final int BYTE_ARRAY_OUTPUT_STREAM_SIZE = 2048; // bytes private Thread mThread; private RemoteService mService; private DecoderThread mDecoder; private boolean mConnectionShouldBeRunning; private boolean mDidCriticalErrorOccur; private BufferedInputStream mBufferedInputStream; private OutputStream mOs; private String mRpgTcpUrl; private int mRpgTcpPort; private Socket mSocket; private HeartbeatSenderThread mHeartbeatSender; private ResponseReaderThread mResponseReader; private long mLastErrorRetryTime, mLastErrorTimestamp; private ByteArrayOutputStream mBaos; public TcpConnectionThread(DecoderThread decoder, RemoteService service) { mSocket = new Socket(); mBaos = new ByteArrayOutputStream(BYTE_ARRAY_OUTPUT_STREAM_SIZE); mConnectionShouldBeRunning = true; mDecoder = decoder; mService = service; mLastErrorRetryTime = System.currentTimeMillis(); mLastErrorTimestamp = 0; try { mRpgTcpUrl = SettingsManager.getProperty(Settings.TCP_RPG_URL_KEY); mRpgTcpPort = Integer.parseInt(SettingsManager.getProperty(Settings.TCP_RPG_PORT_KEY)); } catch (Exception e) { HttpConnectionThread.logE("TcpConnectionThread()", "Could not parse URL or Port!", e); mRpgTcpUrl = RPG_FALLBACK_TCP_URL; mRpgTcpPort = RPG_DEFAULT_TCP_PORT; } } public void run() { - QueueManager requestQueue = QueueManager.getInstance(); +// QueueManager requestQueue = QueueManager.getInstance(); mDidCriticalErrorOccur = false; try { // start the initial connection reconnectSocket(); HeartbeatSenderThread hbSender = new HeartbeatSenderThread(this, mService, mSocket); hbSender.setOutputStream(mOs); hbSender.sendHeartbeat(); hbSender = null; // TODO run this when BE supports it but keep HB in front! /* * ConnectionTester connTester = new ConnectionTester(mIs, mOs); if * (connTester.runTest()) { } else {} */ startHelperThreads(); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTED); } catch (IOException e) { haltAndRetryConnection(1); } catch (Exception e) { haltAndRetryConnection(1); } while (mConnectionShouldBeRunning) { try { if ((null != mOs) && (!mDidCriticalErrorOccur)) { List<Request> reqs = QueueManager.getInstance().getRpgRequests(); int reqNum = reqs.size(); List<Integer> reqIdList = null; if (Settings.ENABLED_TRANSPORT_TRACE || Settings.sEnableSuperExpensiveResponseFileLogging) { reqIdList = new ArrayList<Integer>(); } if (reqNum > 0) { mBaos.reset(); // batch payloads for (int i = 0; i < reqNum; i++) { Request req = reqs.get(i); if ((null == req) || (req.getAuthenticationType() == Request.USE_API)) { HttpConnectionThread.logV("TcpConnectionThread.run()", "Ignoring non-RPG method"); continue; } HttpConnectionThread.logD("TcpConnectionThread.run()", "Preparing [" + req.getRequestId() + "] for sending via RPG..."); req.setActive(true); req.writeToOutputStream(mBaos, true); if (req.isFireAndForget()) { // f-a-f, no response, // remove from queue HttpConnectionThread.logD("TcpConnectionThread.run()", "Removed F&F-Request: " + req.getRequestId()); - requestQueue.removeRequest(req.getRequestId()); + QueueManager.getInstance().removeRequest(req.getRequestId()); } if (Settings.ENABLED_TRANSPORT_TRACE) { reqIdList.add(req.getRequestId()); HttpConnectionThread.logD("HttpConnectionThread.run()", "Req ID: " + req.getRequestId() + " <-> Auth: " + req.getAuth()); } } mBaos.flush(); byte[] payload = mBaos.toByteArray(); if (null != payload) { // log file containing response to SD card if (Settings.sEnableSuperExpensiveResponseFileLogging) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < reqIdList.size(); i++) { sb.append(reqIdList.get(i)); sb.append("_"); } LogUtils.logE("XXXXXXYYYXXXXXX Do not Remove this!"); LogUtils.logToFile(payload, "people_" + reqIdList.get(0) + "_" + System.currentTimeMillis() + "_req_" + ((int)payload[2]) // message // type + ".txt"); } // end log file containing response to SD card if (Settings.ENABLED_TRANSPORT_TRACE) { Long userID = null; AuthSessionHolder auth = LoginEngine.getSession(); if (auth != null) { userID = auth.userID; } HttpConnectionThread.logI("TcpConnectionThread.run()", "\n > Sending request(s) " + reqIdList.toString() + ", for user ID " + userID + " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + HessianUtils.getInHessian( new ByteArrayInputStream(payload), true) + "\n "); } try { synchronized (mOs) { mOs.write(payload); mOs.flush(); } } catch (IOException ioe) { HttpConnectionThread.logE("TcpConnectionThread.run()", "Could not send request", ioe); notifyOfNetworkProblems(); } payload = null; } } } synchronized (this) { if (!mDidCriticalErrorOccur) { wait(); } else { while (mDidCriticalErrorOccur) { // loop until a retry // succeeds HttpConnectionThread.logI("TcpConnectionThread.run()", "Wait() for next connection retry has started."); wait(Settings.TCP_RETRY_BROKEN_CONNECTION_INTERVAL); if (mConnectionShouldBeRunning) { haltAndRetryConnection(1); } } } } } catch (Throwable t) { // FlurryAgent.onError("ERROR_TCP_THREAD_CRASHED", "run()", // "TcpConnectionThread"); HttpConnectionThread.logE("TcpConnectionThread.run()", "Unknown Error: ", t); } } stopConnection(); } /** * Gets notified whenever the user is using the UI. In this special case * whenever an error occured with the connection and this method was not * called a short time before */ @Override public void notifyOfUiActivity() { if (mDidCriticalErrorOccur) { if ((System.currentTimeMillis() - mLastErrorRetryTime) >= CONNECTION_RESTART_INTERVAL) { synchronized (this) { notify(); } mLastErrorRetryTime = System.currentTimeMillis(); } } } @Override public void notifyOfRegainedNetworkCoverage() { synchronized (this) { notify(); } } /** * Called back by the response reader, which should notice network problems * first */ protected void notifyOfNetworkProblems() { HttpConnectionThread.logE("TcpConnectionThread.notifyOfNetworkProblems()", "Houston, we have a network problem!", null); haltAndRetryConnection(1); } /** * Attempts to reconnect the socket if it has been closed for some reason. * * @throws IOException Thrown if something goes wrong while reconnecting the * socket. */ private void reconnectSocket() throws IOException { HttpConnectionThread.logI("TcpConnectionThread.reconnectSocket()", "Reconnecting Socket on " + mRpgTcpUrl + ":" + mRpgTcpPort); mSocket = null; mSocket = new Socket(); mSocket.connect(new InetSocketAddress(mRpgTcpUrl, mRpgTcpPort), TCP_DEFAULT_TIMEOUT); mBufferedInputStream = new BufferedInputStream(mSocket.getInputStream()); mOs = mSocket.getOutputStream(); HttpConnectionThread.logI("TcpConnectionThread.reconnectSocket()", "Socket started: " + mRpgTcpUrl + ":" + mRpgTcpPort); } /** * <p> * Retries to establish a network connection after a network error has * occurred or the coverage of the network was lost. The amount of retries * depends on MAX_NUMBER_RETRIES. * </p> * <p> * A new retry is carried out each time an exception is thrown until the * limit of retries has been reached. * </p> * * @param numberOfRetries The amount of retries carried out until the * connection is given up. */ synchronized private void haltAndRetryConnection(int numberOfRetries) { HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "\n \n \nRETRYING CONNECTION: " + numberOfRetries + " tries."); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTING); if (!mConnectionShouldBeRunning) { // connection was killed by service // agent HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "Connection " + "was disconnected by Service Agent. Stopping retries!"); return; } stopConnection(); // stop to kill anything that might cause further IOEs // if we retried enough, we just return and end further retries if (numberOfRetries > MAX_NUMBER_RETRIES) { invalidateRequests(); mDidCriticalErrorOccur = true; mLastErrorTimestamp = System.currentTimeMillis(); /* * FlurryAgent.onError("ERROR_TCP_FAILED", * "Failed reconnecting for the 3rd time. Stopping!" + * mLastErrorTimestamp, "TcpConnectionThread"); */ synchronized (this) { notify(); // notify as we might be currently blocked on a // request's wait() } ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_DISCONNECTED); return; } try { // sleep a while to let the connection recover int sleepVal = (ERROR_RETRY_INTERVAL / 2) * numberOfRetries; Thread.sleep(sleepVal); } catch (InterruptedException ie) { } if (!mConnectionShouldBeRunning) { return; } try { reconnectSocket(); // TODO switch this block with the test connection block below // once the RPG implements this correctly. HeartbeatSenderThread hbSender = new HeartbeatSenderThread(this, mService, mSocket); hbSender.setOutputStream(mOs); hbSender.sendHeartbeat(); hbSender = null; mDidCriticalErrorOccur = false; if (!mConnectionShouldBeRunning) { return; } startHelperThreads(); // restart our connections // TODO add this once the BE supports it! /* * ConnectionTester connTester = new ConnectionTester(mIs, mOs); if * (connTester.runTest()) { mDidCriticalErrorOccur = false; * startHelperThreads(); // restart our connections Map<String, * String> map = new HashMap<String, String>(); * map.put("Last Error Timestamp", "" + mLastErrorTimestamp); * map.put("Last Error Retry Timestamp", "" + mLastErrorRetryTime); * map.put("Current Timestamp", "" + System.currentTimeMillis()); * map.put("Number of Retries", "" + numberOfRetries); * FlurryAgent.onEvent("RecoveredFromTCPError", map); } else { * HttpConnectionThread * .log("TcpConnectionThread.haltAndRetryConnection()", * "Could not receive TCP test response. need to retry..."); * haltAndRetryConnection(++numberOfRetries); } */ Map<String, String> map = new HashMap<String, String>(); map.put("Last Error Timestamp", "" + mLastErrorTimestamp); map.put("Last Error Retry Timestamp", "" + mLastErrorRetryTime); map.put("Current Timestamp", "" + System.currentTimeMillis()); map.put("Number of Retries", "" + numberOfRetries); // FlurryAgent.onEvent("RecoveredFromTCPError", map); ConnectionManager.getInstance().onConnectionStateChanged( ITcpConnectionListener.STATE_CONNECTED); } catch (IOException ioe) { HttpConnectionThread.logI("TcpConnectionThread.haltAndRetryConnection()", "Failed sending heartbeat. Need to retry..."); haltAndRetryConnection(++numberOfRetries); } catch (Exception e) { HttpConnectionThread.logE("TcpConnectionThread.haltAndRetryConnection()", "An unknown error occured: ", e); haltAndRetryConnection(++numberOfRetries); } } /** * Invalidates all the requests so that the engines can either resend or * post an error message for the user. */ private void invalidateRequests() { QueueManager reqQueue = QueueManager.getInstance(); if (null != reqQueue) { TimeOutWatcher timeoutWatcher = reqQueue.getRequestTimeoutWatcher(); if (null != timeoutWatcher) { timeoutWatcher.invalidateAllRequests(); } } } @Override public void startThread() { if ((null != mThread) && (mThread.isAlive()) && (mConnectionShouldBeRunning)) { HttpConnectionThread.logI("TcpConnectionThread.startThread()", "No need to start Thread. " + "Already there. Returning"); return; } mConnectionShouldBeRunning = true; mThread = new Thread(this); mThread.start(); } @Override public void stopThread() { HttpConnectionThread.logI("TcpConnectionThread.stopThread()", "Stop Thread was called!"); mConnectionShouldBeRunning = false; stopConnection(); synchronized (this) { notify(); } } /** * Starts the helper threads in order to be able to read responses and send * heartbeats and passes them the needed input and output streams. */ private void startHelperThreads() { HttpConnectionThread.logI("TcpConnectionThread.startHelperThreads()", "STARTING HELPER THREADS."); if (null == mHeartbeatSender) { mHeartbeatSender = new HeartbeatSenderThread(this, mService, mSocket); HeartbeatSenderThread.mCurrentThread = mHeartbeatSender; } else { HttpConnectionThread.logE("TcpConnectionThread.startHelperThreads()", "HeartbeatSenderThread was not null!", null); } if (null == mResponseReader) { mResponseReader = new ResponseReaderThread(this, mDecoder, mSocket); ResponseReaderThread.mCurrentThread = mResponseReader; } else { HttpConnectionThread.logE("TcpConnectionThread.startHelperThreads()", "ResponseReaderThread was not null!", null); } mHeartbeatSender.setOutputStream(mOs); mResponseReader.setInputStream(mBufferedInputStream); if (!mHeartbeatSender.getIsActive()) { mHeartbeatSender.startConnection(); mResponseReader.startConnection(); } } /** * Stops the helper threads and closes the input and output streams. As the * response reader is at this point in time probably in a blocking * read()-state an IOException will need to be caught. */ private void stopHelperThreads() { HttpConnectionThread.logI("TcpConnectionThread.stopHelperThreads()", "STOPPING HELPER THREADS: " + ((null != mHeartbeatSender) ? mHeartbeatSender.getIsActive() : false)); if (null != mResponseReader) { mResponseReader.stopConnection(); } if (null != mHeartbeatSender) { mHeartbeatSender.stopConnection(); } mOs = null; mBufferedInputStream = null; mHeartbeatSender = null; mResponseReader = null; } /** * Stops the connection and its underlying socket implementation. Keeps the * thread running to allow further logins from the user. */ synchronized private void stopConnection() { HttpConnectionThread.logI("TcpConnectionThread.stopConnection()", "Closing socket..."); stopHelperThreads(); if (null != mSocket) { try { mSocket.close(); } catch (IOException ioe) { HttpConnectionThread.logE("TcpConnectionThread.stopConnection()", "Could not close Socket!", ioe); } finally { mSocket = null; } } QueueManager.getInstance().clearAllRequests(); } @Override public void notifyOfItemInRequestQueue() { HttpConnectionThread.logV("TcpConnectionThread.notifyOfItemInRequestQueue()", "NEW REQUEST AVAILABLE!"); synchronized (this) { notify(); } } @Override public boolean getIsConnected() { return mConnectionShouldBeRunning; } @Override public boolean getIsRpgConnectionActive() { if ((null != mHeartbeatSender) && (mHeartbeatSender.getIsActive())) { return true; } return false; } @Override public void onLoginStateChanged(boolean isLoggedIn) { } }
360/360-Engine-for-Android
236670caae9e5a1ecab177ac15d448b6842c5024
PAND-1796: Fixed the ContactChange Comparator class that would cause a crash
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java index 95af541..f11b205 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java @@ -95,854 +95,854 @@ public class NativeImporter { /** * Internal state representing the task to perform: iterates through the * list of ids to find differences (i.e. added contact, modified contact, * deleted contact). */ private final static int STATE_ITERATE_THROUGH_IDS = 1; /** * Internal state representing the task to perform: process the list of * deleted contacts (i.e. delete the contacts from the people database). * TODO: remove this state */ private final static int STATE_PROCESS_DELETED = 2; /** * Internal state representing the task to perform: final state, nothing * else to perform. */ private final static int STATE_DONE = 3; /** * The current state. */ private int mState = STATE_GET_IDS_LISTS; /** * The list of native ids from the native side. */ private long[] mNativeContactsIds; /** * The list of native ids from the people side. */ private long[] mPeopleNativeContactsIds; /** * The total count of ids to process (native database + people database). */ private int mTotalIds = 0; /** * The current count of processed ids. */ private int mProcessedIds = 0; /** * The index of the current native id. * * @see #mNativeContactsIds */ private int mCurrentNativeId = 0; /** * The index in the current people id. * * @see #mPeopleNativeContactsIds */ private int mCurrentPeopleId = 0; /** * The index of the current deleted people id. * * @see #mDeletedIds */ private int mCurrentDeletedId = 0; /** * Array to store the people ids of contacts to delete. */ private DynamicArrayLong mDeletedIds = new DynamicArrayLong(10); /** * The result status. */ private int mResult = RESULT_UNDEFINED; /** * Instance of a ContactChange comparator. */ private NCCComparator mNCCC = new NCCComparator(); /** * The array of accounts from where to import the native contacts. Note: if * null, will import from the platform default account. */ private Account[] mAccounts = null; /** * Boolean that tracks if the first time Import for 2.X is ongoing. */ private boolean mIsFirstImportOn2X = false; /** * Constructor. * * @param pca handler to the People contacts Api * @param nca handler to the Native contacts Api * @param firstTimeImport true if we import from native for the first time, * false if not */ public NativeImporter(PeopleContactsApi pca, NativeContactsApi nca, boolean firstTimeImport) { mPeopleContactsApi = pca; mNativeContactsApi = nca; initAccounts(firstTimeImport); } /** * Sets the accounts used to import the native contacs. */ private void initAccounts(boolean firstTimeImport) { /** * In case of Android 2.X, the accounts used are different depending if * it's first time sync or not. On Android 1.X, we can just ignore the * accounts logic as not supported by the platform. At first time sync, * we need to import the native contacts from all the Google accounts. * These native contacts are then stored in the 360 People account and * native changes will be only detected from the 360 People account. */ if (VersionUtils.is2XPlatform()) { // account to import from: 360 account if created, all the google // accounts otherwise if (firstTimeImport) { ArrayList<Account> accountList = new ArrayList<Account>(); Account googleAccounts[] = mNativeContactsApi.getAccountsByType(NativeContactsApi.GOOGLE_ACCOUNT_TYPE); if (googleAccounts!=null ){ for (Account account : googleAccounts) { accountList.add(account); } } Account phoneAccounts[] = mNativeContactsApi.getAccountsByType(NativeContactsApi.PHONE_ACCOUNT_TYPE); if (phoneAccounts!=null){ for (Account account : phoneAccounts) { accountList.add(account); } } mAccounts = accountList.toArray(new Account[0]); } else { mAccounts = mNativeContactsApi .getAccountsByType(NativeContactsApi.PEOPLE_ACCOUNT_TYPE); } if (firstTimeImport) mIsFirstImportOn2X = true; } } /** * Sets the internal state to DONE with the provided result status. * * @param result the result status to set */ private void complete(int result) { mState = STATE_DONE; mResult = result; } /** * Tick method to call each time there is time for processing the native * contacts import. Note: the method will block for some time to process a * certain amount of contact then will return. It will have to be called * until it returns true meaning that the import is over. * * @return true when the import task is finished, false if not */ public boolean tick() { switch (mState) { case STATE_GET_IDS_LISTS: getIdsLists(); break; case STATE_ITERATE_THROUGH_IDS: iterateThroughNativeIds(); break; case STATE_PROCESS_DELETED: processDeleted(); break; } return isDone(); } /** * Returns the import state. * * @return true if the import is finished, false if not */ public boolean isDone() { return mState == STATE_DONE; } /** * Gets the import result. * * @see #RESULT_OK * @see #RESULT_ERROR * @see #RESULT_UNDEFINED * @return the import result */ public int getResult() { return mResult; } /** * Gets the current position in the list of ids. This can be used to track * the current progress. * * @see #getCount() * @return the last processed id position in the list of ids */ public int getPosition() { return mProcessedIds; } /** * Gets the total number of ids to process. * * @return the number of ids to process */ public int getCount() { return mTotalIds; } /** * Gets the list of native and people contacts ids. */ private void getIdsLists() { LogUtils.logD("NativeImporter.getIdsLists()"); // Get the list of native ids for the contacts if (mAccounts == null || 0 == mAccounts.length) { // default account LogUtils.logD("NativeImporter.getIdsLists() - using default account"); mNativeContactsIds = mNativeContactsApi.getContactIds(null); } else if (mAccounts.length == 1) { // one account LogUtils.logD("NativeImporter.getIdsLists() - one account found: " + mAccounts[0]); mNativeContactsIds = mNativeContactsApi.getContactIds(mAccounts[0]); } else { // we need to merge the ids from different accounts and sort them final DynamicArrayLong allIds = new DynamicArrayLong(); LogUtils.logD("NativeImporter.getIdsLists() - more than one account found."); for (int i = 0; i < mAccounts.length; i++) { LogUtils.logD("NativeImporter.getIdsLists() - account=" + mAccounts[i]); final long[] ids = mNativeContactsApi.getContactIds(mAccounts[i]); if (ids != null) { allIds.add(ids); } } mNativeContactsIds = allIds.toArray(); // sort the ids // TODO: as the arrays to merge are sorted, consider merging while // keeping the sorting // which is faster than sorting them afterwards if (mNativeContactsIds != null) { Arrays.sort(mNativeContactsIds); } } // check if we have some work to do if (mNativeContactsIds == null) { complete(RESULT_OK); return; } // Get a list of native ids for the contacts we have in the People // database mPeopleNativeContactsIds = mPeopleContactsApi.getNativeContactsIds(); mTotalIds = mNativeContactsIds.length; if (mPeopleNativeContactsIds != null) { mTotalIds += mPeopleNativeContactsIds.length; } mState = STATE_ITERATE_THROUGH_IDS; } /** * Iterates through the list of native and People ids to detect changes. */ private void iterateThroughNativeIds() { LogUtils.logD("NativeImporter.iterateThroughNativeIds()"); final int limit = Math.min(mNativeContactsIds.length, mCurrentNativeId + MAX_CONTACTS_OPERATION_COUNT); // TODO: remove the deleted state / queuing to deleted ids array and // loop with while (mProcessedIds < limit) while (mCurrentNativeId < limit) { if (mPeopleNativeContactsIds == null) { // no native contacts on people side, just add it LogUtils.logD("NativeImporter.iterateThroughNativeIds(): found a new contact"); addNewContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; } else { // both ids lists are ordered by ascending ids so // every people ids that are before the current native ids // are simply deleted contacts while ((mCurrentPeopleId < mPeopleNativeContactsIds.length) && (mPeopleNativeContactsIds[mCurrentPeopleId] < mNativeContactsIds[mCurrentNativeId])) { LogUtils .logD("NativeImporter.iterateThroughNativeIds(): found a contact to delete"); mDeletedIds.add(mPeopleNativeContactsIds[mCurrentPeopleId++]); } if (mCurrentPeopleId == mPeopleNativeContactsIds.length || mPeopleNativeContactsIds[mCurrentPeopleId] > mNativeContactsIds[mCurrentNativeId]) { // has to be a new contact LogUtils.logD("NativeImporter.iterateThroughNativeIds(): found a new contact"); addNewContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; } else { // has to be an existing contact or one that will be deleted LogUtils .logD("NativeImporter.iterateThroughNativeIds(): check existing contact"); checkExistingContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; mCurrentPeopleId++; } } mCurrentNativeId++; } // check if we are done with ids list from native if (mCurrentNativeId == mNativeContactsIds.length) { // we've gone through the native list, any remaining ids from the // people list are deleted ones if (mPeopleNativeContactsIds != null) { while (mCurrentPeopleId < mPeopleNativeContactsIds.length) { LogUtils .logD("NativeImporter.iterateThroughNativeIds(): found a contact to delete"); mDeletedIds.add(mPeopleNativeContactsIds[mCurrentPeopleId++]); } } if (mDeletedIds.size() != 0) { // Some deleted contacts to handle mState = STATE_PROCESS_DELETED; } else { // Nothing else to do complete(RESULT_OK); } } } /** * Deletes the contacts that were added the deleted array. */ private void processDeleted() { LogUtils.logD("NativeImporter.processDeleted()"); final int limit = Math.min(mDeletedIds.size(), mCurrentDeletedId + MAX_CONTACTS_OPERATION_COUNT); while (mCurrentDeletedId < limit) { // we now delete the contacts on people client side // on the 2.X platform, the contact deletion has to be synced back // to native once completed because the // contact is still there on native, just marked as deleted and // waiting for its explicit removal mPeopleContactsApi.deleteNativeContact(mDeletedIds.get(mCurrentDeletedId++), VersionUtils.is2XPlatform()); mProcessedIds++; } if (mCurrentDeletedId == mDeletedIds.size()) { complete(RESULT_OK); } } /** * Adds a new contact to the people database. */ private void addNewContact(long nativeId) { // get the contact data final ContactChange[] contactChanges = mNativeContactsApi.getContact(nativeId); if (contactChanges != null) { if (mIsFirstImportOn2X) { // Override the nativeContactId with an invalid id if we are on // 2.X // and we are doing a first time import because the native id // does not correspond // to the id from the 360 People account where we will export. removeNativeIds(contactChanges); } else { // Force a nativeDetailId to details that have none so that the // comparison // later can be made (see computeDelta method). forceNabDetailId(contactChanges); } // add the contact to the People database if (!mPeopleContactsApi.addNativeContact(contactChanges)) { // TODO: Handle the error case !!! Well how should we handle it: // fail for all remaining contacts or skip the failing contact? LogUtils .logE("NativeImporter.addNewContact() - failed to import native contact id=" + nativeId); } } } /** * Check changes between an existing contact on both native and people * database. * * @param nativeId the native id of the contact to check */ private void checkExistingContact(long nativeId) { // get the native version of that contact final ContactChange[] nativeContact = mNativeContactsApi.getContact(nativeId); // get the people version of that contact final ContactChange[] peopleContact = mPeopleContactsApi.getContact((int)nativeId); if (peopleContact == null) { // we shouldn't be in that situation but nothing to do about it // this means that there were some changes in the meantime between // getting the ids list and now return; } else if (nativeContact == null) { LogUtils .logD("NativeImporter.checkExistingContact(): found a contact marked as deleted"); // this is a 2.X specific case meaning that the contact is marked as // deleted on native side // and waiting for the "syncAdapter" to perform a real delete mDeletedIds.add(nativeId); } else { // general case, find the delta final ContactChange[] delta = computeDelta(peopleContact, nativeContact); if (delta != null) { // update CAB with delta changes mPeopleContactsApi.updateNativeContact(delta); } } } /** * Native ContactChange Comparator class. This class compares ContactChange * and tells which one is greater depending on the key and then the native * detail id. */ private static class NCCComparator implements Comparator<ContactChange> { @Override public int compare(ContactChange change1, ContactChange change2) { // an integer < 0 if object1 is less than object2, 0 if they are // equal, and > 0 if object1 is greater than object2. final int key1 = change1.getKey(); final int key2 = change2.getKey(); if (key1 < key2) { return -1; } else if (key1 > key2) { return 1; } else { // the keys are identical, check the native ids final long id1 = change1.getNabDetailId(); final long id2 = change2.getNabDetailId(); if (id1 < id2) { return -1; - } else if (key1 > key2) { + } else if (id1 > id2) { return 1; } else { return 0; } } } } /** * Sorts the provided array of ContactChange by key and native id. Note: the * method will rearrange the provided array. * * @param changes the ContactChange array to sort */ private void sortContactChanges(ContactChange[] changes) { if ((changes != null) && (changes.length > 1)) { Arrays.sort(changes, mNCCC); } } /** * Computes the difference between the provided arrays of ContactChange. The * delta are the changes to apply to the master ContactChange array to make * it similar to the new changes ContactChange array. (i.e. delete details, * add details or modify details) NOTE: to help the GC, some provided * ContactChange may be modified and returned by the method instead of * creating new ones. * * @param masterChanges the master array of ContactChange (i.e. the original * one) * @param newChanges the new ContactChange array (i.e. contains the new * version of a contact) * @return null if there are no changes or the contact is being deleted, an * array for ContactChange to apply to the master contact if * differences where found */ private ContactChange[] computeDelta(ContactChange[] masterChanges, ContactChange[] newChanges) { LogUtils.logD("NativeImporter.computeDelta()"); // set the native contact id to details that don't have a native detail // id for the comparison as // this is also done on people database side forceNabDetailId(newChanges); // sort the changes by key then native detail id sortContactChanges(masterChanges); sortContactChanges(newChanges); // if the master contact is being deleted, ignore new changes if ((masterChanges[0].getType() & ContactChange.TYPE_DELETE_CONTACT) == ContactChange.TYPE_DELETE_CONTACT) { return null; } // details comparison, skip deleted master details final ContactChange[] deltaChanges = new ContactChange[masterChanges.length + newChanges.length]; int deltaIndex = 0; int masterIndex = 0; int newIndex = 0; while (newIndex < newChanges.length) { while ((masterIndex < masterChanges.length) && (mNCCC.compare(masterChanges[masterIndex], newChanges[newIndex]) < 0)) { final ContactChange masterChange = masterChanges[masterIndex]; if ((masterChange.getType() & ContactChange.TYPE_DELETE_DETAIL) != ContactChange.TYPE_DELETE_DETAIL && (masterChange.getNabDetailId() != ContactChange.INVALID_ID) && (isContactChangeKeySupported(masterChange))) { // this detail does not exist anymore, is not being deleted // and was synced to native // check if it can be deleted (or has to be updated) setDetailForDeleteOrUpdate(masterChanges, masterIndex); deltaChanges[deltaIndex++] = masterChanges[masterIndex]; } masterIndex++; } if ((masterIndex < masterChanges.length) && (mNCCC.compare(newChanges[newIndex], masterChanges[masterIndex]) == 0)) { // similar key and id, check for differences at value level and // flags final ContactChange masterDetail = masterChanges[masterIndex]; final ContactChange newDetail = newChanges[newIndex]; boolean different = false; if (masterDetail.getFlags() != newDetail.getFlags()) { different = true; } if (!areContactChangeValuesEqualsPlusFix(masterChanges, masterIndex, newChanges, newIndex)) { different = true; } if (different) { // found a detail to update LogUtils.logD("NativeImporter.computeDelta() - found a detail to update"); newDetail.setType(ContactChange.TYPE_UPDATE_DETAIL); newDetail.setInternalContactId(masterDetail.getInternalContactId()); newDetail.setInternalDetailId(masterDetail.getInternalDetailId()); deltaChanges[deltaIndex++] = newDetail; } masterIndex++; } else { LogUtils.logD("NativeImporter.computeDelta() - found a detail to add"); // this is a new detail newChanges[newIndex].setType(ContactChange.TYPE_ADD_DETAIL); newChanges[newIndex].setInternalContactId(masterChanges[0].getInternalContactId()); deltaChanges[deltaIndex++] = newChanges[newIndex]; } newIndex++; } while (masterIndex < masterChanges.length) { final ContactChange masterChange = masterChanges[masterIndex]; if ((masterChange.getType() & ContactChange.TYPE_DELETE_DETAIL) != ContactChange.TYPE_DELETE_DETAIL && (masterChange.getNabDetailId() != ContactChange.INVALID_ID) && (isContactChangeKeySupported(masterChange))) { // this detail does not exist anymore, is not being deleted and // was synced to native // check if it can be deleted (or has to be updated) setDetailForDeleteOrUpdate(masterChanges, masterIndex); deltaChanges[deltaIndex++] = masterChanges[masterIndex]; } masterIndex++; } if (deltaIndex == 0) { // the contact has not changed return null; } else if (deltaChanges.length == deltaIndex) { // give the detail changes return deltaChanges; } else { // give the detail changes but need to trim final ContactChange[] trim = new ContactChange[deltaIndex]; System.arraycopy(deltaChanges, 0, trim, 0, deltaIndex); return trim; } } /** * Removes the native ids in case of a first time import on the Android 2.X * platform. * * @param contact the contact to clear from native ids */ private void removeNativeIds(ContactChange[] contact) { if (contact != null) { final int count = contact.length; for (int i = 0; i < count; i++) { final ContactChange change = contact[i]; change.setNabContactId(ContactChange.INVALID_ID); change.setNabDetailId(ContactChange.INVALID_ID); } } } /** * Forces a native detail id onto a detail that does not have one by setting * it to be the native contact id. * * @param contact the contact to fix */ private void forceNabDetailId(ContactChange[] contact) { if (contact != null && contact.length > 0) { final long nativeContactId = contact[0].getNabContactId(); final int count = contact.length; for (int i = 0; i < count; i++) { final ContactChange change = contact[i]; if (change.getNabDetailId() == ContactChange.INVALID_ID) { change.setNabDetailId(nativeContactId); } } } } /* * Below this point, all the defined methods where added to support the * specific case of KEY_VCARD_ORG on Android 1.X platform. KEY_VCARD_ORG is * defined as followed: "company;department1;department2;...;departmentX" It * is a special case because this VCard key on its own is not fully * supported on the Android 1.X platform: only "company" information is. */ /** * Tells whether or not a master change is equal to a new change and * performs some modifications on the provided new change in the specific * case of KEY_VCARD_ORG on Android 1.X. * * @param masterChanges the array of master changes * @param masterIndex the index of the change within the array of master * changes * @param newChanges the array of new changes * @param newIndex the index of the change within the array of new changes * @return true if the changes are equals, false otherwise */ private boolean areContactChangeValuesEqualsPlusFix(ContactChange[] masterChanges, int masterIndex, ContactChange[] newChanges, int newIndex) { final ContactChange masterChange = masterChanges[masterIndex]; final ContactChange newChange = newChanges[newIndex]; if (VersionUtils.is2XPlatform() || masterChange.getKey() != ContactChange.KEY_VCARD_ORG) { // general case return TextUtils.equals(masterChange.getValue(), newChange.getValue()); } else { // this is a special case of Android 1.X where we have to parse the // value // in case of Organization key final String peopleCompValue = VCardHelper.parseCompanyFromOrganization(masterChange .getValue()); final String nativeCompValue = VCardHelper.parseCompanyFromOrganization(newChange .getValue()); // on 1.X, we only need to compare the company name as // department is not supported by the platform final boolean areEquals = TextUtils.equals(peopleCompValue, nativeCompValue); if (!areEquals) { // there is a difference so master change will be updated // we need to preserve the master department values if any final String masterDepartments = VCardHelper .splitDepartmentsFromOrganization(masterChange.getValue()); final ContactChange fixedNewChange = newChange.copyWithNewValue(nativeCompValue + masterDepartments); newChanges[newIndex] = fixedNewChange; } return areEquals; } } /** * Sets a detail as to be deleted or updated. Note: in the general case, the * detail has to be deleted but in the specific situation of KEY_VCARD_ORG * and Android 1.X, it may have to be updated instead * * @param contactChanges the array of ContactChange * @param index the index of the ContactChange to set in the array of * ContactChange */ private void setDetailForDeleteOrUpdate(ContactChange[] contactChanges, int index) { final ContactChange contactChange = contactChanges[index]; if (VersionUtils.is2XPlatform() || contactChange.getKey() != ContactChange.KEY_VCARD_ORG) { // general case, just set the details as deleted contactChange.setType(ContactChange.TYPE_DELETE_DETAIL); LogUtils .logD("NativeImporter.checkDetailForDeleteOrUpdate() - found a detail to delete"); } else { // this is a special case of Android 1.X // we have to set this change to an update if the change // contains departments final String masterDepartments = VCardHelper .splitDepartmentsFromOrganization(contactChange.getValue()); if (!VCardHelper.isEmptyVCardValue(masterDepartments)) { // delete the company name and keep the departments contactChange.setType(ContactChange.TYPE_UPDATE_DETAIL); contactChanges[index] = contactChange.copyWithNewValue(masterDepartments); LogUtils .logD("NativeImporter.checkDetailForDeleteOrUpdate() - found a detail to update"); } else { contactChange.setType(ContactChange.TYPE_DELETE_DETAIL); LogUtils .logD("NativeImporter.checkDetailForDeleteOrUpdate() - found a detail to delete"); } } } /** * Determines whether or not a ContactChange key is supported on native * side. Note: it also handle the non generic case of KEY_VCARD_ORG on * Android 1.X * * @param change the ContactChange to check * @return true if supported, false if not */ private boolean isContactChangeKeySupported(ContactChange change) { final boolean isSupported = mNativeContactsApi.isKeySupported(change.getKey()); if (VersionUtils.is2XPlatform() || change.getKey() != ContactChange.KEY_VCARD_ORG) { return isSupported; } else if (isSupported) { // KEY_VCARD_ORG has the following value: // "company;department1;department2..." // in case of KEY_VCARD_ORG on Android 1.X, we have to check the // support of the key // at the company level of the VCard value because the departments // are not supported // so if there is only the department, we have to return false // instead of true. final String changeCompValue = VCardHelper.parseCompanyFromOrganization(change .getValue()); if (!VCardHelper.isEmptyVCardValue(changeCompValue)) { return true; } } return false; } }
360/360-Engine-for-Android
1376fd3bf9ed5cbe82a6155d99e2c53a311026d3
fixes a nullpointer exception. no review needed
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 057b3e5..8484612 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,764 +1,769 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.identities; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import android.os.Bundle; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Identities; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; /** * Engine responsible for handling retrieval and validation of Identities (e.g. * 3rd party/web accounts). The Identities engine can fetch a list of available * accounts, and set required capabilities and validate credentials for * specified accounts. */ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { /** * States for IdentitiesEngine. States are based on the requests that the * engine needs to handle. */ private enum State { IDLE, FETCHING_IDENTITIES, VALIDATING_IDENTITY_CREDENTIALS, SETTING_IDENTITY_STATUS, GETTING_MY_IDENTITIES, GETTING_MY_CHATABLE_IDENTITIES } /** * Mutex for thread synchronisation */ private final Object mMutex = new Object(); /** * Container class for Identity Capability Status request. Consists of a * network, identity id and a filter containing the required capabilities. */ private static class IdentityStatusRequest { private String mNetwork; private String mIdentityId; private String mIdentityStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setIdentityStatus(String status) { mIdentityStatus = status; } } /** * Container class encapsulating an Identity validation request containing: * dry-run flag, network, user-name, password, set of required capabilities. */ private static class IdentityValidateCredentialsRequest { /** Performs a dry run if true. */ private boolean mDryRun; /** Network to sign into. */ private String mNetwork; /** Username to sign into identity with. */ private String mUserName; /** Password to sign into identity with. */ private String mPassword; private Map<String, Boolean> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private ArrayList<Identity> mMyIdentityList; /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; mMyIdentityList = new ArrayList<Identity>(); mAvailableIdentityList = new ArrayList<Identity>(); mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { if ((mAvailableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return mMyIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chatableIdentities = new ArrayList<Identity>(); int identityListSize = mMyIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = mMyIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue == true)) { chatableIdentities.add(identity); break; } } } // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chatableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chatableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } // invalidate 'chat-able' identities cache if (mMyChatableIdentityList != null) { mMyChatableIdentityList.clear(); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(DecodedResponse resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); + + if ((null == resp) || (null == resp.mDataTypes)) { + LogUtils.logWithName("IdentityEngine.processCommsResponse()", "Response objects or its contents were null. Aborting..."); + return; + } // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); } } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; idBundle = mAvailableIdentityList; } else { requestKey = KEY_MY_IDS; idBundle = mMyIdentityList; } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } /** * * Retrieves the filter for the getAvailableIdentities and getMyIdentities * calls. * * @return The identities filter in form of a bundle. * */ private Bundle getIdentitiesFilter() { Bundle b = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); l.add(IdentityCapability.CapabilityID.get_own_status.name()); b.putStringArrayList("capability", l); return b; } @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } /** * Generate Map containing String capability filters for m supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, List<String>> prepareStringFilter(Bundle filter) { Map<String, List<String>> returnFilter = null; if (filter != null && filter.keySet().size() > 0) { returnFilter = new Hashtable<String, List<String>>(); for (String key : filter.keySet()) { returnFilter.put(key, filter.getStringArrayList(key)); } } else { returnFilter = null; } return returnFilter; } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ /** {@inheritDoc} */ @Override public final void onReset() { if (null != mMyIdentityList) { mMyIdentityList.clear(); } super.onReset(); } }
360/360-Engine-for-Android
0b331816c38a4f9f7e50091c11a06c9f46b22c27
Fixed PAND-1807. Not receiving any push messages.
diff --git a/src/com/vodafone360/people/service/transport/DecoderThread.java b/src/com/vodafone360/people/service/transport/DecoderThread.java index 2e2dfb5..ee1ee43 100644 --- a/src/com/vodafone360/people/service/transport/DecoderThread.java +++ b/src/com/vodafone360/people/service/transport/DecoderThread.java @@ -1,330 +1,333 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.transport; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.service.io.ResponseQueue; import com.vodafone360.people.service.io.Request.Type; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.rpg.RpgHeader; import com.vodafone360.people.service.io.rpg.RpgHelper; import com.vodafone360.people.service.io.rpg.RpgMessage; import com.vodafone360.people.service.io.rpg.RpgMessageTypes; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.hessian.HessianDecoder; import com.vodafone360.people.utils.LogUtils; /** * Responsible for decoding 'raw' Hessian response data. Data is decoded into * specific data types and added to the response queue. The Response queue * stores request id (except for unsolicited Push msgs) and a source/destination * engine to allow appropriate routing. */ public class DecoderThread implements Runnable { private static final String THREAD_NAME = "DecoderThread"; private static final long THREAD_SLEEP_TIME = 300; // ms private volatile boolean mRunning = false; private final List<RawResponse> mResponses = new ArrayList<RawResponse>(); private ResponseQueue mRespQueue = null; /** * The hessian decoder is here declared as member and will be reused instead * of making new instances on every need */ private HessianDecoder mHessianDecoder = new HessianDecoder(); /** * Container class for raw undecoded response data. Holds a request id * (obtained from outgoing request or 0 for unsolicited Push message) and * whether data is GZip compressed or unsolicited. */ public static class RawResponse { public int mReqId; public byte[] mData; public boolean mIsCompressed = false; public boolean mIsPushMessage = false; public RawResponse(int reqId, byte[] data, boolean isCompressed, boolean isPushMessage) { mReqId = reqId; mData = data; mIsCompressed = isCompressed; mIsPushMessage = isPushMessage; } } /** * Start decoder thread */ protected void startThread() { mRunning = true; Thread decoderThread = new Thread(this); decoderThread.setName(THREAD_NAME); decoderThread.start(); } /** * Stop decoder thread */ protected synchronized void stopThread() { this.mRunning = false; this.notify(); } public DecoderThread() { mRespQueue = ResponseQueue.getInstance(); } /** * Add raw response to decoding queue * * @param resp raw data */ public void addToDecode(RawResponse resp) { synchronized (this) { mResponses.add(resp); this.notify(); } } public synchronized boolean getIsRunning() { return mRunning; } /** * Thread's run function If the decoding queue contains any entries we * decode the first response and add the decoded data to the response queue. * If the decode queue is empty, the thread will become inactive. It is * resumed when a raw data entry is added to the decode queue. */ public void run() { LogUtils.logI("DecoderThread.run() [Start thread]"); while (mRunning) { EngineId engineId = EngineId.UNDEFINED; Type type = Type.PUSH_MSG; int reqId = -1; try { if (mResponses.size() > 0) { LogUtils.logI("DecoderThread.run() Decoding [" + mResponses.size() + "x] responses"); // Decode first entry in queue RawResponse decode = mResponses.get(0); reqId = decode.mReqId; if (!decode.mIsPushMessage) { // Attempt to get type from request Request request = QueueManager.getInstance().getRequest(reqId); if (request != null) { type = request.mType; engineId = request.mEngineId; } else { type = Type.COMMON; } } DecodedResponse response = mHessianDecoder.decodeHessianByteArray(reqId, decode.mData, type, decode.mIsCompressed, engineId); // if we have a push message let's try to find out to which engine it should be routed if ((response.getResponseType() == DecodedResponse.ResponseType.PUSH_MESSAGE.ordinal()) && (response.mDataTypes.get(0) != null)) { - engineId = ((PushEvent) response.mDataTypes.get(0)).mEngineId; + // for push messages we have to override the engine id as it is parsed inside the hessian decoder + engineId = ((PushEvent) response.mDataTypes.get(0)).mEngineId; + response.mSource = engineId; + // TODO mSource should get the engineId inside the decoder once types for mDataTypes is out. see PAND-1805. } // This is usually the case for SYSTEM_NOTIFICATION messages // or where the server is returning an error for requests // sent by the engines. IN this case, if there is no special // handling for the engine, we get the engine ID based on // the request ID. if (type == Type.PUSH_MSG && reqId != 0 && engineId == EngineId.UNDEFINED) { Request request = QueueManager.getInstance().getRequest(reqId); if (request != null) { engineId = request.mEngineId; } } if (engineId == EngineId.UNDEFINED) { LogUtils.logE("DecoderThread.run() Unknown engine for message with type[" + type.name() + "]"); // TODO: Throw Exception for undefined messages, as // otherwise they might always remain on the Queue? } // Add data to response queue HttpConnectionThread.logV("DecoderThread.run()", "Add message[" + decode.mReqId + "] to ResponseQueue for engine[" + engineId + "] with data [" + response.mDataTypes + "]"); mRespQueue.addToResponseQueue(response); // Remove item from our list of responses. mResponses.remove(0); // be nice to the other threads Thread.sleep(THREAD_SLEEP_TIME); } else { synchronized (this) { // No waiting responses, so the thread should sleep. try { LogUtils.logV("DecoderThread.run() [Waiting for more responses]"); wait(); } catch (InterruptedException ie) { // Do nothing } } } } catch (Throwable t) { /* * Keep thread running regardless of error. When something goes * wrong we should remove response from queue and report error * back to engine. */ if (mResponses.size() > 0) { mResponses.remove(0); } if (type != Type.PUSH_MSG && engineId != EngineId.UNDEFINED) { List<BaseDataType> list = new ArrayList<BaseDataType>(); // this error type was chosen to make engines remove request // or retry // we may consider using other error code later ServerError error = new ServerError(ServerError.ErrorType.INTERNALERROR); error.errorDescription = "Decoder thread was unable to decode server message"; list.add(error); mRespQueue.addToResponseQueue(new DecodedResponse(reqId, list, engineId, DecodedResponse.ResponseType.SERVER_ERROR.ordinal())); } LogUtils.logE("DecoderThread.run() Throwable on reqId[" + reqId + "]", t); } } LogUtils.logI("DecoderThread.run() [End thread]"); } /** * <p> * Looks at the response and adds it to the necessary decoder. * </p> * TODO: this method should be worked on. The decoder should take care of * deciding which methods are decoded in which way. * * @param response The server response to decode. * @throws Exception Thrown if the returned status line was null or if the * response was null. */ public void handleResponse(byte[] response) throws Exception { InputStream is = null; if (response != null) { try { is = new ByteArrayInputStream(response); final List<RpgMessage> mRpgMessages = new ArrayList<RpgMessage>(); // Get array of RPG messages // throws IO Exception, we pass it to the calling method RpgHelper.splitRpgResponse(is, mRpgMessages); byte[] body = null; RpgHeader rpgHeader = null; // Process each header for (RpgMessage mRpgMessage : mRpgMessages) { body = mRpgMessage.body(); rpgHeader = mRpgMessage.header(); // Determine RPG mssageType (internal response, push // etc) final int mMessageType = rpgHeader.reqType(); HttpConnectionThread.logD("DecoderThread.handleResponse()", "Non-RPG_POLL_MESSAGE"); // Reset blank header counter final boolean mZipped = mRpgMessage.header().compression(); if (body != null && (body.length > 0)) { switch (mMessageType) { case RpgMessageTypes.RPG_EXT_RESP: // External message response HttpConnectionThread .logD( "DecoderThread.handleResponse()", "RpgMessageTypes.RPG_EXT_RESP - " + "Add External Message RawResponse to Decode queue:" + rpgHeader.reqId() + "mBody.len=" + body.length); addToDecode(new RawResponse(rpgHeader.reqId(), body, mZipped, false)); break; case RpgMessageTypes.RPG_PUSH_MSG: // Define push message callback to // notify controller HttpConnectionThread.logD("DecoderThread.handleResponse()", "RpgMessageTypes.RPG_PUSH_MSG - Add Push " + "Message RawResponse to Decode queue:" + 0 + "mBody.len=" + body.length); addToDecode(new RawResponse(rpgHeader.reqId(), body, mZipped, true)); break; case RpgMessageTypes.RPG_INT_RESP: // Internal message response HttpConnectionThread.logD("DecoderThread.handleResponse()", "RpgMessageTypes.RPG_INT_RESP - Add RawResponse to Decode queue:" + rpgHeader.reqId() + "mBody.len=" + body.length); addToDecode(new RawResponse(rpgHeader.reqId(), body, mZipped, false)); break; case RpgMessageTypes.RPG_PRESENCE_RESPONSE: HttpConnectionThread.logD("DecoderThread.handleResponse()", "RpgMessageTypes.RPG_PRESENCE_RESPONSE - " + "Add RawResponse to Decode queue - mZipped[" + mZipped + "]" + "mBody.len=" + body.length); addToDecode(new RawResponse(rpgHeader.reqId(), body, mZipped, false)); break; default: // FIXME after the refactoring we need to add an // error to the responsedecoder break; } } } } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { HttpConnectionThread.logE("DecoderThread.handleResponse()", "Could not close IS: ", ioe); } finally { is = null; } } } } } }
360/360-Engine-for-Android
8dfff3605e21300faff2eb958e644ae9c2b0c81b
follow-up on the code review comments
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 55f68f7..dd459de 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -235,529 +235,522 @@ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue == true)) { chatableIdentities.add(identity); break; } } } // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chatableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chatableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } // invalidate 'chat-able' identities cache if (mMyChatableIdentityList != null) { mMyChatableIdentityList.clear(); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(Response resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); } } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; idBundle = mAvailableIdentityList; } else { requestKey = KEY_MY_IDS; idBundle = mMyIdentityList; } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } /** * * Retrieves the filter for the getAvailableIdentities and getMyIdentities * calls. * * @return The identities filter in form of a bundle. * */ private Bundle getIdentitiesFilter() { Bundle b = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); l.add(IdentityCapability.CapabilityID.get_own_status.name()); b.putStringArrayList("capability", l); return b; } @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } /** * Generate Map containing String capability filters for m supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, List<String>> prepareStringFilter(Bundle filter) { Map<String, List<String>> returnFilter = null; if (filter != null && filter.keySet().size() > 0) { returnFilter = new Hashtable<String, List<String>>(); for (String key : filter.keySet()) { returnFilter.put(key, filter.getStringArrayList(key)); } } else { returnFilter = null; } return returnFilter; } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ + /** {@inheritDoc} */ + @Override public final void onReset() { - clearCachedIdentities(); - super.onReset(); - } - - /** - * - * Clears all cached identities that belong to a user (my identities). Available identities will stay untouched as they do not raise any privacy - * concerns and can stay cached. - * - */ - public void clearCachedIdentities() { if (null != mMyIdentityList) { mMyIdentityList.clear(); } + super.onReset(); } + } diff --git a/src/com/vodafone360/people/engine/meprofile/SyncMeEngine.java b/src/com/vodafone360/people/engine/meprofile/SyncMeEngine.java index 53c1f54..75bf0f4 100644 --- a/src/com/vodafone360/people/engine/meprofile/SyncMeEngine.java +++ b/src/com/vodafone360/people/engine/meprofile/SyncMeEngine.java @@ -156,527 +156,529 @@ public class SyncMeEngine extends BaseEngine { } @Override public long getNextRunTime() { if (!isReady()) { return -1; } if (mFirstTimeSyncStarted && !mFirstTimeMeSyncComplete && (mState == State.IDLE)) { return 0; } if (isCommsResponseOutstanding()) { return 0; } if (isUiRequestOutstanding()) { return 0; } return getCurrentTimeout(); } /** * The condition for the sync me engine run. * @return boolean - TRUE when the engine is ready to run. */ private boolean isReady() { return EngineManager.getInstance().getLoginEngine().isLoggedIn() && checkConnectivity() && mFirstTimeSyncStarted; } @Override public void run() { LogUtils.logD("SyncMeEngine run"); processTimeout(); if (isCommsResponseOutstanding() && processCommsInQueue()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } if (mFromRevision == 0 && (mState == State.IDLE)) { addGetMeProfileContactRequest(); } } @Override public void onCreate() { PersistSettings setting1 = mDbHelper .fetchOption(PersistSettings.Option.FIRST_TIME_MESYNC_STARTED); PersistSettings setting2 = mDbHelper .fetchOption(PersistSettings.Option.FIRST_TIME_MESYNC_COMPLETE); if (setting1 != null) { mFirstTimeSyncStarted = setting1.getFirstTimeMeSyncStarted(); } if (setting2 != null) { mFirstTimeMeSyncComplete = setting2.getFirstTimeMeSyncComplete(); } } @Override public void onDestroy() { } @Override protected void onRequestComplete() { } @Override protected void onTimeoutEvent() { } @Override protected final void processUiRequest(final ServiceUiRequest requestId, Object data) { switch (requestId) { case UPDATE_ME_PROFILE: uploadMeProfile(); break; case GET_ME_PROFILE: getMeProfileChanges(); break; case UPLOAD_ME_STATUS: uploadStatusUpdate(SyncMeDbUtils.updateStatus(mDbHelper, (String)data)); break; default: // do nothing. break; } } /** * Sends a GetMyChanges request to the server, with the current version of * the me profile used as a parameter. */ private void getMeProfileChanges() { if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { return; } newState(State.FETCHING_ME_PROFILE_CHANGES); setReqId(Contacts.getMyChanges(this, mFromRevision)); } /** * The call to download the thumbnail picture for the me profile. * @param url String - picture url of Me Profile (comes with getMyChanges()) * @param localContactId long - local contact id of Me Profile */ private void downloadMeProfileThumbnail(final String url, final long localContactId) { if (NetworkAgent.getAgentState() == NetworkAgent.AgentState.CONNECTED) { Request request = new Request(url, ThumbnailUtils.REQUEST_THUMBNAIL_URI, engineId()); newState(State.FETCHING_ME_PROFILE_THUMBNAIL); setReqId(QueueManager.getInstance().addRequestAndNotify(request)); } } /** * Starts uploading a status update to the server and ignores all other * @param statusDetail - status ContactDetail */ private void uploadStatusUpdate(final ContactDetail statusDetail) { LogUtils.logE("SyncMeProfile uploadStatusUpdate()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { LogUtils.logE("SyncMeProfile uploadStatusUpdate: no internet connection"); return; } if (statusDetail == null) { LogUtils.logE("SyncMeProfile uploadStatusUpdate: null status can't be posted"); return; } newState(State.UPDATING_ME_PRESENCE_TEXT); List<ContactDetail> details = new ArrayList<ContactDetail>(); statusDetail.updated = null; details.add(statusDetail); setReqId(Contacts.setMe(this, details, null, null)); } /** * * Sends a SetMe request to the server in the case that the me profile has * been changed locally. If the me profile thumbnail has always been changed * it will also be uploaded to the server. */ private void uploadMeProfile() { if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { return; } newState(State.UPDATING_ME_PROFILE); Contact meProfile = new Contact(); mDbHelper.fetchContact(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), meProfile); mUploadedMeDetails = SyncMeDbUtils.saveContactDetailChanges(mDbHelper, meProfile); setReqId(Contacts.setMe(this, mUploadedMeDetails, meProfile.aboutMe, meProfile.gender)); } /** * Get current connectivity state from the NetworkAgent. If not connected * completed UI request with COMMs error. * @return true NetworkAgent reports we are connected, false otherwise. */ private boolean checkConnectivity() { if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return false; } return true; } /** * Changes the state of the engine. * @param newState The new state */ private void newState(final State newState) { State oldState = mState; mState = newState; LogUtils.logV("SyncMeEngine newState(): " + oldState + " -> " + mState); } /** * Called by framework when a response to a server request is received. * @param resp The response received */ public final void processCommsResponse(final Response resp) { if (!processPushEvent(resp)) { switch (mState) { case FETCHING_ME_PROFILE_CHANGES: processGetMyChangesResponse(resp); break; case UPDATING_ME_PRESENCE_TEXT: processUpdateStatusResponse(resp); break; case UPDATING_ME_PROFILE: processSetMeResponse(resp); break; case FETCHING_ME_PROFILE_THUMBNAIL: processMeProfileThumbnailResponse(resp); break; default: // do nothing. break; } } } /** * This method stores the thumbnail picture for the me profile * @param resp Response - normally contains ExternalResponseObject for the * picture */ private void processMeProfileThumbnailResponse(final Response resp) { Contact currentMeProfile = new Contact(); ServiceStatus status = SyncMeDbUtils.fetchMeProfile(mDbHelper, currentMeProfile); if (status == ServiceStatus.SUCCESS) { if (resp.mReqId == null || resp.mReqId == 0) { if (resp.mDataTypes.size() > 0 && resp.mDataTypes.get(0).getType() == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE && ((SystemNotification)resp.mDataTypes.get(0)).getSysCode() == SystemNotification.SysNotificationCode.EXTERNAL_HTTP_ERROR) { LogUtils.logE("SyncMeProfile processMeProfileThumbnailResponse():" + SystemNotification.SysNotificationCode.EXTERNAL_HTTP_ERROR); } completeUiRequest(status); return; } else if (resp.mDataTypes.get(0).getType() == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { if (((SystemNotification)resp.mDataTypes.get(0)).getSysCode() == SystemNotification.SysNotificationCode.EXTERNAL_HTTP_ERROR) { LogUtils.logE("SyncMeProfile processMeProfileThumbnailResponse():" + SystemNotification.SysNotificationCode.EXTERNAL_HTTP_ERROR); } completeUiRequest(status); return; } status = BaseEngine .getResponseStatus(BaseDataType.EXTERNAL_RESPONSE_OBJECT_DATA_TYPE, resp.mDataTypes); if (status != ServiceStatus.SUCCESS) { completeUiRequest(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); LogUtils .logE("SyncMeProfile processMeProfileThumbnailResponse() - Can't read response"); return; } if (resp.mDataTypes == null || resp.mDataTypes.isEmpty()) { LogUtils .logE("SyncMeProfile processMeProfileThumbnailResponse() - Datatypes are null"); completeUiRequest(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); return; } // finally save the thumbnails ExternalResponseObject ext = (ExternalResponseObject)resp.mDataTypes.get(0); if (ext.mBody == null) { LogUtils.logE("SyncMeProfile processMeProfileThumbnailResponse() - no body"); completeUiRequest(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); return; } try { ThumbnailUtils.saveExternalResponseObjectToFile(currentMeProfile.localContactID, ext); ContactSummaryTable.modifyPictureLoadedFlag(currentMeProfile.localContactID, true, mDbHelper.getWritableDatabase()); mDbHelper.markMeProfileAvatarChanged(); } catch (IOException e) { LogUtils.logE("SyncMeProfile processMeProfileThumbnailResponse()", e); completeUiRequest(ServiceStatus.ERROR_COMMS_BAD_RESPONSE); } } completeUiRequest(status); } /** * Processes the response from a GetMyChanges request. The me profile data * will be merged in the local database if the response is successful. * Otherwise the processor will complete with a suitable error. * @param resp Response from server. */ private void processGetMyChangesResponse(final Response resp) { LogUtils.logD("SyncMeEngine processGetMyChangesResponse()"); ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.CONTACT_CHANGES_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { ContactChanges changes = (ContactChanges)resp.mDataTypes.get(0); Contact currentMeProfile = new Contact(); status = SyncMeDbUtils.fetchMeProfile(mDbHelper, currentMeProfile); switch (status) { case SUCCESS: String url = SyncMeDbUtils.updateMeProfile(mDbHelper, currentMeProfile, changes.mUserProfile); if (url != null) { downloadMeProfileThumbnail(url, currentMeProfile.localContactID); } else { completeUiRequest(status); } break; case ERROR_NOT_FOUND: // this is the 1st time sync currentMeProfile.copy(changes.mUserProfile); status = SyncMeDbUtils.setMeProfile(mDbHelper, currentMeProfile); mFromRevision = changes.mCurrentServerVersion; StateTable.modifyMeProfileRevision(mFromRevision, mDbHelper .getWritableDatabase()); setFirstTimeMeSyncComplete(true); completeUiRequest(status); break; default: completeUiRequest(status); } } else { completeUiRequest(status); } } /** * Processes the response from a SetMe request. If successful, the server * IDs will be stored in the local database if they have changed. Otherwise * the processor will complete with a suitable error. * @param resp Response from server. */ private void processSetMeResponse(final Response resp) { LogUtils.logD("SyncMeProfile.processMeProfileUpdateResponse()"); ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.CONTACT_CHANGES_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { ContactChanges result = (ContactChanges) resp.mDataTypes.get(0); SyncMeDbUtils.updateMeProfileDbDetailIds(mDbHelper, mUploadedMeDetails, result); if (updateRevisionPostUpdate(result.mServerRevisionBefore, result.mServerRevisionAfter, mFromRevision, mDbHelper)) { mFromRevision = result.mServerRevisionAfter; } } completeUiRequest(status); } /** * This method processes the response to status update by setMe() method * @param resp Response - the expected response datatype is ContactChanges */ private void processUpdateStatusResponse(final Response resp) { LogUtils.logD("SyncMeDbUtils processUpdateStatusResponse()"); ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.CONTACT_CHANGES_DATA_TYPE, resp.mDataTypes); if (status == ServiceStatus.SUCCESS) { ContactChanges result = (ContactChanges) resp.mDataTypes.get(0); LogUtils.logI("SyncMeProfile.processUpdateStatusResponse() - Me profile userId = " + result.mUserProfile.userID); SyncMeDbUtils.savePresenceStatusResponse(mDbHelper, result); } completeUiRequest(status); } @Override protected void completeUiRequest(ServiceStatus status) { super.completeUiRequest(status); newState(State.IDLE); WidgetUtils.kickWidgetUpdateNow(mContext); } /** * Updates the revision of the me profile in the local state table after the * SetMe has completed. This will only happen if the version of the me * profile on the server before the update matches our previous version. * @param before Version before the update * @param after Version after the update * @param currentFromRevision Current version from our database * @param db Database helper used for storing the change * @return true if the update was done, false otherwise. */ private static boolean updateRevisionPostUpdate(final Integer before, final Integer after, final long currentFromRevision, final DatabaseHelper db) { if (before == null || after == null) { return false; } if (!before.equals(currentFromRevision)) { LogUtils .logW("SyncMeProfile.updateRevisionPostUpdate - Previous version is not as expected, current version=" + currentFromRevision + ", server before=" + before + ", server after=" + after); return false; } else { StateTable.modifyMeProfileRevision(after, db.getWritableDatabase()); return true; } } /** * This method adds an external request to Contacts/setMe() method to update * the Me Profile... * @param meProfile Contact - contact to be pushed to the server */ public void addUpdateMeProfileContactRequest() { LogUtils.logV("SyncMeEngine addUpdateMeProfileContactRequest()"); addUiRequestToQueue(ServiceUiRequest.UPDATE_ME_PROFILE, null); } /** * This method adds an external request to Contacts/setMe() method to update * the Me Profile status... * @param textStatus String - the new me profile status to be pushed to the * server */ public void addUpdateMyStatusRequest(String textStatus) { LogUtils.logV("SyncMeEngine addUpdateMyStatusRequest()"); addUiRequestToQueue(ServiceUiRequest.UPLOAD_ME_STATUS, textStatus); } /** * This method adds an external request to Contacts/getMyChanges() method to * update the Me Profile status server. Is called when "pc "push message is * received */ private void addGetMeProfileContactRequest() { LogUtils.logV("SyncMeEngine addGetMeProfileContactRequest()"); addUiRequestToQueue(ServiceUiRequest.GET_ME_PROFILE, null); } /** * This method adds an external request to Contacts/getMyChanges() method to * update the Me Profile status server, is called by the UI at the 1st sync. */ public void addGetMeProfileContactFirstTimeRequest() { LogUtils.logV("SyncMeEngine addGetMeProfileContactFirstTimeRequest()"); setFirstTimeSyncStarted(true); addUiRequestToQueue(ServiceUiRequest.GET_ME_PROFILE, null); } /** * This method process the "pc" push event. * @param resp Response - server response normally containing a "pc" * PushEvent data type * @return boolean - TRUE if a push event was found in the response */ private boolean processPushEvent(final Response resp) { if (resp.mDataTypes == null || resp.mDataTypes.size() == 0) { return false; } BaseDataType dataType = resp.mDataTypes.get(0); if ((dataType == null) || dataType.getType() != BaseDataType.PUSH_EVENT_DATA_TYPE) { return false; } PushEvent pushEvent = (PushEvent) dataType; LogUtils.logV("SyncMeEngine processPushMessage():" + pushEvent.mMessageType); switch (pushEvent.mMessageType) { case PROFILE_CHANGE: addGetMeProfileContactRequest(); break; default: break; } return true; } /** * Helper function to update the database when the state of the * {@link #mFirstTimeMeSyncStarted} flag changes. * @param value New value to the flag. True indicates that first time sync * has been started. The flag is never set to false again by the * engine, it will be only set to false when a remove user data * is done (and the database is deleted). * @return SUCCESS or a suitable error code if the database could not be * updated. */ private ServiceStatus setFirstTimeSyncStarted(final boolean value) { if (mFirstTimeSyncStarted == value) { return ServiceStatus.SUCCESS; } PersistSettings setting = new PersistSettings(); setting.putFirstTimeMeSyncStarted(value); ServiceStatus status = mDbHelper.setOption(setting); if (ServiceStatus.SUCCESS == status) { synchronized (this) { mFirstTimeSyncStarted = value; } } return status; } /** * Helper function to update the database when the state of the * {@link #mFirstTimeMeSyncComplete} flag changes. * @param value New value to the flag. True indicates that first time sync * has been completed. The flag is never set to false again by * the engine, it will be only set to false when a remove user * data is done (and the database is deleted). * @return SUCCESS or a suitable error code if the database could not be * updated. */ private ServiceStatus setFirstTimeMeSyncComplete(final boolean value) { if (mFirstTimeMeSyncComplete == value) { return ServiceStatus.SUCCESS; } PersistSettings setting = new PersistSettings(); setting.putFirstTimeMeSyncComplete(value); ServiceStatus status = mDbHelper.setOption(setting); if (ServiceStatus.SUCCESS == status) { synchronized (this) { mFirstTimeMeSyncComplete = value; } } return status; } /** * This method needs to be called as part of removeAllData()/changeUser() * routine. */ + /** {@inheritDoc} */ + @Override public final void onReset() { mFirstTimeMeSyncComplete = false; mFirstTimeSyncStarted = false; mFromRevision = 0; super.onReset(); } /** * This method TRUE if the Me Profile has been synced once. * @return boolean - TRUE if the Me Profile has been synced once. */ public final boolean isFirstTimeMeSyncComplete() { return mFirstTimeMeSyncComplete; } }
360/360-Engine-for-Android
941292d1418705e1361e3060e0bf82f52a1f923a
switched off transport trace logging
diff --git a/src/com/vodafone360/people/Settings.java b/src/com/vodafone360/people/Settings.java index f02fc5a..ba89fc3 100644 --- a/src/com/vodafone360/people/Settings.java +++ b/src/com/vodafone360/people/Settings.java @@ -1,294 +1,294 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; /** * All application settings. */ public final class Settings { /* * LogCat. */ /** LogCat TAG prefix. **/ public static final String LOG_TAG = "People_"; /* * Transport. */ /** Milliseconds until HTTP connection will time out. */ public static final int HTTP_CONNECTION_TIMEOUT = 30000; /** Maximum number of HTTP connection attempts. */ public static final int HTTP_MAX_RETRY_COUNT = 3; /** HTTP header content type. */ public static final String HTTP_HEADER_CONTENT_TYPE = "application/binary"; /** Number of empty RPG poll responses before stopping RPG poll. */ public static final int BLANK_RPG_HEADER_COUNT = 4; /** TCP Heartbeat interval (10 seconds). */ public static final long TCP_VF_HEARTBEAT_INTERVAL = 10 * 60 * 1000; /** TCP retry interval if we have lost the connection (30 seconds). */ public static final long TCP_RETRY_BROKEN_CONNECTION_INTERVAL = 30 * 60 * 1000; /** TCP socket read time out for the read-operation. */ public static final int TCP_SOCKET_READ_TIMEOUT = 10 * 60 * 1000; /* * Notifications. */ /** LED colour. */ public static final int NOTIFICATION_LED_COLOR = 0xff00ff00; // Green /** LED on time. */ public static final int NOTIFICATION_LED_OFF_TIME = 300; /** LED on time. */ public static final int NOTIFICATION_LED_ON_TIME = 1000; /* * Upgrade Engine */ /** * See UpdateSettingsActivity.FREQUENCY_SETTING_LONG array for meaning (i.e. * Every 6 hours) */ public static final int PREFS_CHECK_FREQUENCY_DEFAULT = 3; /** Show the upgrade dialog box every 10 minutes. */ public static final int DIALOG_CHECK_FREQUENCY_MILLIS = 10 * 60 * 1000; /** * Component trace flags (always checked in as false, not part of build * script). */ /** Trace output for engine components. **/ public static final boolean ENABLED_ENGINE_TRACE = false; /** Trace output for database components. **/ public static final boolean ENABLED_DATABASE_TRACE = false; /** Trace output for transport (i.e. network IO) components. **/ - public static final boolean ENABLED_TRANSPORT_TRACE = true; + public static final boolean ENABLED_TRANSPORT_TRACE = false; /** Trace output for contact synchronisation components. **/ public static final boolean ENABLED_CONTACTS_SYNC_TRACE = false; /** Log engine runtime information to file for profiling. **/ public static final boolean ENABLED_PROFILE_ENGINES = false; /** * This is a list of strings containing the names of engines to be * deactivated in the build. A de-activated engine is constructed but will * never be run (nor will onCreate or onDestroy be called). Any UI requests * will be automatically completed by the framework with a * ServiceStatus.ERROR_NOT_IMPLEMENTED error. */ public static final String DEACTIVATE_ENGINE_LIST_KEY = "deactivated-engines-list"; /* * Hard coded settings */ /** Enable dialler cheat code. **/ public static final boolean DIALER_CHEATCODES_ENABLED = true; /** Enable SMS account activation. **/ public static final boolean ENABLE_ACTIVATION = false; /** * Enable SIM inserted check. Always set to TRUE. Makes the application * unusable if there is no valid SIM card inserted into the device. */ public static final boolean ENABLE_SIM_CHECK = true; /** Enable fetching native contacts. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS = true; /** Enable fetching native contacts on change. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS_ON_CHANGE = true; /** Enable ME profile synchronisation. **/ public static final boolean ENABLE_ME_PROFILE_SYNC = true; /** Enable server contact synchronisation. **/ public static final boolean ENABLE_SERVER_CONTACT_SYNC = true; /** Enable server thumbnail synchronisation. **/ public static final boolean ENABLE_THUMBNAIL_SYNC = true; /** Enable update native contacts synchronisation. **/ public static final boolean ENABLE_UPDATE_NATIVE_CONTACTS = true; /** Enable hiding of connected friends group. **/ public static final boolean HIDE_CONNECTED_FRIENDS_GROUP = true; /* * Keys for properties that can be changed at build time. */ /** Key for application ID setting. **/ public static final String APP_KEY_ID = "app-key-id"; /** Key for application secret key setting. **/ public static final String APP_SECRET_KEY = "app-secret-key"; /** Key for enable logging setting. **/ protected static final String ENABLE_LOGCAT_KEY = "enable-logcat"; /** Key for enable RPG setting. **/ public static final String ENABLE_RPG_KEY = "use-rpg"; /** Key for enable SNS resource icon setting. **/ public static final String ENABLE_SNS_RESOURCE_ICON_KEY = "enable-sns-resource-icon"; /** Key for RPG server URL setting. **/ public static final String RPG_SERVER_KEY = "rpg-url"; /** Key for Hessian URL setting. **/ public static final String SERVER_URL_HESSIAN_KEY = "hessian-url"; /* * Keys without defaults. */ /** Key for TCP server URL setting. **/ public static final String TCP_RPG_URL_KEY = "rpg-tcp-url"; /** Key for TCP port setting. **/ public static final String TCP_RPG_PORT_KEY = "rpg-tcp-port"; /** Key for upgrade check URL setting. **/ public static final String UPGRADE_CHECK_URL_KEY = "upgrade-url"; /* * Default for properties that can be changed at build time. */ /** Default for logging enabled setting. **/ protected static final String DEFAULT_ENABLE_LOGCAT = "true"; /** Default for RPG enabled setting. **/ protected static final String DEFAULT_ENABLE_RPG = "true"; /** Default for SNS resource icon setting. **/ protected static final String DEFAULT_ENABLE_SNS_RESOURCE_ICON = "true"; /** Default for RPG server URL setting. **/ protected static final String DEFAULT_RPG_SERVER = "http://rpg.vodafone360.com/rpg/mcomet/"; /** Default for Hessian URL setting. **/ protected static final String DEFAULT_SERVER_URL_HESSIAN = "http://api.vodafone360.com/services/hessian/"; /* * Request timeouts for all engines and requests, except for fire and * forget calls to RPG: SET_AVAILABILITY and SEND_CHAT_MSG. */ /** Do not handle timeouts for this API. **/ private static final long DONT_HANDLE_TIMEOUTS = -1; /** Generic timeout for requests. **/ private static final long ALL_ENGINES_REQUESTS_TIMEOUT = 60000; /** Timeout for all presence API requests. **/ private static final long PRESENCE_ENGINE_REQUESTS_TIMEOUT = 120000; /** Number of milliseconds in a week. **/ public static final long HISTORY_IS_WEEK_LONG = 7 * 24 * 60 * 60 * 1000; /** Timeout for request waiting in queue. **/ public static final long REMOVE_REQUEST_FROM_QUEUE_MILLIS = 15 * 60 * 1000; /* * The timeouts in milliseconds for the different APIs. */ /** Timeout for activities API. **/ public static final long API_REQUESTS_TIMEOUT_ACTIVITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for authentication API. **/ public static final long API_REQUESTS_TIMEOUT_AUTH = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat create conversation API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_CREATE_CONV = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat send message API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_SEND_MESSAGE = DONT_HANDLE_TIMEOUTS; /** Timeout for contacts API. **/ public static final long API_REQUESTS_TIMEOUT_CONTACTS = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for group privacy API. **/ public static final long API_REQUESTS_TIMEOUT_GROUP_PRIVACY = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for identities API. **/ public static final long API_REQUESTS_TIMEOUT_IDENTITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for presence list API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_LIST = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Timeout for presence set availability API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Enable Facebook chat. **/ public static boolean sEnableFacebookChat = true; /** * Danger! Only set to true if you know what you are doing! This logs each * response no matter if gzipped or not to the SD card under the given * request ID. */ public static boolean sEnableSuperExpensiveResponseFileLogging = false; /** * Private constructor to prevent instantiation. */ private Settings() { // Do nothing. } } \ No newline at end of file
360/360-Engine-for-Android
77d9a98c09311b0c20b5006c32bf84bc6ae0f6c8
clear the cached identities list on "change user" - PAND-1795
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 061aa45..55f68f7 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -231,513 +231,533 @@ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue == true)) { chatableIdentities.add(identity); break; } } } // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chatableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chatableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } // invalidate 'chat-able' identities cache if (mMyChatableIdentityList != null) { mMyChatableIdentityList.clear(); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override protected void processCommsResponse(Response resp) { LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } } else { LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); } } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; idBundle = mAvailableIdentityList; } else { requestKey = KEY_MY_IDS; idBundle = mMyIdentityList; } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } /** * * Retrieves the filter for the getAvailableIdentities and getMyIdentities * calls. * * @return The identities filter in form of a bundle. * */ private Bundle getIdentitiesFilter() { Bundle b = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); l.add(IdentityCapability.CapabilityID.get_own_status.name()); b.putStringArrayList("capability", l); return b; } @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } /** * Generate Map containing String capability filters for m supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, List<String>> prepareStringFilter(Bundle filter) { Map<String, List<String>> returnFilter = null; if (filter != null && filter.keySet().size() > 0) { returnFilter = new Hashtable<String, List<String>>(); for (String key : filter.keySet()) { returnFilter.put(key, filter.getStringArrayList(key)); } } else { returnFilter = null; } return returnFilter; } + /** + * This method needs to be called as part of removeAllData()/changeUser() + * routine. + */ + public final void onReset() { + clearCachedIdentities(); + super.onReset(); + } + + /** + * + * Clears all cached identities that belong to a user (my identities). Available identities will stay untouched as they do not raise any privacy + * concerns and can stay cached. + * + */ + public void clearCachedIdentities() { + if (null != mMyIdentityList) { + mMyIdentityList.clear(); + } + } }
360/360-Engine-for-Android
d195b35aac245c8bcc5aacfc8505a01a0f04a74c
made use of the response object types. also changed some request types for identities requests as they were too generic.
diff --git a/src/com/vodafone360/people/Settings.java b/src/com/vodafone360/people/Settings.java index ba89fc3..f02fc5a 100644 --- a/src/com/vodafone360/people/Settings.java +++ b/src/com/vodafone360/people/Settings.java @@ -1,294 +1,294 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; /** * All application settings. */ public final class Settings { /* * LogCat. */ /** LogCat TAG prefix. **/ public static final String LOG_TAG = "People_"; /* * Transport. */ /** Milliseconds until HTTP connection will time out. */ public static final int HTTP_CONNECTION_TIMEOUT = 30000; /** Maximum number of HTTP connection attempts. */ public static final int HTTP_MAX_RETRY_COUNT = 3; /** HTTP header content type. */ public static final String HTTP_HEADER_CONTENT_TYPE = "application/binary"; /** Number of empty RPG poll responses before stopping RPG poll. */ public static final int BLANK_RPG_HEADER_COUNT = 4; /** TCP Heartbeat interval (10 seconds). */ public static final long TCP_VF_HEARTBEAT_INTERVAL = 10 * 60 * 1000; /** TCP retry interval if we have lost the connection (30 seconds). */ public static final long TCP_RETRY_BROKEN_CONNECTION_INTERVAL = 30 * 60 * 1000; /** TCP socket read time out for the read-operation. */ public static final int TCP_SOCKET_READ_TIMEOUT = 10 * 60 * 1000; /* * Notifications. */ /** LED colour. */ public static final int NOTIFICATION_LED_COLOR = 0xff00ff00; // Green /** LED on time. */ public static final int NOTIFICATION_LED_OFF_TIME = 300; /** LED on time. */ public static final int NOTIFICATION_LED_ON_TIME = 1000; /* * Upgrade Engine */ /** * See UpdateSettingsActivity.FREQUENCY_SETTING_LONG array for meaning (i.e. * Every 6 hours) */ public static final int PREFS_CHECK_FREQUENCY_DEFAULT = 3; /** Show the upgrade dialog box every 10 minutes. */ public static final int DIALOG_CHECK_FREQUENCY_MILLIS = 10 * 60 * 1000; /** * Component trace flags (always checked in as false, not part of build * script). */ /** Trace output for engine components. **/ public static final boolean ENABLED_ENGINE_TRACE = false; /** Trace output for database components. **/ public static final boolean ENABLED_DATABASE_TRACE = false; /** Trace output for transport (i.e. network IO) components. **/ - public static final boolean ENABLED_TRANSPORT_TRACE = false; + public static final boolean ENABLED_TRANSPORT_TRACE = true; /** Trace output for contact synchronisation components. **/ public static final boolean ENABLED_CONTACTS_SYNC_TRACE = false; /** Log engine runtime information to file for profiling. **/ public static final boolean ENABLED_PROFILE_ENGINES = false; /** * This is a list of strings containing the names of engines to be * deactivated in the build. A de-activated engine is constructed but will * never be run (nor will onCreate or onDestroy be called). Any UI requests * will be automatically completed by the framework with a * ServiceStatus.ERROR_NOT_IMPLEMENTED error. */ public static final String DEACTIVATE_ENGINE_LIST_KEY = "deactivated-engines-list"; /* * Hard coded settings */ /** Enable dialler cheat code. **/ public static final boolean DIALER_CHEATCODES_ENABLED = true; /** Enable SMS account activation. **/ public static final boolean ENABLE_ACTIVATION = false; /** * Enable SIM inserted check. Always set to TRUE. Makes the application * unusable if there is no valid SIM card inserted into the device. */ public static final boolean ENABLE_SIM_CHECK = true; /** Enable fetching native contacts. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS = true; /** Enable fetching native contacts on change. **/ public static final boolean ENABLE_FETCH_NATIVE_CONTACTS_ON_CHANGE = true; /** Enable ME profile synchronisation. **/ public static final boolean ENABLE_ME_PROFILE_SYNC = true; /** Enable server contact synchronisation. **/ public static final boolean ENABLE_SERVER_CONTACT_SYNC = true; /** Enable server thumbnail synchronisation. **/ public static final boolean ENABLE_THUMBNAIL_SYNC = true; /** Enable update native contacts synchronisation. **/ public static final boolean ENABLE_UPDATE_NATIVE_CONTACTS = true; /** Enable hiding of connected friends group. **/ public static final boolean HIDE_CONNECTED_FRIENDS_GROUP = true; /* * Keys for properties that can be changed at build time. */ /** Key for application ID setting. **/ public static final String APP_KEY_ID = "app-key-id"; /** Key for application secret key setting. **/ public static final String APP_SECRET_KEY = "app-secret-key"; /** Key for enable logging setting. **/ protected static final String ENABLE_LOGCAT_KEY = "enable-logcat"; /** Key for enable RPG setting. **/ public static final String ENABLE_RPG_KEY = "use-rpg"; /** Key for enable SNS resource icon setting. **/ public static final String ENABLE_SNS_RESOURCE_ICON_KEY = "enable-sns-resource-icon"; /** Key for RPG server URL setting. **/ public static final String RPG_SERVER_KEY = "rpg-url"; /** Key for Hessian URL setting. **/ public static final String SERVER_URL_HESSIAN_KEY = "hessian-url"; /* * Keys without defaults. */ /** Key for TCP server URL setting. **/ public static final String TCP_RPG_URL_KEY = "rpg-tcp-url"; /** Key for TCP port setting. **/ public static final String TCP_RPG_PORT_KEY = "rpg-tcp-port"; /** Key for upgrade check URL setting. **/ public static final String UPGRADE_CHECK_URL_KEY = "upgrade-url"; /* * Default for properties that can be changed at build time. */ /** Default for logging enabled setting. **/ protected static final String DEFAULT_ENABLE_LOGCAT = "true"; /** Default for RPG enabled setting. **/ protected static final String DEFAULT_ENABLE_RPG = "true"; /** Default for SNS resource icon setting. **/ protected static final String DEFAULT_ENABLE_SNS_RESOURCE_ICON = "true"; /** Default for RPG server URL setting. **/ protected static final String DEFAULT_RPG_SERVER = "http://rpg.vodafone360.com/rpg/mcomet/"; /** Default for Hessian URL setting. **/ protected static final String DEFAULT_SERVER_URL_HESSIAN = "http://api.vodafone360.com/services/hessian/"; /* * Request timeouts for all engines and requests, except for fire and * forget calls to RPG: SET_AVAILABILITY and SEND_CHAT_MSG. */ /** Do not handle timeouts for this API. **/ private static final long DONT_HANDLE_TIMEOUTS = -1; /** Generic timeout for requests. **/ private static final long ALL_ENGINES_REQUESTS_TIMEOUT = 60000; /** Timeout for all presence API requests. **/ private static final long PRESENCE_ENGINE_REQUESTS_TIMEOUT = 120000; /** Number of milliseconds in a week. **/ public static final long HISTORY_IS_WEEK_LONG = 7 * 24 * 60 * 60 * 1000; /** Timeout for request waiting in queue. **/ public static final long REMOVE_REQUEST_FROM_QUEUE_MILLIS = 15 * 60 * 1000; /* * The timeouts in milliseconds for the different APIs. */ /** Timeout for activities API. **/ public static final long API_REQUESTS_TIMEOUT_ACTIVITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for authentication API. **/ public static final long API_REQUESTS_TIMEOUT_AUTH = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat create conversation API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_CREATE_CONV = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for chat send message API. **/ public static final long API_REQUESTS_TIMEOUT_CHAT_SEND_MESSAGE = DONT_HANDLE_TIMEOUTS; /** Timeout for contacts API. **/ public static final long API_REQUESTS_TIMEOUT_CONTACTS = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for group privacy API. **/ public static final long API_REQUESTS_TIMEOUT_GROUP_PRIVACY = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for identities API. **/ public static final long API_REQUESTS_TIMEOUT_IDENTITIES = ALL_ENGINES_REQUESTS_TIMEOUT; /** Timeout for presence list API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_LIST = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Timeout for presence set availability API. **/ public static final long API_REQUESTS_TIMEOUT_PRESENCE_SET_AVAILABILITY = PRESENCE_ENGINE_REQUESTS_TIMEOUT; /** Enable Facebook chat. **/ public static boolean sEnableFacebookChat = true; /** * Danger! Only set to true if you know what you are doing! This logs each * response no matter if gzipped or not to the SD card under the given * request ID. */ public static boolean sEnableSuperExpensiveResponseFileLogging = false; /** * Private constructor to prevent instantiation. */ private Settings() { // Do nothing. } } \ No newline at end of file diff --git a/src/com/vodafone360/people/engine/EngineManager.java b/src/com/vodafone360/people/engine/EngineManager.java index 4cb717c..0a7de8c 100644 --- a/src/com/vodafone360/people/engine/EngineManager.java +++ b/src/com/vodafone360/people/engine/EngineManager.java @@ -1,595 +1,596 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine; import java.security.InvalidParameterException; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import com.vodafone360.people.MainApplication; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback; import com.vodafone360.people.engine.activities.ActivitiesEngine; import com.vodafone360.people.engine.contactsync.ContactSyncEngine; import com.vodafone360.people.engine.groups.GroupsEngine; import com.vodafone360.people.engine.content.ContentEngine; import com.vodafone360.people.engine.identities.IdentityEngine; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.engine.meprofile.SyncMeEngine; import com.vodafone360.people.engine.presence.PresenceEngine; import com.vodafone360.people.engine.upgrade.UpgradeEngine; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.WorkerThread; import com.vodafone360.people.service.io.ResponseQueue; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.utils.LogUtils; /** * EngineManager class is responsible for creating, handling and deletion of * engines in the People client. The EngineManager determine when each engine * should be run based on the engine's next run time or whether there is a * waiting request for that engine. The EngineManager routes received responses * to the appropriate engine. */ public class EngineManager { /** * Identifiers for engines. */ public enum EngineId { LOGIN_ENGINE, CONTACT_SYNC_ENGINE, GROUPS_ENGINE, ACTIVITIES_ENGINE, IDENTITIES_ENGINE, PRESENCE_ENGINE, UPGRADE_ENGINE, CONTENT_ENGINE, SYNCME_ENGINE, UNDEFINED // add ids as we progress } /** * {@link EngineManager} is a singleton, so this is the static reference. */ private static EngineManager sEngineManager; /** * Engine manager maintains a list of all engines in the system. This is a * map between the engine ID and the engine reference. */ private final HashMap<Integer, BaseEngine> mEngineList = new HashMap<Integer, BaseEngine>(); /** * Reference to the {@RemoteService} object which provides * access to the {@link WorkerThread}. */ private RemoteService mService; /** * Engines require access the {@link IEngineEventCallback} interface. * Implements several useful methods for engines such as UI request * complete. */ private IEngineEventCallback mUiEventCallback; /** * @see LoginEngine */ private LoginEngine mLoginEngine; /** * @see UpgradeEngine */ private UpgradeEngine mUpgradeEngine; /** * @see ActivitiesEngine */ private ActivitiesEngine mActivitiesEngine; /** * @see SyncMeEngine */ private SyncMeEngine mSyncMeEngine; /** * @see PresenceEngine */ private PresenceEngine mPresenceEngine; /** * @see IdentityEngine */ private IdentityEngine mIdentityEngine; /** * @see ContactSyncEngine */ private ContactSyncEngine mContactSyncEngine; /** * @see GroupsEngine */ private GroupsEngine mGroupsEngine; /** * @see ContentEngine */ private ContentEngine mContentEngine; /** * Maximum time the run function for an engine is allowed to run before a * warning message will be displayed (debug only) */ private static final long ENGINE_RUN_TIME_THRESHOLD = 3000; /** * Engine Manager Constructor * * @param service {@link RemoteService} reference * @param uiCallback Provides useful engine callback functionality. */ private EngineManager(RemoteService service, IEngineEventCallback uiCallback) { mService = service; mUiEventCallback = uiCallback; } /** * Create instance of EngineManager. * * @param service {@link RemoteService} reference * @param uiCallback Provides useful engine callback functionality. */ public static void createEngineManager(RemoteService service, IEngineEventCallback uiCallback) { sEngineManager = new EngineManager(service, uiCallback); sEngineManager.onCreate(); } /** * Destroy EngineManager. */ public static void destroyEngineManager() { if (sEngineManager != null) { sEngineManager.onDestroy(); sEngineManager = null; } } /** * Get single instance of {@link EngineManager}. * * @return {@link EngineManager} singleton instance. */ public static EngineManager getInstance() { if (sEngineManager == null) { throw new InvalidParameterException("Please call EngineManager.createEngineManager() " + "before EngineManager.getInstance()"); } return sEngineManager; } /** * Add a new engine to the EngineManager. * * @param newEngine Engine to be added. */ private synchronized void addEngine(BaseEngine newEngine) { final String newName = newEngine.getClass().getSimpleName(); String[] deactivatedEngines = SettingsManager .getStringArrayProperty(Settings.DEACTIVATE_ENGINE_LIST_KEY); for (String engineName : deactivatedEngines) { if (engineName.equals(newName)) { LogUtils.logW("DEACTIVATE ENGINE: " + engineName); newEngine.deactivateEngine(); } } if (!newEngine.isDeactivated()) { newEngine.onCreate(); mEngineList.put(newEngine.mEngineId.ordinal(), newEngine); } mService.kickWorkerThread(); } /** * Closes an engine and removes it from the list. * * @param engine Reference of engine by base class {@link BaseEngine} to * close */ private synchronized void closeEngine(BaseEngine engine) { mEngineList.remove(engine.engineId().ordinal()); if (!engine.isDeactivated()) { engine.onDestroy(); } } /** * Called immediately after manager has been created. Starts the necessary * engines */ private synchronized void onCreate() { // LogUtils.logV("EngineManager.onCreate()"); createLoginEngine(); createIdentityEngine(); createSyncMeEngine(); createContactSyncEngine(); createGroupsEngine(); if (SettingsManager.getProperty(Settings.UPGRADE_CHECK_URL_KEY) != null) { createUpgradeEngine(); } createActivitiesEngine(); createPresenceEngine(); createContentEngine(); } /** * Called just before the service is stopped. Shuts down all the engines */ private synchronized void onDestroy() { final int engineCount = mEngineList.values().size(); BaseEngine[] engineList = new BaseEngine[engineCount]; mEngineList.values().toArray(engineList); for (int i = 0; i < engineCount; i++) { closeEngine(engineList[i]); } mLoginEngine = null; mUpgradeEngine = null; mActivitiesEngine = null; mPresenceEngine = null; mIdentityEngine = null; mContactSyncEngine = null; mGroupsEngine = null; mContentEngine = null; } /** * Obtains a reference to the login engine * * @return a reference to the LoginEngine */ public LoginEngine getLoginEngine() { assert mLoginEngine != null; return mLoginEngine; } /** * Create instance of LoginEngine. */ private synchronized void createLoginEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mLoginEngine = new LoginEngine(mService, mUiEventCallback, app.getDatabase()); addEngine(mLoginEngine); } /** * Fetch upgrade engine * * @return UpgradeEngine object */ public UpgradeEngine getUpgradeEngine() { assert mUpgradeEngine != null; return mUpgradeEngine; } /** * Create instance of UpgradeEngine. */ private synchronized void createUpgradeEngine() { mUpgradeEngine = new UpgradeEngine(mService, mUiEventCallback); addEngine(mUpgradeEngine); } /** * Fetch activities engine * * @return a ActivitiesEngine object */ public ActivitiesEngine getActivitiesEngine() { assert mActivitiesEngine != null; return mActivitiesEngine; } /** * Create instance of ActivitiesEngine. */ private synchronized void createActivitiesEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mActivitiesEngine = new ActivitiesEngine(mService, mUiEventCallback, app.getDatabase()); getLoginEngine().addListener(mActivitiesEngine); addEngine(mActivitiesEngine); } /** * Fetch sync me engine, starting it if necessary. * * @return The SyncMeEngine */ public SyncMeEngine getSyncMeEngine() { assert mSyncMeEngine != null; return mSyncMeEngine; } /** * Create instance of SyncMeEngine. */ private synchronized void createSyncMeEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mSyncMeEngine = new SyncMeEngine(mService, mUiEventCallback, app.getDatabase()); addEngine(mSyncMeEngine); } /** * Fetch presence engine * * @return Presence Engine object */ public PresenceEngine getPresenceEngine() { assert mPresenceEngine != null; return mPresenceEngine; } /** * Fetch identity engine * * @return IdentityEngine object */ public IdentityEngine getIdentityEngine() { assert mIdentityEngine != null; return mIdentityEngine; } /** * Fetch content engine * * @return ContentEngine object */ public ContentEngine getContentEngine() { assert mContentEngine != null; return mContentEngine; } /** * Fetch contact sync engine * * @return ContactSyncEngine object */ public ContactSyncEngine getContactSyncEngine() { assert mContactSyncEngine != null; return mContactSyncEngine; } private synchronized void createContactSyncEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mContactSyncEngine = new ContactSyncEngine(mUiEventCallback, mService, app.getDatabase(), null); addEngine(mContactSyncEngine); } /** * Fetch groups engine * * @return GroupEngine object */ public GroupsEngine getGroupsEngine() { assert mGroupsEngine != null; return mGroupsEngine; } private synchronized void createGroupsEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mGroupsEngine = new GroupsEngine(mService, mUiEventCallback, app.getDatabase()); addEngine(mGroupsEngine); } /** * Create instance of IdentityEngine. */ private synchronized void createIdentityEngine() { mIdentityEngine = new IdentityEngine(mUiEventCallback); + ConnectionManager.getInstance().addConnectionListener(mIdentityEngine); addEngine(mIdentityEngine); } /** * Create instance of ContentEngine. */ private synchronized void createContentEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mContentEngine = new ContentEngine(mUiEventCallback, app.getDatabase()); addEngine(mContentEngine); } /** * Create instance of PresenceEngine. */ private synchronized void createPresenceEngine() { final MainApplication app = (MainApplication)mService.getApplication(); mPresenceEngine = new PresenceEngine(mUiEventCallback, app.getDatabase()); ConnectionManager.getInstance().addConnectionListener(mPresenceEngine); getLoginEngine().addListener(mPresenceEngine); addEngine(mPresenceEngine); } /** * Respond to incoming message received from Comms layer. If this message * has a valid engine id it is routed to that engine, otherwise The * {@link EngineManager} will try to get the next response. * * @param source EngineId associated with incoming message. */ public void onCommsInMessage(EngineId source) { BaseEngine engine = null; if (source != null) { engine = mEngineList.get(source.ordinal()); } if (engine != null) { engine.onCommsInMessage(); } else { LogUtils.logE("EngineManager.onCommsInMessage - " + "Cannot dispatch message, unknown source " + source); final ResponseQueue queue = ResponseQueue.getInstance(); queue.getNextResponse(source); } } /** * Run any waiting engines and return the time in milliseconds from now when * this method needs to be called again. * * @return -1 never needs to run, 0 needs to run as soon as possible, * CurrentTime + 60000 in 1 minute, etc. */ public synchronized long runEngines() { long nextRuntime = -1; Set<Integer> e = mEngineList.keySet(); Iterator<Integer> i = e.iterator(); while (i.hasNext()) { int engineId = i.next(); BaseEngine engine = mEngineList.get(engineId); long currentTime = System.currentTimeMillis(); long tempRuntime = engine.getNextRunTime(); // TODO: Pass // mCurrentTime to // getNextRunTime() to // help with Unit // tests if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logV("EngineManager.runEngines() " + "engine[" + engine.getClass().getSimpleName() + "] " + "nextRunTime[" + getHumanReadableTime(tempRuntime, currentTime) + "] " + "current[" + getHumanReadableTime(nextRuntime, currentTime) + "]"); } else { if (tempRuntime > 0 && tempRuntime < currentTime) { LogUtils.logD("Engine[" + engine.getClass().getSimpleName() + "] run pending"); } } if (tempRuntime < 0) { if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logV("EngineManager.runEngines() Engine is off, so ignore"); } } else if (tempRuntime <= currentTime) { if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logV("EngineManager.runEngines() Run Engine [" + engine.getClass().getSimpleName() + "] and make sure we check it once more before sleeping"); } /** TODO: Consider passing mCurrentTime to mEngine.run(). **/ engine.run(); nextRuntime = 0; final long timeForRun = System.currentTimeMillis() - currentTime; if (timeForRun > ENGINE_RUN_TIME_THRESHOLD) { LogUtils.logE("EngineManager.runEngines() Engine [" + engine.getClass().getSimpleName() + "] took " + timeForRun + "ms to run"); } if (Settings.ENABLED_PROFILE_ENGINES) { StringBuilder string = new StringBuilder(); string.append(System.currentTimeMillis()); string.append("|"); string.append(engine.getClass().getSimpleName()); string.append("|"); string.append(timeForRun); LogUtils.profileToFile(string.toString()); } } else { if (nextRuntime != -1) { nextRuntime = Math.min(nextRuntime, tempRuntime); } else { nextRuntime = tempRuntime; } if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logV("EngineManager.runEngines() Set mNextRuntime to [" + getHumanReadableTime(nextRuntime, currentTime) + "]"); } } } if (Settings.ENABLED_ENGINE_TRACE) { LogUtils.logI("EngineManager.getNextRunTime() Return [" + getHumanReadableTime(nextRuntime, System.currentTimeMillis()) + "]"); } return nextRuntime; } /*** * Display the Absolute Time in a human readable format (for testing only). * * @param absoluteTime Time to convert * @param currentTime Current time, for creating all relative times * @return Absolute time in human readable form */ private static String getHumanReadableTime(long absoluteTime, long currentTime) { if (absoluteTime == -1) { return "OFF"; } else if ((absoluteTime == 0)) { return "NOW"; } else if (absoluteTime >= currentTime) { return (absoluteTime - currentTime) + "ms"; } else { return (currentTime - absoluteTime) + "ms LATE"; } } /** * Resets all the engines. Note: the method will block until all the engines * have performed the reset. */ public void resetAllEngines() { LogUtils.logV("EngineManager.resetAllEngines() - begin"); synchronized (mEngineList) { // Propagate the reset event to all engines for (BaseEngine engine : mEngineList.values()) { engine.onReset(); } } // block the thread until all engines have been reset boolean allEngineAreReset = false; while (!allEngineAreReset) { synchronized (mEngineList) { boolean engineNotReset = false; for (BaseEngine engine : mEngineList.values()) { if (!engine.getReset()) { engineNotReset = true; } } if (!engineNotReset) { allEngineAreReset = true; for (BaseEngine engine : mEngineList.values()) { engine.clearReset(); } } } Thread.yield(); } LogUtils.logV("EngineManager.resetAllEngines() - end"); } } diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 80c38c0..e823246 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,746 +1,763 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.identities; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import android.os.Bundle; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.api.Identities; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.LogUtils; /** * Engine responsible for handling retrieval and validation of Identities (e.g. * 3rd party/web accounts). The Identities engine can fetch a list of available * accounts, and set required capabilities and validate credentials for * specified accounts. */ public class IdentityEngine extends BaseEngine implements ITcpConnectionListener { /** * States for IdentitiesEngine. States are based on the requests that the * engine needs to handle. */ private enum State { IDLE, FETCHING_IDENTITIES, VALIDATING_IDENTITY_CREDENTIALS, SETTING_IDENTITY_STATUS, GETTING_MY_IDENTITIES, GETTING_MY_CHATABLE_IDENTITIES } /** * Mutex for thread synchronisation */ private final Object mMutex = new Object(); /** * Container class for Identity Capability Status request. Consists of a * network, identity id and a filter containing the required capabilities. */ private static class IdentityStatusRequest { private String mNetwork; private String mIdentityId; private String mIdentityStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setIdentityStatus(String status) { mIdentityStatus = status; } } /** * Container class encapsulating an Identity validation request containing: * dry-run flag, network, user-name, password, set of required capabilities. */ private static class IdentityValidateCredentialsRequest { /** Performs a dry run if true. */ private boolean mDryRun; /** Network to sign into. */ private String mNetwork; /** Username to sign into identity with. */ private String mUserName; /** Password to sign into identity with. */ private String mPassword; private Map<String, Boolean> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } /** The minimum interval between identity requests. */ private static final long MIN_REQUEST_INTERVAL = 60 * 60 * 1000; /** The timestamp of which my identities were last requested. */ private long mLastMyIdentitiesRequestTimestamp; /** The timestamp of which available identities were last requested. */ private long mLastAvailableIdentitiesRequestTimestamp; /** The state of the state machine handling ui requests. */ private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ private ArrayList<Identity> mMyIdentityList; /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; /** Holds the status messages of the setIdentityCapability-request. */ private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** The key for setIdentityCapability data type for the push ui message. */ public static final String KEY_DATA = "data"; /** The key for available identities for the push ui message. */ public static final String KEY_AVAILABLE_IDS = "availableids"; /** The key for my identities for the push ui message. */ public static final String KEY_MY_IDS = "myids"; /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; mMyIdentityList = new ArrayList<Identity>(); mAvailableIdentityList = new ArrayList<Identity>(); mLastMyIdentitiesRequestTimestamp = 0; mLastAvailableIdentitiesRequestTimestamp = 0; } /** * * Gets all third party identities and adds the mobile identity * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getAvailableThirdPartyIdentities() { if ((mAvailableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } /** * * Gets all third party identities the user is currently signed up for. * * @return A list of 3rd party identities the user is signed in to or an * empty list if something went wrong retrieving the identities. * */ public ArrayList<Identity> getMyThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetMyIdentitiesRequest(); } return mMyIdentityList; } /** * * Takes all third party identities that have a chat capability set to true. * It also includes the 360 identity mobile. * * @return A list of chattable 3rd party identities the user is signed in to * plus the mobile 360 identity. If the retrieval identities failed the * returned list will be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyChattableIdentities() { ArrayList<Identity> chatableIdentities = new ArrayList<Identity>(); int identityListSize = mMyIdentityList.size(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < identityListSize; i++) { Identity identity = mMyIdentityList.get(i); List<IdentityCapability> capabilities = identity.mCapabilities; if (null == capabilities) { continue; // if the capabilties are null skip to next identity } // run through capabilties and check for chat for (int j = 0; j < capabilities.size(); j++) { IdentityCapability capability = capabilities.get(j); if (null == capability) { continue; // skip null capabilities } if ((capability.mCapability == IdentityCapability.CapabilityID.chat) && (capability.mValue == true)) { chatableIdentities.add(identity); break; } } } // add mobile identity to support 360 chat IdentityCapability capability = new IdentityCapability(); capability.mCapability = IdentityCapability.CapabilityID.chat; capability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(capability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = SocialNetwork.MOBILE.toString(); mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = mobileCapabilities; chatableIdentities.add(mobileIdentity); // end: add mobile identity to support 360 chat return chatableIdentities; } /** * Sends a get my identities request to the server which will be handled * by onProcessCommsResponse once a response comes in. */ private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Send a get available identities request to the backend which will be * handled by onProcessCommsResponse once a response comes in. */ private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Enables or disables the given social network. * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus True if identity should be enabled, false otherwise. */ public void addUiSetIdentityStatus(String network, String identityId, boolean identityStatus) { LogUtils.logD("IdentityEngine.addUiSetIdentityCapabilityStatus()"); IdentityStatusRequest data = new IdentityStatusRequest(); data.mIdentityId = identityId; data.mNetwork = network; data.setIdentityStatus(identityStatus ? Identities.ENABLE_IDENTITY : Identities.DISABLE_IDENTITY); // do not empty reqQueue here, ui can put many at one time addUiRequestToQueue(ServiceUiRequest.SET_IDENTITY_CAPABILITY_STATUS, data); } /** * Add request to validate user credentials for a specified identity. * * @param dryRun True if this is a dry-run. * @param network Name of the network/identity. * @param username User-name for login for this identity. * @param password Password for login for this identity. * @param identityCapabilityStatus Bundle containing capability details for * this identity. */ public void addUiValidateIdentityCredentials(boolean dryRun, String network, String username, String password, Bundle identityCapabilityStatus) { LogUtils.logD("IdentityEngine.addUiValidateIdentityCredentials()"); IdentityValidateCredentialsRequest data = new IdentityValidateCredentialsRequest(); data.mDryRun = dryRun; data.mNetwork = network; data.mPassword = password; data.mUserName = username; data.setCapabilityStatus(identityCapabilityStatus); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.VALIDATE_IDENTITY_CREDENTIALS, data); } /** * Issue any outstanding UI request. * * @param requestType Request to be issued. * @param dara Data associated with the request. */ @Override protected void processUiRequest(ServiceUiRequest requestType, Object data) { LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); switch (requestType) { case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to set capabilities for a given Identity. (Request is not * issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_STATUS); IdentityStatusRequest reqData = (IdentityStatusRequest)data; if (!setReqId(Identities.setIdentityStatus(this, reqData.mNetwork, reqData.mIdentityId, reqData.mIdentityStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } // invalidate 'chat-able' identities cache if (mMyChatableIdentityList != null) { mMyChatableIdentityList.clear(); } } /** * Issue request to validate the user credentials for an Identity. (Request * is not issued if there is currently no connectivity). * * @param data Bundled request data. */ private void executeValidateIdentityCredentialsRequest(Object data) { if (!isConnected()) { return; } newState(State.VALIDATING_IDENTITY_CREDENTIALS); IdentityValidateCredentialsRequest reqData = (IdentityValidateCredentialsRequest)data; if (!setReqId(Identities .validateIdentityCredentials(this, reqData.mDryRun, reqData.mNetwork, reqData.mUserName, reqData.mPassword, null, null, reqData.mStatus))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Process a response received from Server. The response is handled * according to the current IdentityEngine state. * * @param resp The decoded response. */ @Override - protected void processCommsResponse(DecodedResponse resp) { - HttpConnectionThread.logE("GOT RESPONSE!!!!!!!!!!!!!!", "Got response: " + resp.mReqId, null); - - LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); + protected void processCommsResponse(DecodedResponse resp) { + LogUtils.logD("IdentityEngine.processCommsResponse() - resp = " + resp); + // TODO replace this whole block with the response type in the DecodedResponse class in the future! if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { // push msg PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else if (resp.mDataTypes.size() > 0) { // regular response switch (resp.mDataTypes.get(0).getType()) { case BaseDataType.MY_IDENTITY_DATA_TYPE: handleGetMyIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE: handleGetAvailableIdentitiesResponse(resp.mDataTypes); break; case BaseDataType.IDENTITY_CAPABILITY_DATA_TYPE: handleSetIdentityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("IdentityEngine.processCommsResponse DEFAULT should never happened."); break; } - } else { + } else { // responses data list is 0, that means e.g. no identities in an identities response LogUtils.logW("IdentityEngine.processCommsResponse List was empty!"); - } + + if (resp.getResponseType() == DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal()) { + pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); + } else if (resp.getResponseType() == DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal()) { + pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); + } + } // end: replace this whole block with the response type in the DecodedResponse class in the future! } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushResponse(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); sendGetMyIdentitiesRequest(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * Run function called via EngineManager. Should have a UI, Comms response * or timeout event to handle. */ @Override public void run() { LogUtils.logD("IdentityEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logD("IdentityEngine.ResponseOutstanding and processCommsInQueue. mState = " + mState.name()); return; } if (processTimeout()) { return; } if (isUiRequestOutstanding()) { processUiQueue(); } } /** * Change current IdentityEngine state. * * @param newState new state. */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mAvailableIdentityList) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { mAvailableIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_AVAILABLE_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetAvailableIdentitiesResponse complete request."); } /** * Handle Server response to request for available Identities. The response * should be a list of Identity items. The request is completed with * ServiceStatus.SUCCESS or ERROR_UNEXPECTED_RESPONSE if the data-type * retrieved are not Identity items. * * @param data List of BaseDataTypes generated from Server response. */ private void handleGetMyIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } } } pushIdentitiesToUi(ServiceUiRequest.GET_MY_IDENTITIES); LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse complete request."); } /** * Handle Server response to set validate credentials request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleValidateIdentityCredentials(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mStatusList.size() == 1) { bu.putBoolean("status", mStatusList.get(0).mStatus); } else { LogUtils.logW("Status list sould have one item. It has " + mStatusList.size()); bu.putParcelableArrayList(KEY_DATA, mStatusList); } } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * Handle Server response to set capability status request. The response * should be a Status-msg indicating whether the request has succeeded or * failed. The request is completed with the status result (or * ERROR_UNEXPECTED_RESPONSE if the data-type retrieved is not a * Status-msg). * * @param data List of BaseDataTypes generated from Server response. */ private void handleSetIdentityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (item.getType() == BaseDataType.STATUS_MSG_DATA_TYPE) { mStatusList.add((StatusMsg)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * * Pushes the identities retrieved by get my identities or by get available identities * to the ui. * * @param request The request type: either get my identities, or get available identities. */ private void pushIdentitiesToUi(ServiceUiRequest request) { String requestKey = null; ArrayList<Identity> idBundle = null; if (request == ServiceUiRequest.GET_AVAILABLE_IDENTITIES) { requestKey = KEY_AVAILABLE_IDS; idBundle = mAvailableIdentityList; } else { requestKey = KEY_MY_IDS; idBundle = mMyIdentityList; } // send update to 3rd party identities ui if it is up Bundle b = new Bundle(); b.putParcelableArrayList(requestKey, idBundle); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribed()) { uiAgent.sendUnsolicitedUiEvent(request, b); } // end: send update to 3rd party identities ui if it is up } /** * Get Connectivity status from the connection manager. * * @return true True if the connection is active, false otherwise. * */ private boolean isConnected() { int connState = ConnectionManager.getInstance().getConnectionState(); return (connState == ITcpConnectionListener.STATE_CONNECTED); } /** * * Retrieves the filter for the getAvailableIdentities and getMyIdentities * calls. * * @return The identities filter in form of a bundle. * */ private Bundle getIdentitiesFilter() { Bundle b = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); l.add(IdentityCapability.CapabilityID.get_own_status.name()); b.putStringArrayList("capability", l); return b; } @Override public void onConnectionStateChanged(int state) { if (state == ITcpConnectionListener.STATE_CONNECTED) { emptyUiRequestQueue(); sendGetAvailableIdentitiesRequest(); sendGetMyIdentitiesRequest(); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as * possible if we need to issue a request, or we have a resonse waiting. * * @return next run-time. */ @Override public long getNextRunTime() { if (isUiRequestOutstanding()) { return 0; } if (isCommsResponseOutstanding()) { return 0; } return getCurrentTimeout(); } /** {@inheritDoc} */ @Override public void onCreate() { } /** {@inheritDoc} */ @Override public void onDestroy() { } /** {@inheritDoc} */ @Override protected void onRequestComplete() { } /** {@inheritDoc} */ @Override protected void onTimeoutEvent() { } /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Boolean> prepareBoolFilter(Bundle filter) { Map<String, Boolean> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Boolean>(); for (String key : filter.keySet()) { objectFilter.put(key, filter.getBoolean(key)); } } else { objectFilter = null; } return objectFilter; } /** * Generate Map containing String capability filters for m supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, List<String>> prepareStringFilter(Bundle filter) { Map<String, List<String>> returnFilter = null; if (filter != null && filter.keySet().size() > 0) { returnFilter = new Hashtable<String, List<String>>(); for (String key : filter.keySet()) { returnFilter.put(key, filter.getStringArrayList(key)); } } else { returnFilter = null; } return returnFilter; } + + /** + * + * Clears all cached identities that belong to a user (my identities). Available identities will stay untouched as they do not raise any privacy + * concerns and can stay cached. + * + */ + public void clearCachedIdentities() { + if (null != mMyIdentityList) { + mMyIdentityList.clear(); + } + } } diff --git a/src/com/vodafone360/people/service/io/Request.java b/src/com/vodafone360/people/service/io/Request.java index 4d71ecd..fd29e6e 100644 --- a/src/com/vodafone360/people/service/io/Request.java +++ b/src/com/vodafone360/people/service/io/Request.java @@ -1,594 +1,596 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.io.IOException; import java.io.OutputStream; import java.util.Hashtable; import java.util.List; import java.util.Vector; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.io.rpg.RpgMessage; import com.vodafone360.people.service.io.rpg.RpgMessageTypes; import com.vodafone360.people.service.transport.http.HttpConnectionThread; import com.vodafone360.people.service.utils.AuthUtils; import com.vodafone360.people.service.utils.hessian.HessianEncoder; /** * Container class for Requests issued from client to People server via the * transport layer. A request consists of a payload, an identifier for the * engine responsible for handling this request, a request type and a request id * which is generated on creation of the request. */ public class Request { /** * Request types, these are based on the content requested from, or * delivered to, the server, and whether the returned response contains a * type identifier or not. */ public enum Type { COMMON, // Strongly typed ADD_CONTACT, TEXT_RESPONSE_ONLY, CONTACT_CHANGES_OR_UPDATES, CONTACT_DELETE, CONTACT_DETAIL_DELETE, FRIENDSHIP_REQUEST, USER_INVITATION, SIGN_UP, SIGN_IN, RETRIEVE_PUBLIC_KEY, EXPECTING_STATUS_ONLY, GROUP_LIST, STATUS_LIST, STATUS, CONTACT_GROUP_RELATION_LIST, CONTACT_GROUP_RELATIONS, ITEM_LIST_OF_LONGS, PRESENCE_LIST, AVAILABILITY, CREATE_CONVERSATION, SEND_CHAT_MESSAGE, PUSH_MSG, - EXTERNAL_RPG_RESPONSE + EXTERNAL_RPG_RESPONSE, + GET_MY_IDENTITIES, + GET_AVAILABLE_IDENTITIES // response to external RPG request } /* * List of parameters which will be used to generate the AUTH parameter. */ private Hashtable<String, Object> mParameters = new Hashtable<String, Object>(); /** * Name of method on the backend. E.g. identities/getavailableidentities. */ private String mApiMethodName; /** RPG message payload (usually Hessian encoded message body). */ // private byte[] mPayload; /** RPG Message type - as defined above. */ public Type mType; /** Handle of Engine associated with this RPG message. */ public EngineId mEngineId = EngineId.UNDEFINED; // to be used to map request // to appropriate engine /** Whether we use RPG for this message. */ // public boolean mUseRpg = true; /** active flag - set to true once we have actually issued a request */ private boolean mIsActive = false; /** * The timeout set for the request. -1 if not set. */ private long mTimeout = -1; /** * The expiry date calculated when the request gets executed. */ private long mExpiryDate = -1; /** true if the request has expired */ public boolean expired; /** * The timestamp when the request's auth was calculated. */ private long mAuthTimestamp; /** * The timestamp when this request was created. */ private long mCreationTimestamp; /** * <p> * Represents the authentication type that needs to be taken into account * when executing this specific request. There are 3 types of authentication * types: * </p> * <ul> * <li>USE_API: needs the API. These requests are usually requests like * getSessionByCredentials that use application authentication.</li> * <li>USE_RPG: these requests should use the RPG and some of them MUST use * the RPG. Usually, all requests after the auth requests should use the * RPG.</li> * <li>USE_BOTH: some requests like the requests for getting terms and * conditions or privacy statements need to be able to use the RPG or API at * any time of the application lifecycle.</li> * </ul> */ private byte mAuthenticationType; public static final byte USE_API = 1, USE_RPG = 2, USE_BOTH = 3; /** * If true, this method is a fire and forget method and will not expect any * responses to come in. This fact can be used for removing requests from * the queue as soon as they have been sent. */ private boolean mIsFireAndForget; /** RPG message request id. */ private int mRequestId; /** * Constructor used for constructing internal (RPG/API) requests. * * @param apiMethodName The method name of the call, e.g. * "identities/getavailableidentities". * @param type RPG message type. * @param engId The engine ID. Will be used for routing the response to this * request back to the engine that can process it. * @param needsUserAuthentication If true we need to authenticate this * request by providing the session in the auth. This requires * the user to be logged in. * @param isFireAndForget True if the request is a fire and forget request. * @param timeout the timeout in milliseconds before the request throws a * timeout exception */ public Request(String apiMethodName, Type type, EngineId engineId, boolean isFireAndForget, long timeout) { mType = type; // TODO find out a type yourself? mEngineId = engineId; mApiMethodName = apiMethodName; mIsFireAndForget = isFireAndForget; mCreationTimestamp = System.currentTimeMillis(); mTimeout = timeout; if ((type == Type.RETRIEVE_PUBLIC_KEY) || (type == Type.SIGN_UP) || (type == Type.STATUS) || (type == Type.SIGN_IN)) { // we need to register, sign in, get t&c's etc. so the request needs // to happen without // user auth mAuthenticationType = USE_API; } else if (type == Type.TEXT_RESPONSE_ONLY) { // t&c or privacy mAuthenticationType = USE_BOTH; } else { // all other requests should use the RPG by default mAuthenticationType = USE_RPG; } } /** * Constructor used for constructing an external request used for fetching * e.g. images. * * @param externalUrl The external URL of the object to fetch. * @param urlParams THe parameters to add to the URL of this request. * @param engineId The ID of the engine that will be called back once the * response for this request comes in. */ public Request(String externalUrl, String urlParams, EngineId engineId) { mType = Type.EXTERNAL_RPG_RESPONSE; mEngineId = engineId; mApiMethodName = ""; mIsFireAndForget = false; mCreationTimestamp = System.currentTimeMillis(); mParameters = new Hashtable<String, Object>(); mParameters.put("method", "GET"); mParameters.put("url", externalUrl + urlParams); mAuthenticationType = USE_RPG; } /** * Is request active - i.e has it been issued * * @return true if request is active */ public boolean isActive() { return mIsActive; } /** * <p> * Sets whether this request is active or not. An active request is a * request that is currently being sent to the server and awaiting a * response. * </p> * <p> * The reason is that an active request should not be sent twice. * </p> * * @param isActive True if the request is active, false otherwise. */ public void setActive(boolean isActive) { mIsActive = isActive; } /** * Returns a description of the contents of this object * * @return The description */ @Override public String toString() { StringBuilder sb = new StringBuilder("Request [mEngineId="); sb.append(mEngineId); sb.append(", mIsActive="); sb.append(mIsActive); sb.append(", mTimeout="); sb.append(mTimeout); sb.append(", mReqId="); sb.append(mRequestId); sb.append(", mType="); sb.append(mType); sb.append(", mNeedsUserAuthentication="); sb.append(mAuthenticationType); sb.append(", mExpired="); sb.append(expired); sb.append(", mDate="); sb.append(mExpiryDate); sb.append("]\n"); sb.append(mParameters); return sb.toString(); } /** * Adds element to list of params * * @param name key name for object to be added to parameter list * @param nv object which will be added */ public void addData(String name, Hashtable<String, ?> nv) { mParameters.put(name, nv); } /** * Adds element to list of params * * @param name key name for object to be added to parameter list * @param value object which will be added */ public void addData(String name, Vector<Object> value) { mParameters.put(name, value); } /** * Adds element to list of params * * @param name key name for object to be added to parameter list * @param value object which will be added */ public void addData(String name, List<String> value) { mParameters.put(name, value); } /** * Adds byte array to parameter list * * @param varName name * @param value byte[] array to be added */ public void addData(String varName, byte[] value) { mParameters.put(varName, value); } /** * Create new NameValue and adds it to list of params * * @param varName name * @param value string value */ public void addData(String varName, String value) { mParameters.put(varName, value); } /** * Create new NameValue and adds it to list of params * * @param varName name * @param value Long value */ public void addData(String varName, Long value) { mParameters.put(varName, value); } /** * Create new NameValue and adds it to list of params * * @param varName name * @param value Integer value */ public void addData(String varName, Integer value) { mParameters.put(varName, value); } /** * Create new NameValue and adds it to list of params * * @param varName name * @param value Boolean value */ public void addData(String varName, Boolean value) { mParameters.put(varName, value); } /** * Returns a Hashtable containing current request parameter list. * * @return params The parameters that were added to this backend request. */ /* * public Hashtable<String, Object> getParameters() { return mParameters; } */ /** * Returns the authentication type of this request. This can be one of the * following: USE_API, which must be used for authentication requests that * need application authentication, USE_RPG, useful for requests against the * API that need user authentication and want to profit from the mobile * enhancements of the RPG, or USE_BOTH for requests that need to be able to * be used on the API or RPG. These requests are for example the Terms and * Conditions requests which need to be accessible from anywhere in the * client. * * @return True if this method requires user authentication or a valid * session to be more precise. False is returned if the method only * needs application authentication. */ public byte getAuthenticationType() { return mAuthenticationType; } /** * Gets the request ID of this request. * * @return The unique request ID for this request. */ public int getRequestId() { return mRequestId; } /** * Sets the request ID for this request. * * @param requestId The request ID to set. */ public void setRequestId(int requestId) { mRequestId = requestId; } /** * Gets the time stamp when this request's hash was calculated. * * @return The time stamp representing the creation date of this request. */ public long getAuthTimestamp() { return mAuthTimestamp; } /** * Gets the time stamp when this request was created. * * @return The time stamp representing the creation date of this request. */ public long getCreationTimestamp() { return mCreationTimestamp; } /** * Gets the set timeout. * * @return the timeout in milliseconds, -1 if not set. */ public long getTimeout() { return mTimeout; } /** * Gets the calculated expiry date. * * @return the expiry date in milliseconds, -1 if not set. */ public long getExpiryDate() { return mExpiryDate; } /** * Overwrites the timestamp if we need to wait one more second due to an * issue on the backend. * * @param timestamp The timestamp in milliseconds(!) to overwrite with. */ /* public void overwriteTimetampBecauseOfBadSessionErrorOnBackend(long timestamp) { mAuthTimestamp = timestamp; if (null != mParameters) { if (null != mParameters.get("timestamp")) { String ts = "" + (timestamp / 1000); mParameters.put("timestamp", ts); } } } */ /** * Returns the API call this request will use. * * @return The API method name this request will call. */ public String getApiMethodName() { return mApiMethodName; } /** * Returns true if the method is a fire and forget method. Theses methods * can be removed from the request queue as soon as they have been sent out. * * @return True if the request is fire and forget, false otherwise. */ public boolean isFireAndForget() { return mIsFireAndForget; } /** * Serializes the request's data structure to the passed output stream * enabling the connection to easily prepare one or multiple) requests. * * @param os The output stream to serialise this request to. * @param writeRpgHeader If true the RPG header is written. */ public void writeToOutputStream(OutputStream os, boolean writeRpgHeader) { if (null == os) { return; } byte[] body; calculateAuth(); try { body = makeBody(); if (!writeRpgHeader) { os.write(body); // writing to the api directly return; } } catch (IOException ioe) { HttpConnectionThread.logE("Request.writeToOutputStream()", "Failed writing standard API request: " + mRequestId, ioe); return; } int requestType = 0; if (mType == Request.Type.PRESENCE_LIST) { requestType = RpgMessageTypes.RPG_GET_PRESENCE; } else if (mType == Request.Type.AVAILABILITY) { requestType = RpgMessageTypes.RPG_SET_AVAILABILITY; } else if (mType == Request.Type.CREATE_CONVERSATION) { requestType = RpgMessageTypes.RPG_CREATE_CONV; } else if (mType == Request.Type.SEND_CHAT_MESSAGE) { requestType = RpgMessageTypes.RPG_SEND_IM; } else if (mType == Request.Type.EXTERNAL_RPG_RESPONSE) { requestType = RpgMessageTypes.RPG_EXT_REQ; } else { requestType = RpgMessageTypes.RPG_INT_REQ; } byte[] message = RpgMessage.createRpgMessage(body, requestType, mRequestId); try { os.write(message); } catch (IOException ioe) { HttpConnectionThread.logE("Request.writeToOutputStream()", "Failed writing RPG request: " + mRequestId, ioe); } } /** * Creates the body of the request using the parameter list. * * @return payload The hessian encoded payload of this request body. * @throws IOException Thrown if anything goes wrong using the hessian * encoder. */ private byte[] makeBody() throws IOException { // XXX this whole method needs to go or at least be changed into a // bytearray outputstream byte[] payload = HessianEncoder.createHessianByteArray(mApiMethodName, mParameters); if (payload == null) { return null; } payload[1] = (byte)1; // TODO we need to change this if we want to use a // baos payload[2] = (byte)0; return payload; } /** * Gets the auth of this request. Prior to the the * writeToOutputStream()-method must have been called. * * @return The auth of this request or null if it was not calculated before. */ public String getAuth() { return (String)mParameters.get("auth"); } /** * Calculate the Auth value for this Requester. TODO: Throttle by * timestamp/function to prevent automatic backend log out */ private void calculateAuth() { String ts = null; if (null != mParameters) { ts = (String)mParameters.get("timestamp"); } if (null == ts) { ts = "" + (System.currentTimeMillis() / 1000); } AuthSessionHolder session = LoginEngine.getSession(); if (session != null) { addData("auth", SettingsManager.getProperty(Settings.APP_KEY_ID) + "::" + session.sessionID + "::" + ts); } else { addData("auth", SettingsManager.getProperty(Settings.APP_KEY_ID) + "::" + ts); } addData("auth", AuthUtils.calculateAuth(mApiMethodName, mParameters, ts, session)); /** * if (mNeedsUserAuthentication) { addData("auth", * AuthUtils.calculateAuth(mApiMethodName, mParameters, ts, session)); } * else { // create the final auth without the session addData("auth", * AuthUtils.calculateAuth(mApiMethodName, mParameters, ts, null)); } */ } /** * Calculates the expiry date based on the timeout. TODO: should have * instead an execute() method to call when performing the request. it would * set the request to active, calculates the expiry date, etc... */ public void calculateExpiryDate() { if (mTimeout > 0) { mExpiryDate = System.currentTimeMillis() + mTimeout; } } } diff --git a/src/com/vodafone360/people/service/io/ResponseQueue.java b/src/com/vodafone360/people/service/io/ResponseQueue.java index 90901d2..d686ed7 100644 --- a/src/com/vodafone360/people/service/io/ResponseQueue.java +++ b/src/com/vodafone360/people/service/io/ResponseQueue.java @@ -1,252 +1,248 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io; import java.util.ArrayList; import java.util.List; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.LogUtils; /** * Queue of responses received from server. These may be either responses to * requests issued by the People client or unsolicited ('Push') messages. The * content of these Responses will have already been decoded by the * DecoderThread and converted to data-types understood by the People Client. */ public class ResponseQueue { /** * The list of responses held by this queue. An array-list of Responses. */ private final List<DecodedResponse> mResponses = new ArrayList<DecodedResponse>(); /** * The engine manager holding the various engines to cross check where * responses belong to. */ private EngineManager mEngMgr = null; /** * Class encapsulating a decoded response from the server A Response * contains; a request id which should match a request id from a request * issued by the People Client (responses to non-RPG requests or * non-solicited messages will not have a request id), the request data, a * list of decoded BaseDataTypes generated from the response content and an * engine id informing the framework which engine the response should be * routed to. */ public static class DecodedResponse { public static enum ResponseType { /** An unknown response in case anything went wrong. */ UNKNOWN, /** A response for a request that timed out. */ SERVER_ERROR, /** A response that timed out before it arrived from the server. */ TIMED_OUT_RESPONSE, /** Represents a push message that was pushed by the server */ PUSH_MESSAGE, /** The response type for available identities. */ GET_AVAILABLE_IDENTITIES_RESPONSE, /** The response type for my identities. */ GET_MY_IDENTITIES_RESPONSE, /** The response type for get activities calls. */ GET_ACTIVITY_RESPONSE, /** The response type for get session by credentials calls. */ LOGIN_RESPONSE, /** The response type for get contacts changes calls. */ GET_CONTACTCHANGES_RESPONSE, /** The response type for get get me calls. */ GETME_RESPONSE, - /** The response type for get my identities calls. */ - GET_MY_IDENTITY_RESPONSE, - /** The response type for get available identities calls. */ - GET_AVAILABLE_IDENTITY_RESPONSE, /** The response type for get contact group relation calls. */ GET_CONTACT_GROUP_RELATIONS_RESPONSE, /** The response type for get groups calls. */ GET_GROUPS_RESPONSE, /** The response type for add contact calls. */ ADD_CONTACT_RESPONSE, /** The response type for signup user crypted calls. */ SIGNUP_RESPONSE, /** The response type for get public key calls. */ RETRIEVE_PUBLIC_KEY_RESPONSE, /** The response type for delete contacts calls. */ DELETE_CONTACT_RESPONSE, /** The response type for delete contact details calls. */ DELETE_CONTACT_DETAIL_RESPONSE, /** The response type for get presence calls. */ GET_PRESENCE_RESPONSE, /** The response type for create conversation calls. */ CREATE_CONVERSATION_RESPONSE; // TODO add more types here and remove them from the BaseDataType. Having them in ONE location is better than in dozens!!! } /** The type of the response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ private int mResponseType; /** The request ID the response came in for. */ public Integer mReqId; /** The response items (e.g. identities of a getAvailableIdentities call) to store for the response. */ public List<BaseDataType> mDataTypes = new ArrayList<BaseDataType>(); /** The ID of the engine the response should be worked off in. */ public EngineId mSource; /** * Constructs a response object with request ID, the data and the engine * ID the response belongs to. * * @param reqId The corresponding request ID for the response. * @param data The data of the response. * @param source The originating engine ID. * @param responseType The response type. Values can be found in Response.ResponseType. * */ public DecodedResponse(Integer reqId, List<BaseDataType> data, EngineId source, final int responseType) { mReqId = reqId; mDataTypes = data; mSource = source; mResponseType = responseType; } /** * The response type for this response. The types are defined in Response.ResponseType. * * @return The response type of this response (e.g. GET_AVAILABLE_IDENTITIES_RESPONSE). */ public int getResponseType() { return mResponseType; } } /** * Protected constructor to highlight the singleton nature of this class. */ protected ResponseQueue() { } /** * Gets an instance of the ResponseQueue as part of the singleton pattern. * * @return The instance of ResponseQueue. */ public static ResponseQueue getInstance() { return ResponseQueueHolder.rQueue; } /** * Use Initialization on demand holder pattern */ private static class ResponseQueueHolder { private static final ResponseQueue rQueue = new ResponseQueue(); } /** * Adds a response item to the queue. * * @param reqId The request ID to add the response for. * @param data The response data to add to the queue. * @param source The corresponding engine that fired off the request for the * response. */ public void addToResponseQueue(final DecodedResponse response) { synchronized (QueueManager.getInstance().lock) { ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.UNKNOWN_DATA_TYPE, response.mDataTypes); if (status == ServiceStatus.ERROR_INVALID_SESSION) { EngineManager em = EngineManager.getInstance(); if (em != null) { LogUtils.logE("Logging out the current user because of invalide session"); em.getLoginEngine().logoutAndRemoveUser(); return; } } mResponses.add(response); final RequestQueue rQ = RequestQueue.getInstance(); rQ.removeRequest(response.mReqId); mEngMgr = EngineManager.getInstance(); if (mEngMgr != null) { mEngMgr.onCommsInMessage(response.mSource); } } } /** * Retrieves the next response in the list if there is one. * * @param source The originating engine id that requested this response. * @return Response The first response that matches the given engine or null * if no response was found. */ public DecodedResponse getNextResponse(EngineId source) { DecodedResponse resp = null; for (int i = 0; i < mResponses.size(); i++) { resp = mResponses.get(i); if (resp.mSource == source) { mResponses.remove(i); if (source != null) { LogUtils.logV("ResponseQueue.getNextResponse() Returning a response to engine[" + source.name() + "]"); } return resp; } } return null; } /** * Get number of items currently in the response queue. * * @return number of items currently in the response queue. */ private int responseCount() { return mResponses.size(); } /** * Test if we have response for the specified request id. * * @param reqId Request ID. * @return true If we have a response for this ID. */ protected synchronized boolean responseExists(int reqId) { boolean exists = false; for (int i = 0; i < responseCount(); i++) { if (mResponses.get(i).mReqId != null && mResponses.get(i).mReqId.intValue() == reqId) { exists = true; break; } } return exists; } } diff --git a/src/com/vodafone360/people/service/io/api/Identities.java b/src/com/vodafone360/people/service/io/api/Identities.java index 0bd324f..5d898ce 100644 --- a/src/com/vodafone360/people/service/io/api/Identities.java +++ b/src/com/vodafone360/people/service/io/api/Identities.java @@ -1,214 +1,214 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.io.api; import java.util.Hashtable; import java.util.List; import java.util.Map; import com.vodafone360.people.Settings; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.login.LoginEngine; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.utils.LogUtils; /** * Implementation of Now+ Identities APIs (used for access to 3rd party accounts * such as Facebook). */ public class Identities { private final static String FUNCTION_GET_AVAILABLE_IDENTITIES = "identities/getavailableidentities"; private final static String FUNCTION_GET_MY_IDENTITIES = "identities/getmyidentities"; // AA private final static String FUNCTION_SET_IDENTITY_CAPABILITY_STATUS = // "identities/setidentitycapabilitystatus"; private final static String FUNCTION_SET_IDENTITY_STATUS = "identities/setidentitystatus"; private final static String FUNCTION_VALIDATE_IDENTITY_CREDENTIALS = "identities/validateidentitycredentials"; public final static String ENABLE_IDENTITY = "enable"; public final static String DISABLE_IDENTITY = "disable"; //public final static String SUSPENDED_IDENTITY = "suspended"; /** * Implementation of identities/getavailableidentities API. Parameters are; * [auth], Map<String, List<String>> filterlist [opt] * * @param engine handle to IdentitiesEngine * @param filterlist List of filters the get identities request is filtered * against. * @return request id generated for this request */ public static int getAvailableIdentities(BaseEngine engine, Map<String, List<String>> filterlist) { if (LoginEngine.getSession() == null) { LogUtils.logE("Identities.getAvailableIdentities() Invalid session, return -1"); return -1; } - Request request = new Request(FUNCTION_GET_AVAILABLE_IDENTITIES, Request.Type.COMMON, + Request request = new Request(FUNCTION_GET_AVAILABLE_IDENTITIES, Request.Type.GET_AVAILABLE_IDENTITIES, engine.engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); if (filterlist != null) { request.addData("filterlist", ApiUtils.createHashTable(filterlist)); } QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } /** * Implementation of identities/getmyidentities API. Parameters are; [auth], * Map<String, List<String>> filterlist [opt] * * @param engine handle to IdentitiesEngine * @param filterlist List of filters the get identities request is filtered * against. * @return request id generated for this request */ public static int getMyIdentities(BaseEngine engine, Map<String, List<String>> filterlist) { if (LoginEngine.getSession() == null) { LogUtils.logE("Identities.getMyIdentities() Invalid session, return -1"); return -1; } - Request request = new Request(FUNCTION_GET_MY_IDENTITIES, Request.Type.COMMON, engine + Request request = new Request(FUNCTION_GET_MY_IDENTITIES, Request.Type.GET_MY_IDENTITIES, engine .engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); if (filterlist != null) { request.addData("filterlist", ApiUtils.createHashTable(filterlist)); } QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } /** * @param engine * @param network * @param identityid * @param identityStatus * @return */ public static int setIdentityStatus(BaseEngine engine, String network, String identityid, String identityStatus) { if (LoginEngine.getSession() == null) { LogUtils.logE("Identities.setIdentityStatus() Invalid session, return -1"); return -1; } if (identityid == null) { LogUtils.logE("Identities.setIdentityStatus() identityid cannot be NULL"); return -1; } if (network == null) { LogUtils.logE("Identities.setIdentityStatus() network cannot be NULL"); return -1; } if (identityStatus == null) { LogUtils.logE("Identities.setIdentityStatus() identity status cannot be NULL"); return -1; } Request request = new Request(FUNCTION_SET_IDENTITY_STATUS, Request.Type.EXPECTING_STATUS_ONLY, engine.engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); request.addData("network", network); request.addData("identityid", identityid); request.addData("status", identityStatus); QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } /** * Implementation of identities/validateidentitycredentials API. Parameters * are; [auth], Boolean dryrun [opt], String network [opt], String username, * String password, String server [opt], String contactdetail [opt], Map * identitycapabilitystatus [opt] * * @param engine handle to IdentitiesEngine * @param dryrun Whether this is a dry-run request. * @param network Name of network. * @param username User-name. * @param password Password. * @param server * @param contactdetail * @param identitycapabilitystatus Capabilities for this identity/network. * @return request id generated for this request */ public static int validateIdentityCredentials(BaseEngine engine, Boolean dryrun, String network, String username, String password, String server, String contactdetail, Map<String, Boolean> identitycapabilitystatus) { if (LoginEngine.getSession() == null) { LogUtils.logE("Identities.validateIdentityCredentials() Invalid session, return -1"); return -1; } if (network == null) { LogUtils.logE("Identities.validateIdentityCredentials() network cannot be NULL"); return -1; } if (username == null) { LogUtils.logE("Identities.validateIdentityCredentials() username cannot be NULL"); return -1; } if (password == null) { LogUtils.logE("Identities.validateIdentityCredentials() password cannot be NULL"); return -1; } Request request = new Request(FUNCTION_VALIDATE_IDENTITY_CREDENTIALS, Request.Type.EXPECTING_STATUS_ONLY, engine.engineId(), false, Settings.API_REQUESTS_TIMEOUT_IDENTITIES); if (dryrun != null) { request.addData("dryrun", dryrun); } request.addData("network", network); request.addData("username", username); request.addData("password", password); if (server != null) { request.addData("server", server); } if (contactdetail != null) { request.addData("contactdetail", contactdetail); } if (identitycapabilitystatus != null) { request.addData("identitycapabilitystatus", new Hashtable<String, Object>( identitycapabilitystatus)); } QueueManager queue = QueueManager.getInstance(); int requestId = queue.addRequest(request); queue.fireQueueStateChanged(); return requestId; } } diff --git a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java index 3663a23..e8aa994 100644 --- a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java +++ b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java @@ -1,554 +1,556 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.utils.hessian; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Vector; import java.util.zip.GZIPInputStream; import com.caucho.hessian.micro.MicroHessianInput; import com.vodafone360.people.datatypes.ActivityItem; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactChanges; import com.vodafone360.people.datatypes.ContactDetailDeletion; import com.vodafone360.people.datatypes.ContactListResponse; import com.vodafone360.people.datatypes.Conversation; import com.vodafone360.people.datatypes.ExternalResponseObject; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.ItemList; import com.vodafone360.people.datatypes.PresenceList; import com.vodafone360.people.datatypes.PublicKeyDetails; import com.vodafone360.people.datatypes.PushAvailabilityEvent; import com.vodafone360.people.datatypes.PushChatConversationEvent; import com.vodafone360.people.datatypes.PushChatMessageEvent; import com.vodafone360.people.datatypes.PushClosedConversationEvent; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.SimpleText; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.datatypes.UserProfile; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.service.io.ResponseQueue.DecodedResponse; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.io.rpg.RpgPushMessage; import com.vodafone360.people.utils.CloseUtils; import com.vodafone360.people.utils.LogUtils; /** * Hessian decoding . TODO: Currently casting every response to a Map, losing * for example push events "c0" which only contains a string. This may need a * fix. */ public class HessianDecoder { private static final String KEY_ACTIVITY_LIST = "activitylist"; private static final String KEY_AVAILABLE_IDENTITY_LIST = "availableidentitylist"; private static final String KEY_CONTACT_ID_LIST = "contactidlist"; private static final String KEY_CONTACT_LIST = "contactlist"; private static final String KEY_IDENTITY_LIST = "identitylist"; private static final String KEY_SESSION = "session"; private static final String KEY_USER_PROFILE = "userprofile"; private static final String KEY_USER_PROFILE_LIST = "userprofilelist"; /** * The MicroHessianInput is here declared as member and will be reused * instead of making new instances on every need */ private MicroHessianInput mMicroHessianInput = new MicroHessianInput(); /** * * Parse Hessian encoded byte array placing parsed contents into List. * * @param requestId The request ID that the response was received for. * @param data byte array containing Hessian encoded data * @param type Event type Shows whether we have a push or common message type. * @param isZipped True if the response is gzipped, otherwise false. * @param engineId The engine ID the response should be reported back to. * * @return The response containing the decoded objects. * * @throws IOException Thrown if there is something wrong with reading the (gzipped) hessian encoded input stream. * */ public DecodedResponse decodeHessianByteArray(int requestId, byte[] data, Request.Type type, boolean isZipped, EngineId engineId) throws IOException { InputStream is = null; InputStream bis = null; if (isZipped == true) { LogUtils.logV("HessianDecoder.decodeHessianByteArray() Handle zipped data"); bis = new ByteArrayInputStream(data); is = new GZIPInputStream(bis, data.length); } else { LogUtils.logV("HessianDecoder.decodeHessianByteArray() Handle non-zipped data"); is = new ByteArrayInputStream(data); } DecodedResponse response = null; mMicroHessianInput.init(is); LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); try { response = decodeResponse(is, requestId, type, isZipped, engineId); } catch (IOException e) { LogUtils.logE("HessianDecoder.decodeHessianByteArray() " + "IOException during decodeResponse", e); } CloseUtils.close(bis); CloseUtils.close(is); return response; } @SuppressWarnings("unchecked") public Hashtable<String, Object> decodeHessianByteArrayToHashtable(byte[] data) throws IOException { InputStream is = new ByteArrayInputStream(data); mMicroHessianInput.init(is); Object obj = null; obj = mMicroHessianInput.decodeTag(); if (obj instanceof Hashtable) { return (Hashtable<String, Object>)obj; } else { return null; } } /** * * * * @param is * @param requestId * @param type * @param isZipped * @param engineId * * @return * * @throws IOException */ @SuppressWarnings("unchecked") private DecodedResponse decodeResponse(InputStream is, int requestId, Request.Type type, boolean isZipped, EngineId engineId) throws IOException { boolean usesReplyTag = false; int responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); List<BaseDataType> resultList = new ArrayList<BaseDataType>(); mMicroHessianInput.init(is); // skip start int tag = is.read(); // initial map tag or fail if (tag == 'r') { // reply / response is.read(); // read major and minor is.read(); tag = is.read(); // read next tag usesReplyTag = true; } if (tag == -1) { return null; } // check for fail // read reason string and throw exception if (tag == 'f') { ServerError zybErr = new ServerError(mMicroHessianInput.readFault().errString()); resultList.add(zybErr); DecodedResponse decodedResponse = new DecodedResponse(requestId, resultList, engineId, DecodedResponse.ResponseType.SERVER_ERROR.ordinal()); return decodedResponse; } // handle external response // this is not wrapped up in a hashtable if (type == Request.Type.EXTERNAL_RPG_RESPONSE) { LogUtils.logV("HessianDecoder.decodeResponse() EXTERNAL_RPG_RESPONSE"); if (tag != 'I') { LogUtils.logE("HessianDecoder.decodeResponse() " + "tag!='I' Unexpected Hessian type:" + tag); } parseExternalResponse(resultList, is, tag); DecodedResponse decodedResponse = new DecodedResponse(requestId, resultList, engineId, DecodedResponse.ResponseType.SERVER_ERROR.ordinal()); return decodedResponse; } // internal response: should contain a Map type - i.e. Hashtable if (tag != 'M') { LogUtils .logE("HessianDecoder.decodeResponse() tag!='M' Unexpected Hessian type:" + tag); throw new IOException("Unexpected Hessian type"); - } else if ((type != Request.Type.COMMON) && (type != Request.Type.SIGN_IN)) { - // get initial hash table - // TODO: we cast every response to a Map, losing e.g. push event - // "c0" which only contains a string - to fix - Hashtable<String, Object> hash = (Hashtable<String, Object>)mMicroHessianInput - .decodeType(tag); - responseType = decodeResponseByRequestType(resultList, hash, type); - } else { // if we have a common request + } else if ((type == Request.Type.COMMON) || (type == Request.Type.SIGN_IN) || // if we have a common request or sign in request + (type == Request.Type.GET_MY_IDENTITIES) || (type == Request.Type.GET_AVAILABLE_IDENTITIES)) { Hashtable<String, Object> map = (Hashtable<String, Object>)mMicroHessianInput .readHashMap(tag); if (null == map) { return null; } if (map.containsKey(KEY_SESSION)) { AuthSessionHolder auth = new AuthSessionHolder(); Hashtable<String, Object> authHash = (Hashtable<String, Object>)map .get(KEY_SESSION); resultList.add(auth.createFromHashtable(authHash)); responseType = DecodedResponse.ResponseType.LOGIN_RESPONSE.ordinal(); } else if (map.containsKey(KEY_CONTACT_LIST)) { // contact list getContacts(resultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); responseType = DecodedResponse.ResponseType.GET_CONTACTCHANGES_RESPONSE.ordinal(); } else if (map.containsKey(KEY_USER_PROFILE_LIST)) { Vector<Hashtable<String, Object>> upVect = (Vector<Hashtable<String, Object>>)map .get(KEY_USER_PROFILE_LIST); for (Hashtable<String, Object> obj : upVect) { resultList.add(UserProfile.createFromHashtable(obj)); } responseType = DecodedResponse.ResponseType.GETME_RESPONSE.ordinal(); } else if (map.containsKey(KEY_USER_PROFILE)) { Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map .get(KEY_USER_PROFILE); resultList.add(UserProfile.createFromHashtable(userProfileHash)); responseType = DecodedResponse.ResponseType.GETME_RESPONSE.ordinal(); - } else if ((map.containsKey(KEY_IDENTITY_LIST)) + } else if ((map.containsKey(KEY_IDENTITY_LIST)) // we have identity items in the map which we can parse || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { int identityType = 0; Vector<Hashtable<String, Object>> idcap = null; if (map.containsKey(KEY_IDENTITY_LIST)) { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); identityType = BaseDataType.MY_IDENTITY_DATA_TYPE; - responseType = DecodedResponse.ResponseType.GET_MY_IDENTITY_RESPONSE.ordinal(); + responseType = DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal(); } else { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); identityType = BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE; - responseType = DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITY_RESPONSE.ordinal(); + responseType = DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal(); } for (Hashtable<String, Object> obj : idcap) { Identity id = new Identity(identityType); resultList.add(id.createFromHashtable(obj)); } - + } else if (type == Request.Type.GET_AVAILABLE_IDENTITIES) { // we have an available identities response, but it is empty + responseType = DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal(); + } else if (type == Request.Type.GET_MY_IDENTITIES) { // we have a my identities response, but it is empty + responseType = DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal(); } else if (map.containsKey(KEY_ACTIVITY_LIST)) { Vector<Hashtable<String, Object>> activityList = (Vector<Hashtable<String, Object>>)map .get(KEY_ACTIVITY_LIST); for (Hashtable<String, Object> obj : activityList) { resultList.add(ActivityItem.createFromHashtable(obj)); } responseType = DecodedResponse.ResponseType.GET_ACTIVITY_RESPONSE.ordinal(); } + } else if ((type != Request.Type.COMMON) && (type != Request.Type.SIGN_IN)) { + // get initial hash table + // TODO: we cast every response to a Map, losing e.g. push event + // "c0" which only contains a string - to fix + Hashtable<String, Object> hash = (Hashtable<String, Object>)mMicroHessianInput + .decodeType(tag); + responseType = decodeResponseByRequestType(resultList, hash, type); } if (usesReplyTag) { is.read(); // read the last 'z' } DecodedResponse decodedResponse = new DecodedResponse(requestId, resultList, engineId, responseType); return decodedResponse; } private void parseExternalResponse(List<BaseDataType> clist, InputStream is, int tag) throws IOException { mMicroHessianInput.init(is); ExternalResponseObject resp = new ExternalResponseObject(); // we already read the 'I' in the decodeResponse()-method // now we read and check the response code if (mMicroHessianInput.readInt(tag) != 200) { return; } try { resp.mMimeType = mMicroHessianInput.readString(); } catch (IOException ioe) { LogUtils.logE("Failed to parse hessian string."); return; } // read data - could be gzipped try { resp.mBody = mMicroHessianInput.readBytes(); } catch (IOException ioe) { LogUtils.logE("Failed to read bytes."); return; } LogUtils.logI("HessianDecoder.parseExternalResponse()" + " Parsed external object with length: " + resp.mBody.length); clist.add(resp); } /** * * Parses the hashtables retrieved from the hessian payload that came from the server and * returns a type for it. * * @param clist The list that will be populated with the data types. * @param hash The hash table that contains the parsed date returned by the backend. * @param type The type of the request that was sent, e.g. get contacts changes. * * @return The type of the response that was parsed (to be found in DecodedResponse.ResponseType). * */ private int decodeResponseByRequestType(List<BaseDataType> clist, Hashtable<String, Object> hash, Request.Type type) { int responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); switch (type) { case CONTACT_CHANGES_OR_UPDATES: responseType = DecodedResponse.ResponseType.GET_CONTACTCHANGES_RESPONSE.ordinal(); // create ContactChanges ContactChanges contChanges = new ContactChanges(); contChanges = contChanges.createFromHashtable(hash); clist.add(contChanges); break; case ADD_CONTACT: clist.add(Contact.createFromHashtable(hash)); responseType = DecodedResponse.ResponseType.ADD_CONTACT_RESPONSE.ordinal(); break; case SIGN_UP: clist.add(Contact.createFromHashtable(hash)); responseType = DecodedResponse.ResponseType.SIGNUP_RESPONSE.ordinal(); break; case RETRIEVE_PUBLIC_KEY: // AA define new object type clist.add(PublicKeyDetails.createFromHashtable(hash)); responseType = DecodedResponse.ResponseType.RETRIEVE_PUBLIC_KEY_RESPONSE.ordinal(); break; case CONTACT_DELETE: ContactListResponse cresp = new ContactListResponse(); cresp.createFromHashTable(hash); // add ids @SuppressWarnings("unchecked") Vector<Long> contactIds = (Vector<Long>)hash.get(KEY_CONTACT_ID_LIST); if (contactIds != null) { for (Long cid : contactIds) { cresp.mContactIdList.add((cid).intValue()); } } clist.add(cresp); responseType = DecodedResponse.ResponseType.DELETE_CONTACT_RESPONSE.ordinal(); break; case CONTACT_DETAIL_DELETE: ContactDetailDeletion cdel = new ContactDetailDeletion(); clist.add(cdel.createFromHashtable(hash)); responseType = DecodedResponse.ResponseType.DELETE_CONTACT_DETAIL_RESPONSE.ordinal(); break; case CONTACT_GROUP_RELATION_LIST: ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); groupRelationList.populateFromHashtable(hash); clist.add(groupRelationList); responseType = DecodedResponse.ResponseType.GET_CONTACT_GROUP_RELATIONS_RESPONSE.ordinal(); break; case CONTACT_GROUP_RELATIONS: ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); groupRelationsList.populateFromHashtable(hash); clist.add(groupRelationsList); responseType = DecodedResponse.ResponseType.GET_CONTACT_GROUP_RELATIONS_RESPONSE.ordinal(); break; case GROUP_LIST: ItemList zyblist = new ItemList(ItemList.Type.group_privacy); zyblist.populateFromHashtable(hash); clist.add(zyblist); responseType = DecodedResponse.ResponseType.GET_GROUPS_RESPONSE.ordinal(); break; case ITEM_LIST_OF_LONGS: ItemList listOfLongs = new ItemList(ItemList.Type.long_value); listOfLongs.populateFromHashtable(hash); clist.add(listOfLongs); responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); // TODO break; - case STATUS_LIST: + case STATUS_LIST: // TODO status and status list are used by many requests as a type. each request should have its own type however! ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); zybstatlist.populateFromHashtable(hash); clist.add(zybstatlist); responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); // TODO break; + case STATUS: + StatusMsg s = new StatusMsg(); + s.mStatus = true; + clist.add(s); + responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); // TODO + break; case TEXT_RESPONSE_ONLY: Object val = hash.get("result"); if (val != null && val instanceof String) { SimpleText txt = new SimpleText(); txt.addText((String)val); clist.add(txt); } responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); // TODO break; case EXPECTING_STATUS_ONLY: StatusMsg statMsg = new StatusMsg(); clist.add(statMsg.createFromHashtable(hash)); responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); // TODO break; - - case STATUS: - StatusMsg s = new StatusMsg(); - s.mStatus = true; - clist.add(s); - responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal(); // TODO - break; - case PRESENCE_LIST: PresenceList mPresenceList = new PresenceList(); mPresenceList.createFromHashtable(hash); clist.add(mPresenceList); responseType = DecodedResponse.ResponseType.GET_PRESENCE_RESPONSE.ordinal(); break; case PUSH_MSG: // parse content of RPG Push msg parsePushMessage(clist, hash); responseType = DecodedResponse.ResponseType.PUSH_MESSAGE.ordinal(); break; case CREATE_CONVERSATION: Conversation mConversation = new Conversation(); mConversation.createFromHashtable(hash); clist.add(mConversation); responseType = DecodedResponse.ResponseType.CREATE_CONVERSATION_RESPONSE.ordinal(); break; default: LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" + type.name() + "]"); } return responseType; } private void getContacts(List<BaseDataType> clist, Vector<?> cont) { for (Object obj : cont) { @SuppressWarnings("unchecked") Hashtable<String, Object> hash = (Hashtable<String, Object>)obj; clist.add(Contact.createFromHashtable(hash)); } } private void parsePushMessage(List<BaseDataType> list, Hashtable<String, Object> hash) { RpgPushMessage push = RpgPushMessage.createFromHashtable(hash); parsePushPayload(push, list); } private void parsePushPayload(RpgPushMessage msg, List<BaseDataType> list) { // convert push msg type string to PushMsgType PushMessageTypes type = msg.mType; EngineId engineId = EngineId.UNDEFINED; if (type != null) { switch (type) { case CHAT_MESSAGE: LogUtils.logV("Parse incomming chat_message"); engineId = EngineId.PRESENCE_ENGINE; list.add(new PushChatMessageEvent(msg, engineId)); return; case AVAILABILITY_STATE_CHANGE: LogUtils.logV("Parse availability state change:"); engineId = EngineId.PRESENCE_ENGINE; list.add(PushAvailabilityEvent.createPushEvent(msg, engineId)); return; case START_CONVERSATION: LogUtils.logV("Parse new conversation event:"); engineId = EngineId.PRESENCE_ENGINE; list.add(new PushChatConversationEvent(msg, engineId)); return; case CLOSED_CONVERSATION: LogUtils.logV("Parse closed conversation event:"); engineId = EngineId.PRESENCE_ENGINE; list.add(new PushClosedConversationEvent(msg, engineId)); return; case CONVERSATION_END: break; // API events create push message type case PROFILE_CHANGE: engineId = EngineId.SYNCME_ENGINE; break; case CONTACTS_CHANGE: engineId = EngineId.CONTACT_SYNC_ENGINE; break; case TIMELINE_ACTIVITY_CHANGE: case STATUS_ACTIVITY_CHANGE: engineId = EngineId.ACTIVITIES_ENGINE; break; case FRIENDSHIP_REQUEST_RECEIVED: break; case IDENTITY_CHANGE: engineId = EngineId.IDENTITIES_ENGINE; break; case IDENTITY_NETWORK_CHANGE: engineId = EngineId.IDENTITIES_ENGINE; break; case SYSTEM_NOTIFICATION: LogUtils.logE("SYSTEM_NOTIFICATION push msg:" + msg.mHash); list.add(SystemNotification.createFromHashtable(msg.mHash, engineId)); return; default: } list.add(PushEvent.createPushEvent(msg, engineId)); } } }
360/360-Engine-for-Android
de21697ff160e62dc6d709f52a15f31434848f4f
Fixed problems with connectivity. NetworkAgent was not differentiating between state changes for 3G and WIFI, so if the 3G network would disconnect after WIFI connects, it would consider itself to be in disconnected state.
diff --git a/src/com/vodafone360/people/service/agent/NetworkAgent.java b/src/com/vodafone360/people/service/agent/NetworkAgent.java index b10f73b..ff23880 100644 --- a/src/com/vodafone360/people/service/agent/NetworkAgent.java +++ b/src/com/vodafone360/people/service/agent/NetworkAgent.java @@ -1,674 +1,690 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.agent; import java.security.InvalidParameterException; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.ContentObserver; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.telephony.TelephonyManager; import android.text.format.DateUtils; import com.vodafone360.people.Intents; import com.vodafone360.people.MainApplication; import com.vodafone360.people.service.PersistSettings; import com.vodafone360.people.service.RemoteService; import com.vodafone360.people.service.PersistSettings.InternetAvail; import com.vodafone360.people.service.interfaces.IConnectionManagerInterface; import com.vodafone360.people.service.interfaces.IWorkerThreadControl; import com.vodafone360.people.utils.LogUtils; /** * The network Agent monitors the connectivity status of the device and makes * decisions about the communication strategy. The Agent has the following * states {connected | disconnected}, with changes reported to various listeners * in the service. */ public class NetworkAgent { /** Roaming notification is on */ public static final int ROAMING_DIALOG_GLOBAL_ON = 0; /** Roaming notification is off */ public static final int ROAMING_DIALOG_GLOBAL_OFF = 1; private static final int TYPE_WIFI = 1; private static AgentState mAgentState = AgentState.UNKNOWN; private ConnectivityManager mConnectivityManager; private ContentResolver mContentResolver; private AgentDisconnectReason mDisconnectReason = AgentDisconnectReason.UNKNOWN; private SettingsContentObserver mDataRoamingSettingObserver; private boolean mInternetConnected; private boolean mDataRoaming; private boolean mBackgroundData; private boolean mIsRoaming; private boolean mIsInBackground; - private boolean mWifiActive; - private boolean mNetworkWorking = true; // dateTime value in milliseconds private Long mDisableRoamingNotificationUntil = null; private IWorkerThreadControl mWorkerThreadControl; private IConnectionManagerInterface mConnectionMgrIf; private Context mContext; public enum AgentState { CONNECTED, DISCONNECTED, UNKNOWN }; + + private boolean mWifiNetworkAvailable; + private boolean mMobileNetworkAvailable; /** * Reasons for Service Agent changing state to disconnected */ public enum AgentDisconnectReason { AGENT_IS_CONNECTED, // Sanity check NO_INTERNET_CONNECTION, NO_WORKING_NETWORK, DATA_SETTING_SET_TO_MANUAL_CONNECTION, DATA_ROAMING_DISABLED, BACKGROUND_CONNECTION_DISABLED, // WIFI_INACTIVE, UNKNOWN } public enum StatesOfService { IS_CONNECTED_TO_INTERNET, IS_NETWORK_WORKING, IS_ROAMING, IS_ROAMING_ALLOWED, IS_INBACKGROUND, IS_BG_CONNECTION_ALLOWED, IS_WIFI_ACTIVE }; /** * Listens for changes made to People client's status. The NetworkAgent is * specifically interested in changes to the data settings (e.g. data * disabled, only in home network or roaming). */ private class SettingsContentObserver extends ContentObserver { private String mSettingName; private SettingsContentObserver(String settingName) { super(new Handler()); mSettingName = settingName; } /** * Start content observer. */ private void start() { if (mContentResolver != null) { mContentResolver.registerContentObserver(Settings.Secure.getUriFor(mSettingName), true, this); } } /** * De-activate content observer. */ private void close() { if (mContentResolver != null) { mContentResolver.unregisterContentObserver(this); } } @Override public void onChange(boolean selfChange) { onDataSettingChanged(mSettingName); } public boolean getBooleanValue() { if (mContentResolver != null) { try { return (Settings.Secure.getInt(mContentResolver, mSettingName) != 0); } catch (SettingNotFoundException e) { LogUtils.logE("NetworkAgent.SettingsContentObserver.getBooleanValue() " + "SettingNotFoundException", e); return false; } } return false; } } /** * The constructor. * * @param context Android context. * @param workerThreadControl Handle to kick the worker thread. * @param connMgrIf Handler to signal the connection manager. * @throws InvalidParameterException Context is NULL. * @throws InvalidParameterException IWorkerThreadControl is NULL. * @throws InvalidParameterException IConnectionManagerInterface is NULL. */ public NetworkAgent(Context context, IWorkerThreadControl workerThreadControl, IConnectionManagerInterface connMgrIf) { if (context == null) { throw new InvalidParameterException("NetworkAgent() Context canot be NULL"); } if (workerThreadControl == null) { throw new InvalidParameterException("NetworkAgent() IWorkerThreadControl canot be NULL"); } if (connMgrIf == null) { throw new InvalidParameterException( "NetworkAgent() IConnectionManagerInterface canot be NULL"); } mContext = context; mWorkerThreadControl = workerThreadControl; mConnectionMgrIf = connMgrIf; mContentResolver = context.getContentResolver(); mConnectivityManager = (ConnectivityManager)context .getSystemService(Context.CONNECTIVITY_SERVICE); mDataRoamingSettingObserver = new SettingsContentObserver(Settings.Secure.DATA_ROAMING); } /** * Create NetworkAgent and start observers of device connectivity state. * * @throws InvalidParameterException DataRoamingSettingObserver is NULL. * @throws InvalidParameterException Context is NULL. * @throws InvalidParameterException ConnectivityManager is NULL. */ public void onCreate() { if (mDataRoamingSettingObserver == null) { throw new InvalidParameterException( "NetworkAgent.onCreate() DataRoamingSettingObserver canot be NULL"); } if (mContext == null) { throw new InvalidParameterException("NetworkAgent.onCreate() Context canot be NULL"); } if (mConnectivityManager == null) { throw new InvalidParameterException( "NetworkAgent.onCreate() ConnectivityManager canot be NULL"); } mDataRoamingSettingObserver.start(); mDataRoaming = mDataRoamingSettingObserver.getBooleanValue(); mContext.registerReceiver(mBackgroundDataBroadcastReceiver, new IntentFilter( ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED)); mContext.registerReceiver(mInternetConnectivityReceiver, new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION)); mContext.registerReceiver(mServiceStateRoamingReceiver, new IntentFilter( "android.intent.action.SERVICE_STATE")); NetworkInfo info = mConnectivityManager.getActiveNetworkInfo(); if (info != null) { mInternetConnected = (info.getState() == NetworkInfo.State.CONNECTED); - mWifiActive = (info.getType() == TYPE_WIFI); + mWifiNetworkAvailable = (info.getType() == TYPE_WIFI); mIsRoaming = info.isRoaming(); } mBackgroundData = mConnectivityManager.getBackgroundDataSetting(); onConnectionStateChanged(); } /** * Destroy NetworkAgent and un-register observers. * * @throws InvalidParameterException Context is NULL. * @throws InvalidParameterException DataRoamingSettingObserver is NULL. */ public void onDestroy() { if (mContext == null) { throw new InvalidParameterException("NetworkAgent.onCreate() Context canot be NULL"); } if (mDataRoamingSettingObserver == null) { throw new InvalidParameterException( "NetworkAgent.onDestroy() DataRoamingSettingObserver canot be NULL"); } mContext.unregisterReceiver(mInternetConnectivityReceiver); mContext.unregisterReceiver(mBackgroundDataBroadcastReceiver); mContext.unregisterReceiver(mServiceStateRoamingReceiver); mDataRoamingSettingObserver.close(); mDataRoamingSettingObserver = null; } /** * Receive notification from * ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED */ private final BroadcastReceiver mBackgroundDataBroadcastReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogUtils .logV("NetworkAgent.broadcastReceiver.onReceive() ACTION_BACKGROUND_DATA_SETTING_CHANGED"); synchronized (NetworkAgent.this) { if (mConnectivityManager != null) { mBackgroundData = mConnectivityManager.getBackgroundDataSetting(); onConnectionStateChanged(); } } } }; /** * Receive notification from ConnectivityManager.CONNECTIVITY_ACTION */ private final BroadcastReceiver mInternetConnectivityReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() CONNECTIVITY_ACTION"); synchronized (NetworkAgent.this) { - mInternetConnected = false; - NetworkInfo info = (NetworkInfo)intent - .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); - if (!intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) { - if (info != null) { - mInternetConnected = (info.getState() == NetworkInfo.State.CONNECTED); - mWifiActive = (info.getType() == TYPE_WIFI); - } + NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); + boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); + + if (info == null) { + LogUtils.logW("NetworkAgent.broadcastReceiver.onReceive() EXTRA_NETWORK_INFO not found."); + } else { + if (info.getType() == TYPE_WIFI) { + mWifiNetworkAvailable = (info.getState() == NetworkInfo.State.CONNECTED); + } else { + mMobileNetworkAvailable = (info.getState() == NetworkInfo.State.CONNECTED); + } + } + + if (noConnectivity) { + LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() EXTRA_NO_CONNECTIVITY found!"); + mInternetConnected = false; + } else { + mInternetConnected = mWifiNetworkAvailable || mMobileNetworkAvailable; } + + LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() mInternetConnected = " + mInternetConnected + + ", mWifiNetworkAvailable = " + mWifiNetworkAvailable + + ", mMobileNetworkAvailable = " + mMobileNetworkAvailable); + onConnectionStateChanged(); } } }; /** * Receive notification from android.intent.action.SERVICE_STATE */ private final BroadcastReceiver mServiceStateRoamingReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() SERVICE_STATE"); synchronized (NetworkAgent.this) { // //ConnectivityManager provides wrong information about // roaming // NetworkInfo info = // mConnectivityManager.getActiveNetworkInfo(); // if (info != null) { // mIsRoaming = info.isRoaming(); // } LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() Extras are: " + intent.getExtras()); Bundle bu = intent.getExtras(); // int state = bu.getInt("state"); boolean roam = bu.getBoolean("roaming"); mIsRoaming = roam; onConnectionStateChanged(); LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() Network Roaming = " + mIsRoaming); LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() WiFi active = " - + mWifiActive); + + mWifiNetworkAvailable); } processRoaming(null); } }; /** * Notify interested parties of changes in Internet setting. * * @param val updated InternetAvail value. */ public void notifyDataSettingChanged(InternetAvail val) { processRoaming(val); onConnectionStateChanged(); } /** * Displaying notification to the user about roaming * * @param InternetAvail value. */ private void processRoaming(InternetAvail val) { InternetAvail internetAvail; if (val != null) { internetAvail = val; } else { internetAvail = getInternetAvailSetting(); } Intent intent = new Intent(); if (mContext != null && mIsRoaming && (internetAvail == InternetAvail.ALWAYS_CONNECT) && (mDisableRoamingNotificationUntil == null || mDisableRoamingNotificationUntil < System .currentTimeMillis())) { LogUtils.logV("NetworkAgent.processRoaming() " + "Displaying notification - DisplayRoaming[" + mIsRoaming + "]"); intent.setAction(Intents.ROAMING_ON); } else { /* * We are not roaming then we should remove notification, if no * notification were before nothing happens */ LogUtils.logV("NetworkAgent.processRoaming() Removing notification - " + " DisplayRoaming[" + mIsRoaming + "]"); intent.setAction(Intents.ROAMING_OFF); } mContext.sendBroadcast(intent); } private InternetAvail getInternetAvailSetting() { if (mContext != null) { PersistSettings setting = ((MainApplication)((RemoteService)mContext).getApplication()) .getDatabase().fetchOption(PersistSettings.Option.INTERNETAVAIL); if (setting != null) { return setting.getInternetAvail(); } } return null; } public int getRoamingNotificationType() { int type; if (mDataRoaming) { type = ROAMING_DIALOG_GLOBAL_ON; } else { type = ROAMING_DIALOG_GLOBAL_OFF; } return type; } /** * Get current device roaming setting. * * @return current device roaming setting. */ public boolean getRoamingDeviceSetting() { return mDataRoaming; } public void setShowRoamingNotificationAgain(boolean showAgain) { LogUtils.logV("NetworkAgent.setShowRoamingNotificationAgain() " + "showAgain[" + showAgain + "]"); if (showAgain) { mDisableRoamingNotificationUntil = null; } else { mDisableRoamingNotificationUntil = System.currentTimeMillis() + DateUtils.DAY_IN_MILLIS; if (mContext != null) { LogUtils.logV("NetworkAgent.setShowRoamingNotificationAgain() " + "Next notification on [" + DateUtils.formatDateTime(mContext, mDisableRoamingNotificationUntil, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_YEAR) + "]"); } } processRoaming(null); } /** * Received when user modifies one of the system settings */ private synchronized void onDataSettingChanged(String settingName) { LogUtils.logV("NetworkAgent.onDataSettingChanged() settingName[" + settingName + "]" + " has changed"); if (settingName.equals(Settings.Secure.DATA_ROAMING)) { if (mDataRoamingSettingObserver != null) { mDataRoaming = mDataRoamingSettingObserver.getBooleanValue(); onConnectionStateChanged(); } } } /** * Contains the main logic that determines the agent state for network * access */ private void onConnectionStateChanged() { if (!mInternetConnected) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() No internet connection"); mDisconnectReason = AgentDisconnectReason.NO_INTERNET_CONNECTION; setNewState(AgentState.DISCONNECTED); return; } else { - if (mWifiActive) { + if (mWifiNetworkAvailable) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() WIFI connected"); } else { LogUtils.logV("NetworkAgent.onConnectionStateChanged() Cellular connected"); } } if (mContext != null) { MainApplication app = (MainApplication)((RemoteService)mContext).getApplication(); if ((app.getInternetAvail() == InternetAvail.MANUAL_CONNECT)/* * AA: I * commented * it - * TBD * &&! - * mWifiActive + * mWifiNetworkAvailable */) { LogUtils.logV("NetworkAgent.onConnectionStateChanged()" + " Internet allowed only in manual mode"); mDisconnectReason = AgentDisconnectReason.DATA_SETTING_SET_TO_MANUAL_CONNECTION; setNewState(AgentState.DISCONNECTED); return; } } if (!mNetworkWorking) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() Network is not working"); mDisconnectReason = AgentDisconnectReason.NO_WORKING_NETWORK; setNewState(AgentState.DISCONNECTED); return; } if (mIsRoaming && !mDataRoaming) { LogUtils.logV("NetworkAgent.onConnectionStateChanged() " + "Connect while roaming not allowed"); mDisconnectReason = AgentDisconnectReason.DATA_ROAMING_DISABLED; setNewState(AgentState.DISCONNECTED); return; } if (mIsInBackground && !mBackgroundData) { LogUtils .logV("NetworkAgent.onConnectionStateChanged() Background connection not allowed"); mDisconnectReason = AgentDisconnectReason.BACKGROUND_CONNECTION_DISABLED; setNewState(AgentState.DISCONNECTED); return; } LogUtils.logV("NetworkAgent.onConnectionStateChanged() Connection available"); setNewState(AgentState.CONNECTED); } public static AgentState getAgentState() { LogUtils.logV("NetworkAgent.getAgentState() mAgentState[" + mAgentState.name() + "]"); return mAgentState; } private void setNewState(AgentState newState) { if (newState == mAgentState) { return; } LogUtils.logI("NetworkAgent.setNewState(): " + mAgentState + " -> " + newState); mAgentState = newState; if (newState == AgentState.CONNECTED) { mDisconnectReason = AgentDisconnectReason.AGENT_IS_CONNECTED; onConnected(); } else if (newState == AgentState.DISCONNECTED) { onDisconnected(); } } private void onConnected() { checkActiveNetworkState(); if (mWorkerThreadControl != null) { mWorkerThreadControl.kickWorkerThread(); } if (mConnectionMgrIf != null) { mConnectionMgrIf.signalConnectionManager(true); } } private void onDisconnected() { // AA:need to kick it to make engines run and set the if (mWorkerThreadControl != null) { mWorkerThreadControl.kickWorkerThread(); } if (mConnectionMgrIf != null) { mConnectionMgrIf.signalConnectionManager(false); } } private void checkActiveNetworkState() { if (mConnectivityManager != null) { NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo == null) { LogUtils.logW("NetworkAgent.checkActiveNetworkInfoy() " + "mConnectivityManager.getActiveNetworkInfo() Returned null"); return; } else { if (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { LogUtils.logV("NetworkAgent.checkActiveNetworkInfoy() WIFI network"); // TODO: Do something } else if (mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { LogUtils.logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE and ROAMING"); // TODO: Do something // Only works when you are registering with network switch (mNetworkInfo.getSubtype()) { case TelephonyManager.NETWORK_TYPE_EDGE: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE EDGE network"); // TODO: Do something break; case TelephonyManager.NETWORK_TYPE_GPRS: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE GPRS network"); // TODO: Do something break; case TelephonyManager.NETWORK_TYPE_UMTS: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE UMTS network"); // TODO: Do something break; case TelephonyManager.NETWORK_TYPE_UNKNOWN: LogUtils .logV("NetworkAgent.checkActiveNetworkInfoy() MOBILE UNKNOWN network"); // TODO: Do something break; default: // Do nothing. break; } ; } } } else { LogUtils.logW("NetworkAgent.checkActiveNetworkInfoy() mConnectivityManager is null"); } } public void setNetworkAgentState(NetworkAgentState state) { LogUtils.logD("NetworkAgent.setNetworkAgentState() state[" + state + "]"); // TODO: make assignments if any changes boolean changes[] = state.getChanges(); if (changes[StatesOfService.IS_CONNECTED_TO_INTERNET.ordinal()]) mInternetConnected = state.isInternetConnected(); if (changes[StatesOfService.IS_NETWORK_WORKING.ordinal()]) mNetworkWorking = state.isNetworkWorking(); if (changes[StatesOfService.IS_ROAMING_ALLOWED.ordinal()]) mDataRoaming = state.isRoamingAllowed(); if (changes[StatesOfService.IS_INBACKGROUND.ordinal()]) mIsInBackground = state.isInBackGround(); if (changes[StatesOfService.IS_BG_CONNECTION_ALLOWED.ordinal()]) mBackgroundData = state.isBackDataAllowed(); if (changes[StatesOfService.IS_WIFI_ACTIVE.ordinal()]) - mWifiActive = state.isWifiActive(); + mWifiNetworkAvailable = state.isWifiActive(); if (changes[StatesOfService.IS_ROAMING.ordinal()]) {// special case for // roaming mIsRoaming = state.isRoaming(); // This method sets the mAgentState, and mDisconnectReason as well // by calling setNewState(); onConnectionStateChanged(); processRoaming(null); } else // This method sets the mAgentState, and mDisconnectReason as well // by calling setNewState(); onConnectionStateChanged(); } public NetworkAgentState getNetworkAgentState() { NetworkAgentState state = new NetworkAgentState(); state.setRoaming(mIsRoaming); state.setRoamingAllowed(mDataRoaming); state.setBackgroundDataAllowed(mBackgroundData); state.setInBackGround(mIsInBackground); state.setInternetConnected(mInternetConnected); state.setNetworkWorking(mNetworkWorking); - state.setWifiActive(mWifiActive); + state.setWifiActive(mWifiNetworkAvailable); state.setDisconnectReason(mDisconnectReason); state.setAgentState(mAgentState); LogUtils.logD("NetworkAgent.getNetworkAgentState() state[" + state + "]"); return state; } // ///////////////////////////// // FOR TESTING PURPOSES ONLY // // ///////////////////////////// /** * Forces the AgentState to a specific value. * * @param newState the state to set Note: to be used only for test purposes */ public static void setAgentState(AgentState newState) { mAgentState = newState; } }
360/360-Engine-for-Android
04ea2800da1b9b9adaeb324dec14f57889f4f871
PAND-1753: [UI Refresh] Crash after sync.
diff --git a/src/com/caucho/hessian/micro/MicroHessianInput.java b/src/com/caucho/hessian/micro/MicroHessianInput.java index b2776d5..687ff79 100644 --- a/src/com/caucho/hessian/micro/MicroHessianInput.java +++ b/src/com/caucho/hessian/micro/MicroHessianInput.java @@ -1,599 +1,599 @@ /* * Copyright (c) 2001-2006 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Hessian", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Scott Ferguson * */ package com.caucho.hessian.micro; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Hashtable; import java.util.Vector; import com.vodafone360.people.utils.LogUtils; /** * Input stream for Hessian requests, compatible with microedition Java. It only * uses classes and types available to J2ME. In particular, it does not have any * support for the &lt;double> type. * <p> * MicroHessianInput does not depend on any classes other than in J2ME, so it * can be extracted independently into a smaller package. * <p> * MicroHessianInput is unbuffered, so any client needs to provide its own * buffering. * * <pre> * InputStream is = ...; // from http connection * MicroHessianInput in = new MicroHessianInput(is); * String value; * in.startReply(); // read reply header * value = in.readString(); // read string value * in.completeReply(); // read reply footer * </pre> */ public class MicroHessianInput { protected BufferedInputStream is; /** Using fast but not thread safe StringBuilder for constructing strings */ private StringBuilder mStringBuilder = new StringBuilder(255); /** * Creates a new Hessian input stream, initialized with an underlying input * stream. * * @param is the underlying input stream. */ public MicroHessianInput(InputStream is) { init(is); } /** * Creates an uninitialized Hessian input stream. */ public MicroHessianInput() { } /** * Initialize the hessian stream with the underlying input stream. */ public void init(InputStream is) { this.is = new BufferedInputStream(is); } /** * Starts reading the reply * <p> * A successful completion will have a single value: * * <pre> * r x01 x00 * </pre> */ public void startReply() throws IOException { int tag = is.read(); if (tag != 'r') throw protocolException("expected hessian reply"); // remove some bits from the input stream is.skip(2); } /** * Completes reading the call * <p> * A successful completion will have a single value: * * <pre> * z * </pre> */ public void completeReply() throws IOException { int tag = is.read(); if (tag != 'z') throw protocolException("expected end of reply"); } /** * Reads a boolean * * <pre> * T * F * </pre> */ public boolean readBoolean() throws IOException { int tag = is.read(); switch (tag) { case 'T': return true; case 'F': return false; default: throw expect("boolean", tag); } } /** * Reads an integer * * <pre> * I b32 b24 b16 b8 * </pre> */ public int readInt() throws IOException { int tag = is.read(); return readInt(tag); } public int readInt(int tag) throws IOException { if (tag != 'I') throw expect("integer", tag); int b32 = is.read(); int b24 = is.read(); int b16 = is.read(); int b8 = is.read(); return (b32 << 24) + (b24 << 16) + (b16 << 8) + b8; } /** * Reads a long * * <pre> * L b64 b56 b48 b40 b32 b24 b16 b8 * </pre> */ public long readLong() throws IOException { int tag = is.read(); return readLong(tag); } private long readLong(int tag) throws IOException { if (tag != 'L') throw protocolException("expected long"); long b64 = is.read(); long b56 = is.read(); long b48 = is.read(); long b40 = is.read(); long b32 = is.read(); long b24 = is.read(); long b16 = is.read(); long b8 = is.read(); return ((b64 << 56) + (b56 << 48) + (b48 << 40) + (b40 << 32) + (b32 << 24) + (b24 << 16) + (b16 << 8) + b8); } /** * Reads a date. * * <pre> * T b64 b56 b48 b40 b32 b24 b16 b8 * </pre> */ public long readUTCDate() throws IOException { int tag = is.read(); if (tag != 'd') throw protocolException("expected date"); long b64 = is.read(); long b56 = is.read(); long b48 = is.read(); long b40 = is.read(); long b32 = is.read(); long b24 = is.read(); long b16 = is.read(); long b8 = is.read(); return ((b64 << 56) + (b56 << 48) + (b48 << 40) + (b40 << 32) + (b32 << 24) + (b24 << 16) + (b16 << 8) + b8); } /** * Reads a byte array * * @return byte[] array extracted from Hessian stream, NULL if 'N' specified * in data. * @throws IOException. */ public byte[] readBytes() throws IOException { int tag = is.read(); return readBytes(tag); } private byte[] readBytes(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'B') throw expect("bytes", tag); int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; byte[] bytes = new byte[len]; is.read(bytes); return bytes; } /** * Reads an arbitrary object the input stream. */ public Object readObject(Class<?> expectedClass) throws IOException { int tag = is.read(); switch (tag) { case 'N': return null; case 'T': return true; case 'F': return false; case 'I': { int b32 = is.read(); int b24 = is.read(); int b16 = is.read(); int b8 = is.read(); return ((b32 << 24) + (b24 << 16) + (b16 << 8) + b8); } case 'L': { long b64 = is.read(); long b56 = is.read(); long b48 = is.read(); long b40 = is.read(); long b32 = is.read(); long b24 = is.read(); long b16 = is.read(); long b8 = is.read(); return ((b64 << 56) + (b56 << 48) + (b48 << 40) + (b40 << 32) + (b32 << 24) + (b24 << 16) + (b16 << 8) + b8); } case 'd': { long b64 = is.read(); long b56 = is.read(); long b48 = is.read(); long b40 = is.read(); long b32 = is.read(); long b24 = is.read(); long b16 = is.read(); long b8 = is.read(); return new Date((b64 << 56) + (b56 << 48) + (b48 << 40) + (b40 << 32) + (b32 << 24) + (b24 << 16) + (b16 << 8) + b8); } case 'S': case 'X': { int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; return readStringImpl(len); } case 'B': { if (tag != 'B') throw expect("bytes", tag); int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (int i = 0; i < len; i++) bos.write(is.read()); return bos.toByteArray(); } default: throw new IOException("unknown code:" + (char)tag); } } public Vector<Object> readVector() throws IOException { int tag = is.read(); return readVector(tag); } private Vector<Object> readVector(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'V') throw expect("vector", tag); Vector<Object> v = new Vector<Object>(); Object o = decodeTag(); if (o instanceof End) return v; if (o instanceof Type) o = decodeTag(); if (o instanceof End) return v; int len = 0; if (o instanceof Integer) { len = ((Integer)o); o = decodeTag(); } for (int i = 0; i < len; i++) { v.addElement(o); o = decodeTag(); } return v; } public Fault readFault() throws IOException { decodeTag(); int tag = is.read(); if (tag == 'S') { return new Fault(readString(tag)); } return null; } public Object decodeTag() throws IOException { int tag = is.read(); // HessianUtils.printTagValue(tag); return decodeType(tag); } public Object decodeType(int tag) throws IOException { // LogUtils.logD("HessianDecoder.decodeType() tag["+tag+"]"); switch (tag) { case 't': // tag is.skip(2); Type type = new Type(); return type; case 'l': // length int i = 0; i += (is.read() << 24); i += (is.read() << 16); i += (is.read() << 8); i += is.read(); Integer len = i; return len; case 'z': // end End end = new End(); return end; case 'N': // null return null; case 'r': // reply startReply should have retrieved this? return null; case 'M': return readHashMap(tag); case 'V': // array/Vector return readVector(tag); case 'T': // boolean true return true; case 'F': // boolean false return false; case 'I': // integer return readInt(tag); case 'L': // read long return readLong(tag); case 'd': // UTC date return null; case 'S': // String return readString(tag); case 'B': // read byte array return readBytes(tag); case 'f': return readFault(); default: LogUtils.logE("HessianDecoder.decodeType() Unknown type"); return null; } } /** * Reads a string * * <pre> * S b16 b8 string value * </pre> */ public String readString() throws IOException { int tag = is.read(); return readString(tag); } private String readString(int tag) throws IOException { if (tag == 'N') return null; if (tag != 'S') throw expect("string", tag); int b16 = is.read(); int b8 = is.read(); int len = (b16 << 8) + b8; return readStringImpl(len); } /** * Reads a string from the underlying stream. */ private String readStringImpl(int length) throws IOException { - // reset the stringbuilder. Recycling is better then making allways a + // reset the StringBuilder. Recycling is better than making always a // new one. mStringBuilder.setLength(0); for (int i = 0; i < length; i++) { int ch = is.read(); if (ch < 0x80) mStringBuilder.append((char)ch); else if ((ch & 0xe0) == 0xc0) { int ch1 = is.read(); int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f); mStringBuilder.append((char)v); } else if ((ch & 0xf0) == 0xe0) { int ch1 = is.read(); int ch2 = is.read(); int v = ((ch & 0x0f) << 12) + ((ch1 & 0x3f) << 6) + (ch2 & 0x3f); mStringBuilder.append((char)v); } else if ((ch & 0xff) >= 0xf0 && (ch & 0xff) <= 0xf4) { // UTF-4 final byte[] b = new byte[4]; b[0] = (byte)ch; b[1] = (byte)is.read(); b[2] = (byte)is.read(); b[3] = (byte)is.read(); mStringBuilder.append(new String(b, "utf-8")); i++; } else throw new IOException("bad utf-8 encoding"); } - return mStringBuilder.toString(); + return mStringBuilder.substring(0, mStringBuilder.length()); } public Hashtable<String, Object> readHashMap() throws IOException { // read map type int tag = is.read(); return readHashMap(tag); } public Hashtable<String, Object> readHashMap(int tag) throws IOException { // read map type if (tag == 'N') return null; if (tag != 'M') throw expect("map", tag); Hashtable<String, Object> ht = new Hashtable<String, Object>(); Object obj = decodeTag(); if (obj instanceof Type) { // get following object obj = decodeTag(); } Object obj1 = null; while (obj != null && !(obj instanceof End)) // 'z' = list-end { obj1 = decodeTag(); ht.put(obj.toString(), obj1); obj = decodeTag(); } return ht; } protected IOException expect(String expect, int ch) { if (ch < 0) return protocolException("expected " + expect + " at end of file"); else return protocolException("expected " + expect + " at " + (char)ch); } protected IOException protocolException(String message) { return new IOException(message); } /** * Place-holder class for End tag 'z' */ private static class End { } /** * Place-holder class for Type tag 't' */ private static class Type { } /** * Class holding error string returned during Hessian decoding */ public static class Fault { private String mErrString = null; private Fault(String eString) { mErrString = eString; } public String errString() { return mErrString; } } }
360/360-Engine-for-Android
411026fe478281dc6f39622d7585a2bfaa5113f9
add cached boolean flag for 'Add Accounts' ui-refresh [PAND-1726]
diff --git a/src/com/vodafone360/people/ApplicationCache.java b/src/com/vodafone360/people/ApplicationCache.java index 12ba59b..8fcc742 100644 --- a/src/com/vodafone360/people/ApplicationCache.java +++ b/src/com/vodafone360/people/ApplicationCache.java @@ -1,642 +1,665 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people; import java.security.InvalidParameterException; import java.util.ArrayList; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactSummary; import com.vodafone360.people.engine.contactsync.SyncStatus; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.ThirdPartyAccount; import com.vodafone360.people.utils.LoginPreferences; import com.vodafone360.people.utils.LogUtils; /** * Caches information about the current state of the application. Stores most * recent activity and caches other information such as login details, so that * the application is returned to its most recent state when brought back to the * foreground or re-entered. The cached details can be cleared if required (as * part of 'Remove user data' for example). */ public class ApplicationCache { /** Text key for Terms of Service content. **/ private final static String TERMS_OF_SERVICE = "TERMS_OF_SERVICE"; /** Text key for Terms of Service last updated time. **/ private final static String TERMS_OF_SERVICE_TIME = "TERMS_OF_SERVICE_TIME"; /** Text key for Privacy content. **/ private final static String PRIVACY = "PRIVACY"; /** Text key for Privacy last updated time. **/ private final static String PRIVACY_TIME = "PRIVACY_TIME"; /** * Refresh any cached terms of service or privacy content after 10 minutes. */ private final static long REFRESH_TIME = 10 * 60 * 1000; private static final String TRUE = "true"; private static final String FALSE = "false"; /** * Login details are stored in the preferences file so that they can be used * to pre-populate the edit fields if the user is interrupted in the middle * of login/signup */ public static final String PREFS_FILE = "NOW_PLUS"; public static final String CONTACT_DATA = "ContactData"; public static final String CONTACT_SUMMARY = "ContactSummary"; public static final String CONTACT_ID = "CONTACTID"; public static final String CONTACT_NAME = "CONTACTNAME"; public static final String CONTACT_NUMBER = "CONTACTNUMBER"; public static final String CONTACT_NETWORK = "CONTACTNETWORK"; public static final String CONTACT_MODIFIED = "ContactModified"; public static final String STARTUP_LAUNCH_PATH_KEY = "LAUNCHED_FROM"; public static final int RESULT_DELETE = -100; public static final int CONTACT_PROFILE_VIEW = 0; public static final int CONTACT_PROFILE_EDIT = 1; public static final int CONTACT_PROFILE_ADD = 2; public static final int CONTACT_PROFILE_VIEW_ME = 3; public static final String THIRD_PARTY_ACCOUNT_NAME_KEY = "ThirdPartyAccountName"; public static final String THIRD_PARTY_ACCOUNT_NETWORK_KEY = "ThirdPartyNetworkName"; public static final String THIRD_PARTY_ACCOUNT_USERNAME_KEY = "ThirdPartyAccountUsername"; public static final String THIRD_PARTY_ACCOUNT_PASSWORD_KEY = "ThirdPartyAccountPassword"; public static final String THIRD_PARTY_ACCOUNT_CAPABILITIES = "ThirdPartyAccountCapabilities"; public static final String THIRD_PARTY_ACCOUNT_ERROR_CODE = "ThirdPartyAccountErrorCode"; private final static String FACEBOOK_SUBSCRIBED = "FacebookSubscribed"; private final static String HYVES_SUBSCRIBED = "HyvesSubscribed"; public final static String PREFS_NAME = "NowPlus_Prefs"; // Check settings public final static String PREFS_CHECK_FREQUENCY = "checkFrequency"; // Upgrade version - these values are deleted when the latest version is not // new public final static String PREFS_LAST_DIALOG_DATE = "lastDialogDate"; public final static String PREFS_LAST_CHECKED_DATE = "lastCheckedDate"; public final static String PREFS_UPGRADE_LATEST_VERSION = "upgradeLatestVersion"; public final static String PREFS_UPGRADE_URL = "upgradeUrl"; public final static String PREFS_UPGRADE_TEXT = "upgradeText"; public static String sWidgetProviderClassName = null; public static String sIsNewMessage = "isNewMessage"; // Frequency setting descriptions and defaults public final static long[] FREQUENCY_SETTING_LONG = { -1, // Off 7 * 24 * 60 * 60 * 1000, // Weekly 24 * 60 * 60 * 1000, // Daily 6 * 60 * 60 * 1000, // Every 6 hours 1 * 60 * 60 * 1000, // Hourly 10 * 60 * 1000 // Every 10 minutes }; /** In memory cache of the current contacts sync status. **/ private SyncStatus mSyncStatus = null; // Cached login flags private boolean mFirstTimeLogin = true; private boolean mScanThirdPartyAccounts = true; private boolean mAcceptedTermsAndConditions = false; private int mIdentityBeingProcessed = -1; private ArrayList<ThirdPartyAccount> mThirdPartyAccountsCache; private ContactSummary mMeProfileSummary; private Contact mCurrentContact; private ContactSummary mCurrentContactSummary; private ServiceStatus mServiceStatus = ServiceStatus.ERROR_UNKNOWN; private TimelineSummaryItem mCurrentTimelineSummary; private long mCurrentContactFilter; + + /** Cached whether ThirdPartyAccountsActivity is opened. */ + private boolean mIsAddAccountActivityOpened; + + /*** + * GETTER Whether "add Account" activity is opened + * + * @return True if "add Account" activity is opened + */ + public boolean addAccountActivityOpened() { + return mIsAddAccountActivityOpened; + } + /*** + * SETTER Whether "add Account" activity is opened. + * + * @param flag if "add Account" activity is opened + */ + public void setAddAccountActivityOpened(final boolean flag) { + mIsAddAccountActivityOpened = flag; + } + /** * Whether this is a first time login (on this device) for current account. * * @return True if this is the first login for current account. */ public boolean firstTimeLogin() { return mFirstTimeLogin; } /** * Set whether this is a first time login (on this device) for current * account. If we have not logged in on this device (or after 'Remove user * data') we will need to perform the first time 'full' time contact sync. * * @param aState True if this is our 1st time sync. */ public void setFirstTimeLogin(boolean state) { mFirstTimeLogin = state; } /** * Set whether application should re-scan 3rd party accounts. * * @param state true if application should re-scan 3rd party accounts. */ public void setScanThirdPartyAccounts(boolean state) { mScanThirdPartyAccounts = state; } /** * Return whether application should re-scan 3rd party accounts. * * @return true if application should re-scan 3rd party accounts. */ public boolean getScanThirdPartyAccounts() { return mScanThirdPartyAccounts; } /** * Set index of Identity currently being processed. * * @param index Index of Identity currently being processed. */ public void setIdentityBeingProcessed(int index) { mIdentityBeingProcessed = index; } /** * Return index of the Identity currently being processed. * * @return index of the Identity currently being processed. */ public int getIdentityBeingProcessed() { return mIdentityBeingProcessed; } /** * Set whether user has accepted the Terms and Conditions on sign-up. * * @param state true if user has accepted terms and conditions. */ public void setAcceptedTermsAndConditions(boolean state) { mAcceptedTermsAndConditions = state; } /** * Return whether user has accepted the Terms and Conditions on sign-up. * * @return true if user has accepted terms and conditions. */ public boolean getAcceptedTermsAndConditions() { return mAcceptedTermsAndConditions; } /** * Clear all cached data currently stored in People application. */ protected void clearCachedData(Context context) { LoginPreferences.clearPreferencesFile(context); LoginPreferences.clearCachedLoginDetails(); mFirstTimeLogin = true; mScanThirdPartyAccounts = true; mIdentityBeingProcessed = -1; mAcceptedTermsAndConditions = false; mMeProfileSummary = null; mCurrentContact = null; mCurrentContactSummary = null; mServiceStatus = ServiceStatus.ERROR_UNKNOWN; mThirdPartyAccountsCache = null; mSyncStatus = null; + + mIsAddAccountActivityOpened = false; } /** * Gets the ME profile object. * * @return The ME profile object. */ public ContactSummary getMeProfile() { return mMeProfileSummary; } /** * Sets the ME profile object. * * @param summary ContyactSummary for Me profile. */ public void setMeProfile(ContactSummary summary) { mMeProfileSummary = summary; } /** * Gets the contact currently being viewed in the UI. * * @return The currently view contact. */ public Contact getCurrentContact() { return mCurrentContact; } /** * Sets the contact currently being viewed in the UI. * * @param contact The currently viewed contact. */ public void setCurrentContact(Contact contact) { mCurrentContact = contact; } /** * Gets the summary information of the contact currently being viewed in the * UI. * * @return Contact summary information. */ public ContactSummary getCurrentContactSummary() { return mCurrentContactSummary; } /** * Sets the summary information of the contact currently being viewed in the * UI. * * @param contactSummary Contact summary information. */ public void setCurrentContactSummary(ContactSummary contactSummary) { mCurrentContactSummary = contactSummary; } /** * Return status of request issued to People service. * * @return status of request issued to People service. */ public ServiceStatus getServiceStatus() { return mServiceStatus; } /** * Set status of request issued to People service. * * @param status of request issued to People service. */ public void setServiceStatus(ServiceStatus status) { mServiceStatus = status; } /** * Cache list of 3rd party accounts (Identities) associated with current * login. * * @param list List of ThirdPartyAccount items retrieved from current login. */ public void storeThirdPartyAccounts(Context context, ArrayList<ThirdPartyAccount> list) { setValue(context, FACEBOOK_SUBSCRIBED, isFacebookInThirdPartyAccountList(list) + ""); setValue(context, HYVES_SUBSCRIBED, isHyvesInThirdPartyAccountList(list) + ""); mThirdPartyAccountsCache = list; } /** * Return cached list of 3rd party accounts (Identities) associated with * current login. * * @return List of ThirdPartyAccount items retrieved from current login. */ public ArrayList<ThirdPartyAccount> getThirdPartyAccounts() { return mThirdPartyAccountsCache; } /*** * Return TRUE if the given ThirdPartyAccount contains a Facebook account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Facebook account. */ private static boolean isFacebookInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("facebook")) { if (thirdPartyAccount.isChecked()) { LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook is checked"); return true; } else { LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook is unchecked"); return false; } } } } LogUtils.logV("ApplicationCache." + "isFacebookInThirdPartyAccountList() Facebook not found in list"); return false; } /*** * Return TRUE if the given ThirdPartyAccount contains a Hyves account. * * @param list List of ThirdPartyAccount objects, can be NULL. * @return TRUE if the given ThirdPartyAccount contains a Hyves account. */ private static boolean isHyvesInThirdPartyAccountList(ArrayList<ThirdPartyAccount> list) { if (list != null) { for (ThirdPartyAccount thirdPartyAccount : list) { if (thirdPartyAccount.getDisplayName().toLowerCase().startsWith("hyves")) { if (thirdPartyAccount.isChecked()) { LogUtils .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is checked"); return true; } else { LogUtils .logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves is unchecked"); return false; } } } } LogUtils.logV("ApplicationCache.isHyvesInThirdPartyAccountList() Hyves not found in list"); return false; } /** * Get list of IDs of Home-screen widgets. * * @param context Current context. * @return list of IDs of Home-screen widgets. */ public int[] getWidgetIdList(Context context) { if(sWidgetProviderClassName != null) { return AppWidgetManager.getInstance(context).getAppWidgetIds( new ComponentName(context, sWidgetProviderClassName)); } return null; } /*** * Set a value in the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param value Preference value. */ private static void setValue(Context context, String key, String value) { SharedPreferences.Editor editor = context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(key, value); if (!editor.commit()) { throw new NullPointerException("MainApplication.setValue() Failed to set key[" + key + "] with value[" + value + "]"); } LogUtils.logV("ApplicationCache.setValue() key [" + key + "] value [" + value + "] saved to properties file"); } /*** * Gets the current sync state, or NULL if the state has not been set in * this JVM instance. * * @return SyncStatus or NULL. */ public SyncStatus getSyncStatus() { return mSyncStatus; } /*** * Sets the current sync status. * * @param syncStatus New sync status. */ public void setSyncStatus(SyncStatus syncStatus) { mSyncStatus = syncStatus; } /*** * Get a value from the preferences file. * * @param context Android context. * @param key Preferences file parameter key. * @param defaultValue Preference value. * @return */ private static String getValue(Context context, String key, String defaultValue) { return context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).getString(key, defaultValue); } /*** * Return the resource ID for the SNS Subscribed warning (e.g. * facebook/hyves/etc posting), or -1 if no warning is necessary. * * @param context Android context. * @return Resource ID for textView or -1 is warning is not required. * @throws InvalidParameterException when context is NULL. */ public static int getSnsSubscribedWarningId(Context context) { if (context == null) { throw new InvalidParameterException("ApplicationCache.getSnsSubscribedWarningId() " + "context cannot be NULL"); } boolean facebook = getValue(context, FACEBOOK_SUBSCRIBED, "").equals("true"); boolean hyves = getValue(context, HYVES_SUBSCRIBED, "").equals("true"); if (facebook && hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves_and_facebook; } else if (facebook) { return R.string.ContactStatusListActivity_update_status_on_facebook; } else if (hyves) { return R.string.ContactStatusListActivity_update_status_on_hyves; } else { return -1; } } public static boolean isBooleanValue(Context context, String key) { return TRUE.equals(getValue(context, key, FALSE)); } public static void setBooleanValue(Context context, String key, boolean value) { setValue(context, key, value ? TRUE : FALSE); } /** * Gets the summary information of the Timeline currently being viewed in the * UI. * * @return Timeline summary information. */ public TimelineSummaryItem getCurrentTimelineSummary() { return mCurrentTimelineSummary; } /** * Sets the summary information of the Timeline Item currently being viewed in the * UI. * * @param timelineSummary Timeline summary information. */ public void setCurrentTimelineSummary(TimelineSummaryItem timelineSummary) { mCurrentTimelineSummary = timelineSummary; } /*** * Set the Terms of Service content into the cache. * * @param value Terms of Service content. * @param context Android context. */ public static void setTermsOfService(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(TERMS_OF_SERVICE, value); editor.putLong(TERMS_OF_SERVICE_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setTermsOfService() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Set the Privacy content into the cache. * * @param value Privacy content. * @param context Android context. */ public static void setPrivacyStatemet(final String value, final Context context) { SharedPreferences.Editor editor = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0).edit(); editor.putString(PRIVACY, value); editor.putLong(PRIVACY_TIME, System.currentTimeMillis()); if (!editor.commit()) { throw new NullPointerException( "MainApplication.setPrivacyStatemet() Failed to set Terms " + "of Service with value[" + value + "]"); } } /*** * Get the Terms of Service content from the cache. Will return NULL if * there is no content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Terms of Service content */ public static String getTermsOfService(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(TERMS_OF_SERVICE_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME) { return null; } else { return sharedPreferences.getString(TERMS_OF_SERVICE, null); } } /*** * Get the Privacy content from the cache. Will return NULL if there is no * content, or it is over REFRESH_TIME ms old. * * @param context Android context. * @return Privacy content */ public static String getPrivacyStatement(final Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( ApplicationCache.PREFS_FILE, 0); long time = sharedPreferences.getLong(PRIVACY_TIME, -1); if (time == -1 || time < System.currentTimeMillis() - REFRESH_TIME) { return null; } else { return sharedPreferences.getString(PRIVACY, null); } } private static ServiceStatus sStatus = ServiceStatus.SUCCESS; public static void setTermsStatus(final ServiceStatus status) { sStatus = status; } public static ServiceStatus getTermsStatus() { return sStatus; } /** * @param currentContactFilter the mCurrentContactFilter to set */ public final void setCurrentContactFilter(final long currentContactFilter) { mCurrentContactFilter = currentContactFilter; } /** * @return the mCurrentContactFilter */ public final long getCurrentContactFilter() { return mCurrentContactFilter; } }
360/360-Engine-for-Android
ec7b5ca107e2a1f972549977f9346b3bcc2b394f
Fixed sql query for getting timeline items
diff --git a/src/com/vodafone360/people/database/tables/ActivitiesTable.java b/src/com/vodafone360/people/database/tables/ActivitiesTable.java index f3c3aa9..bd271fa 100644 --- a/src/com/vodafone360/people/database/tables/ActivitiesTable.java +++ b/src/com/vodafone360/people/database/tables/ActivitiesTable.java @@ -736,1026 +736,1027 @@ public abstract class ActivitiesTable { context.getContentResolver().delete(Calls.CONTENT_URI, Calls.NUMBER + "=" + timelineItem.mContactAddress, null); } } } String whereClause = null; //Delete from People Client database if(timelineItem.mLocalContactId != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.LOCAL_CONTACT_ID + "='" + timelineItem.mLocalContactId + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } else if(timelineItem.mContactAddress != null) { if(timelineItem.mNativeThreadId == null) { // Delete CallLogs & Chat Logs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + " IS NULL;"; } else { //Delete Sms/MmsLogs whereClause = Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + " AND " + Field.CONTACT_ADDRESS + "='" + timelineItem.mContactAddress + "' AND " + Field.NATIVE_THREAD_ID + "=" + timelineItem.mNativeThreadId + ";"; } } if (writableDb.delete(TABLE_NAME, whereClause, null) < 0) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivity() " + "Unable to delete specified activity", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } /** * Deletes all the timeline activities for a particular contact from the table. * * @param Context * @param timelineItem TimelineSummaryItem to be deleted * @param writableDb Writable SQLite database * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteTimelineActivities(Context context, TimelineSummaryItem latestTimelineItem, SQLiteDatabase writableDb, SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.deleteTimelineActivities()"); Cursor cursor = null; try { TimelineNativeTypes[] typeList = null; TimelineSummaryItem timelineItem = null; //For CallLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } //For SmsLog/MmsLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } //For ChatLog Timeline typeList = new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }; cursor = fetchTimelineEventsForContact(0L, latestTimelineItem.mLocalContactId, latestTimelineItem.mContactName, typeList, null, readableDb); if(cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); timelineItem = getTimelineData(cursor); if(timelineItem != null) { deleteTimelineActivity(context, timelineItem, writableDb, readableDb); } } } catch (SQLException e) { LogUtils.logE("ActivitiesTable.deleteTimelineActivities() " + "Unable to delete timeline activities", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if(cursor != null) { CloseUtils.close(cursor); } } return ServiceStatus.SUCCESS; } /** * Fetches timeline events grouped by local contact ID, name or contact * address. Events returned will be in reverse-chronological order. If a * native type list is provided the result will be filtered by the list. * * @param minTimeStamp Only timeline events from this date will be returned * @param nativeTypes A list of native types to filter the result, or null * to return all. * @param readableDb Readable SQLite database * @return A cursor containing the result. The * {@link #getTimelineData(Cursor)} method should be used for * reading the cursor. */ public static Cursor fetchTimelineEventList(final Long minTimeStamp, final TimelineNativeTypes[] nativeTypes, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.fetchTimelineEventList() " + "minTimeStamp[" + minTimeStamp + "]"); try { int andVal = 1; String typesQuery = " AND "; if (nativeTypes != null) { typesQuery += DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), nativeTypes, "OR"); typesQuery += " AND "; andVal = 2; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + Field.TIMESTAMP + " > " + minTimeStamp + " AND (" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") ORDER BY " + Field.TIMESTAMP + " DESC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchLastUpdateTime() " + "Unable to fetch timeline event list", e); return null; } } /** * Adds a list of timeline events to the database. Each event is grouped by * contact and grouped by contact + native type. * * @param itemList List of timeline events * @param isCallLog true to group all activities with call logs, false to * group with messaging * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error */ public static ServiceStatus addTimelineEvents( final ArrayList<TimelineSummaryItem> itemList, final boolean isCallLog, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addTimelineEvents()"); TimelineNativeTypes[] activityTypes; if (isCallLog) { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.CallLog }; } else { activityTypes = new TimelineNativeTypes[] { TimelineNativeTypes.SmsLog, TimelineNativeTypes.MmsLog }; } for (TimelineSummaryItem item : itemList) { try { writableDb.beginTransaction(); if (findNativeActivity(item.mNativeItemId, item.mNativeItemType, writableDb)) { continue; } int latestStatusVal = 0; if (item.mContactName != null || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, activityTypes, writableDb); } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM); values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } item.mLocalActivityId = writableDb.insert(TABLE_NAME, null, values); if (item.mLocalActivityId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "ERROR_DATABASE_CORRUPT - Unable to add " + "timeline list to database"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /** * The method returns the ROW_ID i.e. the INTEGER PRIMARY KEY AUTOINCREMENT * field value for the inserted row, i.e. LOCAL_ID. * * @param item TimelineSummaryItem. * @param read - TRUE if the chat message is outgoing or gets into the * timeline history view for a contact with LocalContactId. * @param writableDb Writable SQLite database. * @return LocalContactID or -1 if the row was not inserted. */ public static long addChatTimelineEvent(final TimelineSummaryItem item, final boolean read, final SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "DatabaseHelper.addChatTimelineEvent()"); try { writableDb.beginTransaction(); int latestStatusVal = 0; if (item.mContactName != null || item.mLocalContactId != null) { latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, null, writableDb); latestStatusVal |= removeContactGroup(item.mLocalContactId, item.mContactName, item.mTimestamp, ActivityItem.TIMELINE_ITEM, new TimelineNativeTypes[] { TimelineNativeTypes.ChatLog }, writableDb); } ContentValues values = new ContentValues(); values.put(Field.CONTACT_NAME.toString(), item.mContactName); values.put(Field.CONTACT_ID.toString(), item.mContactId); values.put(Field.USER_ID.toString(), item.mUserId); values.put(Field.LOCAL_CONTACT_ID.toString(), item.mLocalContactId); values.put(Field.CONTACT_NETWORK.toString(), item.mContactNetwork); values.put(Field.DESCRIPTION.toString(), item.mDescription); /** Chat message body. **/ values.put(Field.TITLE.toString(), item.mTitle); values.put(Field.CONTACT_ADDRESS.toString(), item.mContactAddress); if (read) { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); } else { values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | 0); } values.put(Field.NATIVE_ITEM_ID.toString(), item.mNativeItemId); values.put(Field.NATIVE_ITEM_TYPE.toString(), item.mNativeItemType); values.put(Field.TIMESTAMP.toString(), item.mTimestamp); if (item.mType != null) { values.put(Field.TYPE.toString(), item.mType.getTypeCode()); } values.put(Field.LATEST_CONTACT_STATUS.toString(), latestStatusVal); values.put(Field.NATIVE_THREAD_ID.toString(), item.mNativeThreadId); /** Conversation ID for chat message. **/ // values.put(Field.URI.toString(), item.conversationId); // 0 for incoming, 1 for outgoing if (item.mIncoming != null) { values.put(Field.INCOMING.toString(), item.mIncoming.ordinal()); } final long itemId = writableDb.insert(TABLE_NAME, null, values); if (itemId < 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() - " + "Unable to add timeline list to database, index<0:" + itemId); return -1; } writableDb.setTransactionSuccessful(); return itemId; } catch (SQLException e) { LogUtils.logE("ActivitiesTable.addTimelineEvents() SQLException - " + "Unable to add timeline list to database", e); return -1; } finally { writableDb.endTransaction(); } } /** * Clears the grouping of an activity in the database, if the given activity * is newer. This is so that only the latest activity is returned for a * particular group. Each activity is associated with two groups: * <ol> * <li>All group - Grouped by contact only</li> * <li>Native group - Grouped by contact and native type (call log or * messaging)</li> * </ol> * The group to be removed is determined by the activityTypes parameter. * Grouping must also work for timeline events that are not associated with * a contact. The following fields are used to do identify a contact for the * grouping (in order of priority): * <ol> * <li>localContactId - If it not null</li> * <li>name - If this is a valid telephone number, the match will be done to * ensure that the same phone number written in different ways will be * included in the group. See {@link #fetchNameWhereClause(Long, String)} * for more information.</li> * </ol> * * @param localContactId Local contact Id or NULL if the activity is not * associated with a contact. * @param name Name of contact or contact address (telephone number, email, * etc). * @param newUpdateTime The time that the given activity has occurred * @param flag Bitmap of types including: * <ul> * <li>{@link ActivityItem#TIMELINE_ITEM} - Timeline items</li> * <li>{@link ActivityItem#STATUS_ITEM} - Status item</li> * <li>{@link ActivityItem#ALREADY_READ} - Items that have been * read</li> * </ul> * @param activityTypes A list of native types to include in the grouping. * Currently, only two groups are supported (see above). If this * parameter is null the contact will be added to the * "all group", otherwise the contact is added to the native * group. * @param writableDb Writable SQLite database * @return The latest contact status value which should be added to the * current activities grouping. */ private static int removeContactGroup(final Long localContactId, final String name, final Long newUpdateTime, final int flag, final TimelineNativeTypes[] activityTypes, final SQLiteDatabase writableDb) { String whereClause = ""; int andVal = 1; if (activityTypes != null) { whereClause = DatabaseHelper.createWhereClauseFromList( Field.NATIVE_ITEM_TYPE.toString(), activityTypes, "OR"); whereClause += " AND "; andVal = 2; } String nameWhereClause = fetchNameWhereClause(localContactId, name); if (nameWhereClause == null) { return 0; } whereClause += nameWhereClause; Long prevTime = null; Long prevLocalId = null; Integer prevLatestContactStatus = null; Cursor cursor = null; try { cursor = writableDb.rawQuery("SELECT " + Field.TIMESTAMP + "," + Field.LOCAL_ACTIVITY_ID + "," + Field.LATEST_CONTACT_STATUS + " FROM " + TABLE_NAME + " WHERE " + whereClause + " AND " + "(" + Field.LATEST_CONTACT_STATUS + " & " + andVal + ") AND (" + Field.FLAG + "&" + flag + ") ORDER BY " + Field.TIMESTAMP + " DESC", null); if (cursor.moveToFirst()) { prevTime = cursor.getLong(0); prevLocalId = cursor.getLong(1); prevLatestContactStatus = cursor.getInt(2); } } catch (SQLException e) { return 0; } finally { CloseUtils.close(cursor); } if (prevTime != null && newUpdateTime != null) { if (newUpdateTime >= prevTime) { ContentValues cv = new ContentValues(); cv.put(Field.LATEST_CONTACT_STATUS.toString(), prevLatestContactStatus & (~andVal)); if (writableDb.update(TABLE_NAME, cv, Field.LOCAL_ACTIVITY_ID + "=" + prevLocalId, null) <= 0) { LogUtils.logE("ActivitiesTable.addTimelineEvents() " + "Unable to update timeline as the latest"); return 0; } return andVal; } else { return 0; } } return andVal; } /** * Checks if an activity exists in the database. * * @param nativeId The native ID which links the activity with the record in * the native table. * @param type The native type (An ordinal from the #TimelineNativeTypes * enumeration) * @param readableDb Readable SQLite database * @return true if the activity was found, false otherwise */ private static boolean findNativeActivity(final int nativeId, final int type, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper.findNativeActivity()"); Cursor cursor = null; boolean result = false; try { final String[] args = { Integer.toString(nativeId), Integer.toString(type) }; cursor = readableDb.rawQuery("SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_ID + "=? AND " + Field.NATIVE_ITEM_TYPE + "=?", args); if (cursor.moveToFirst()) { result = true; } } finally { CloseUtils.close(cursor); } return result; } /** * Returns a string which can be added to the where clause in an SQL query * on the activities table, to filter the result for a specific contact or * name. The clause will prioritise in the following way: * <ol> * <li>Use localContactId - If it not null</li> * <li>Use name - If this is a valid telephone number, the match will be * done to ensure that the same phone number written in different ways will * be included in the group. * </ol> * * @param localContactId The local contact ID, or null if the contact does * not exist in the People database. * @param name A string containing the name, or a telephone number/email * identifying the contact. * @return The where clause string */ private static String fetchNameWhereClause(final Long localContactId, final String name) { DatabaseHelper.trace(false, "DatabaseHelper.fetchNameWhereClause()"); if (localContactId != null) { return Field.LOCAL_CONTACT_ID + "=" + localContactId; } if (name == null) { return null; } final String searchName = DatabaseUtils.sqlEscapeString(name); if (PhoneNumberUtils.isWellFormedSmsAddress(name)) { - return "PHONE_NUMBERS_EQUAL(" + Field.CONTACT_NAME + "," - + searchName + ")"; + return "(PHONE_NUMBERS_EQUAL(" + Field.CONTACT_NAME + "," + + searchName + ") OR "+ Field.CONTACT_NAME + "=" + + searchName+")"; } else { return Field.CONTACT_NAME + "=" + searchName; } } /** * Returns the timeline summary data from the current location of the given * cursor. The cursor can be obtained using * {@link #fetchTimelineEventList(Long, TimelineNativeTypes[], * SQLiteDatabase)} or * {@link #fetchTimelineEventsForContact(Long, Long, String, * TimelineNativeTypes[], SQLiteDatabase)}. * * @param cursor Cursor in the required position. * @return A filled out TimelineSummaryItem object */ public static TimelineSummaryItem getTimelineData(final Cursor cursor) { DatabaseHelper.trace(false, "DatabaseHelper.getTimelineData()"); TimelineSummaryItem item = new TimelineSummaryItem(); item.mLocalActivityId = SqlUtils.setLong(cursor, Field.LOCAL_ACTIVITY_ID.toString(), null); item.mTimestamp = SqlUtils.setLong(cursor, Field.TIMESTAMP.toString(), null); item.mContactName = SqlUtils.setString(cursor, Field.CONTACT_NAME.toString()); if (!cursor.isNull( cursor.getColumnIndex(Field.CONTACT_AVATAR_URL.toString()))) { item.mHasAvatar = true; } item.mLocalContactId = SqlUtils.setLong(cursor, Field.LOCAL_CONTACT_ID.toString(), null); item.mTitle = SqlUtils.setString(cursor, Field.TITLE.toString()); item.mDescription = SqlUtils.setString(cursor, Field.DESCRIPTION.toString()); item.mContactNetwork = SqlUtils.setString(cursor, Field.CONTACT_NETWORK.toString()); item.mNativeItemType = SqlUtils.setInt(cursor, Field.NATIVE_ITEM_TYPE.toString(), null); item.mNativeItemId = SqlUtils.setInt(cursor, Field.NATIVE_ITEM_ID.toString(), null); item.mType = SqlUtils.setActivityItemType(cursor, Field.TYPE.toString()); item.mContactId = SqlUtils.setLong(cursor, Field.CONTACT_ID.toString(), null); item.mUserId = SqlUtils.setLong(cursor, Field.USER_ID.toString(), null); item.mNativeThreadId = SqlUtils.setInt(cursor, Field.NATIVE_THREAD_ID.toString(), null); item.mContactAddress = SqlUtils.setString(cursor, Field.CONTACT_ADDRESS.toString()); item.mIncoming = SqlUtils.setTimelineSummaryItemType(cursor, Field.INCOMING.toString()); return item; } /** * Fetches timeline events for a specific contact identified by local * contact ID, name or address. Events returned will be in * reverse-chronological order. If a native type list is provided the result * will be filtered by the list. * * @param timeStamp Only events from this time will be returned * @param localContactId The local contact ID if the contact is in the * People database, or null. * @param name The name or address of the contact (required if local contact * ID is NULL). * @param nativeTypes A list of required native types to filter the result, * or null to return all timeline events for the contact. * @param readableDb Readable SQLite database * @param networkName The name of the network the contacts belongs to * (required in order to provide appropriate chat messages * filtering) If the parameter is null messages from all networks * will be returned. The values are the * SocialNetwork.VODAFONE.toString(), * SocialNetwork.GOOGLE.toString(), or * SocialNetwork.MICROSOFT.toString() results. * @return The cursor that can be read using * {@link #getTimelineData(Cursor)}. */ public static Cursor fetchTimelineEventsForContact(final Long timeStamp, final Long localContactId, final String name, final TimelineNativeTypes[] nativeTypes, final String networkName, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "fetchTimelineEventsForContact()"); try { String typesQuery = " AND "; if (nativeTypes.length > 0) { StringBuffer typesQueryBuffer = new StringBuffer(); typesQueryBuffer.append(" AND ("); for (int i = 0; i < nativeTypes.length; i++) { final TimelineNativeTypes type = nativeTypes[i]; typesQueryBuffer.append(Field.NATIVE_ITEM_TYPE + "=" + type.ordinal()); if (i < nativeTypes.length - 1) { typesQueryBuffer.append(" OR "); } } typesQueryBuffer.append(") AND "); typesQuery = typesQueryBuffer.toString(); } /** Filter by account. **/ String networkQuery = ""; String queryNetworkName = networkName; if (queryNetworkName != null) { if (queryNetworkName.equals(SocialNetwork.PC.toString()) || queryNetworkName.equals( SocialNetwork.MOBILE.toString())) { queryNetworkName = SocialNetwork.VODAFONE.toString(); } networkQuery = Field.CONTACT_NETWORK + "='" + queryNetworkName + "' AND "; } String whereAppend; if (localContactId == null) { whereAppend = Field.LOCAL_CONTACT_ID + " IS NULL AND " + fetchNameWhereClause(localContactId, name); if (whereAppend == null) { return null; } } else { whereAppend = Field.LOCAL_CONTACT_ID + "=" + localContactId; } String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + "," + Field.INCOMING + " FROM " + TABLE_NAME + " WHERE (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")" + typesQuery + networkQuery + whereAppend + " ORDER BY " + Field.TIMESTAMP + " ASC"; return readableDb.rawQuery(query, null); } catch (SQLiteException e) { LogUtils.logE("ActivitiesTable.fetchTimelineEventsForContact() " + "Unable to fetch timeline event for contact list", e); return null; } } /** * Mark the chat timeline events for a given contact as read. * * @param localContactId Local contact ID. * @param networkName Name of the SNS. * @param writableDb Writable SQLite reference. * @return Number of rows affected by database update. */ public static int markChatTimelineEventsForContactAsRead( final Long localContactId, final String networkName, final SQLiteDatabase writableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "fetchTimelineEventsForContact()"); ContentValues values = new ContentValues(); values.put(Field.FLAG.toString(), ActivityItem.TIMELINE_ITEM | ActivityItem.ALREADY_READ); String networkQuery = ""; if (networkName != null) { networkQuery = " AND (" + Field.CONTACT_NETWORK + "='" + networkName + "')"; } final String where = Field.LOCAL_CONTACT_ID + "=" + localContactId + " AND " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" /** * If the network is null, set all messages as read for this * contact. */ + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")" + networkQuery; return writableDb.update(TABLE_NAME, values, where, null); } /** * Returns the timestamp for the newest status event for a given server * contact. * * @param local contact id Server contact ID * @param readableDb Readable SQLite database * @return The timestamp in milliseconds, or 0 if not found. */ public static long fetchLatestStatusTimestampForContact(final long localContactId, final SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "fetchLatestStatusTimestampForContact()"); Cursor cursor = null; try { String query = "SELECT MAX( " + ActivitiesTable.Field.TIMESTAMP + ") FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + " = " + localContactId + " AND " + Field.TYPE + "='" + ActivityItem.Type.CONTACT_SENT_STATUS_UPDATE.toString().toLowerCase() + "'"; cursor = readableDb.rawQuery(query, null); if (cursor.moveToFirst() && !cursor.isNull(0)) { return cursor.getLong(0); } else { return 0; } } finally { CloseUtils.close(cursor); } } /** * Updates timeline when a new contact is added to the People database. * Updates all timeline events that are not associated with a contact and * have a phone number that matches the oldName parameter. * * @param oldName The telephone number (since is the name of an activity * that is not associated with a contact) * @param newName The new name * @param newLocalContactId The local Contact Id for the added contact. * @param newContactId The server Contact Id for the added contact (or null * if the contact has not yet been synced). * @param witeableDb Writable SQLite database */ public static void updateTimelineContactNameAndId(final String oldName, final String newName, final Long newLocalContactId, final Long newContactId, final SQLiteDatabase witeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "updateTimelineContactNameAndId()"); try { ContentValues values = new ContentValues(); if (newName != null) { values.put(Field.CONTACT_NAME.toString(), newName); } else { LogUtils.logE("updateTimelineContactNameAndId() " + "newName should never be null"); } if (newLocalContactId != null) { values.put(Field.LOCAL_CONTACT_ID.toString(), newLocalContactId); } else { LogUtils.logE("updateTimelineContactNameAndId() " + "newLocalContactId should never be null"); } if (newContactId != null) { values.put(Field.CONTACT_ID.toString(), newContactId); } else { /** * newContactId will be null if adding a contact from the UI. */ LogUtils.logI("updateTimelineContactNameAndId() " + "newContactId is null"); /** * We haven't got server Contact it, it means it haven't been * synced yet. */ } String name = ""; if (oldName != null) { name = oldName; LogUtils.logW("ActivitiesTable." + "updateTimelineContactNameAndId() oldName is NULL"); } String[] args = { "2", name }; String whereClause = Field.LOCAL_CONTACT_ID + " IS NULL AND " + Field.FLAG + "=? AND PHONE_NUMBERS_EQUAL(" + Field.CONTACT_ADDRESS + ",?)"; witeableDb.update(TABLE_NAME, values, whereClause, args); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.updateTimelineContactNameAndId() " + "Unable update table", e); throw e; } } /** * Updates the timeline when a contact name is modified in the database. * * @param newName The new name. * @param localContactId Local contact Id which was modified. * @param witeableDb Writable SQLite database */ public static void updateTimelineContactNameAndId(final String newName, final Long localContactId, final SQLiteDatabase witeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "updateTimelineContactNameAndId()"); if (newName == null || localContactId == null) { LogUtils.logE("updateTimelineContactNameAndId() newName or " + "localContactId == null newName(" + newName + ") localContactId(" + localContactId + ")"); return; } try { ContentValues values = new ContentValues(); Long cId = ContactsTable.fetchServerId(localContactId, witeableDb); values.put(Field.CONTACT_NAME.toString(), newName); if (cId != null) { values.put(Field.CONTACT_ID.toString(), cId); } String[] args = { localContactId.toString() }; String whereClause = Field.LOCAL_CONTACT_ID + "=?"; witeableDb.update(TABLE_NAME, values, whereClause, args); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.updateTimelineContactNameAndId()" + " Unable update table", e); } } /** * Updates the timeline entries in the activities table to remove deleted * contact info. * * @param localContactId - the contact id that has been deleted * @param writeableDb - reference to the database */ public static void removeTimelineContactData(final Long localContactId, final SQLiteDatabase writeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "removeTimelineContactData()"); if (localContactId == null) { LogUtils.logE("removeTimelineContactData() localContactId == null " + "localContactId(" + localContactId + ")"); return; } try { //Remove all the Chat Entries removeChatTimelineForContact(localContactId, writeableDb); String[] args = { localContactId.toString() }; String query = "UPDATE " + TABLE_NAME + " SET " + Field.LOCAL_CONTACT_ID + "=NULL, " + Field.CONTACT_ID + "=NULL, " + Field.CONTACT_NAME + "=" + Field.CONTACT_ADDRESS + " WHERE " + Field.LOCAL_CONTACT_ID + "=? AND (" + Field.FLAG + "&" + ActivityItem.TIMELINE_ITEM + ")"; writeableDb.execSQL(query, args); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.removeTimelineContactData() Unable " + "to update table: \n", e); } } /** * Removes all the items from the chat timeline for the given contact. * * @param localContactId Given contact ID. * @param writeableDb Writable SQLite database. */ private static void removeChatTimelineForContact( final Long localContactId, final SQLiteDatabase writeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "removeChatTimelineForContact()"); if (localContactId == null || (localContactId == -1)) { LogUtils.logE("removeChatTimelineForContact() localContactId == " + "null " + "localContactId(" + localContactId + ")"); return; } final String query = Field.LOCAL_CONTACT_ID + "=" + localContactId + " AND (" + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + ")"; try { writeableDb.delete(TABLE_NAME, query, null); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.removeChatTimelineForContact() " + "Unable to update table", e); } } /** * Removes items from the chat timeline that are not for the given contact. * * @param localContactId Given contact ID. * @param writeableDb Writable SQLite database. */ public static void removeChatTimelineExceptForContact( final Long localContactId, final SQLiteDatabase writeableDb) { DatabaseHelper.trace(false, "DatabaseHelper." + "removeTimelineContactData()"); if (localContactId == null || (localContactId == -1)) { LogUtils.logE("removeTimelineContactData() localContactId == null " + "localContactId(" + localContactId + ")"); return; } try { final long olderThan = System.currentTimeMillis() - Settings.HISTORY_IS_WEEK_LONG; final String query = Field.LOCAL_CONTACT_ID + "!=" + localContactId + " AND (" + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + ") AND (" + Field.TIMESTAMP + "<" + olderThan + ")"; writeableDb.delete(TABLE_NAME, query, null); } catch (SQLException e) { LogUtils.logE("ActivitiesTable.removeTimelineContactData() " + "Unable to update table", e); } } /*** * Returns the number of users have currently have unread chat messages. * * @param readableDb Reference to a readable database. * @return Number of users with unread chat messages. */ public static int getNumberOfUnreadChatUsers( final SQLiteDatabase readableDb) { final String query = "SELECT " + Field.LOCAL_CONTACT_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" /** * This condition below means the timeline is not yet marked * as READ. */ + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; Cursor cursor = null; try { cursor = readableDb.rawQuery(query, null); ArrayList<Long> ids = new ArrayList<Long>(); Long id = null; while (cursor.moveToNext()) { id = cursor.getLong(0); if (!ids.contains(id)) { ids.add(id); } } return ids.size(); } finally { CloseUtils.close(cursor); } } /*** * Returns the number of unread chat messages. * * @param readableDb Reference to a readable database. * @return Number of unread chat messages. */ public static int getNumberOfUnreadChatMessages( final SQLiteDatabase readableDb) { final String query = "SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ")"; Cursor cursor = null; try { cursor = readableDb.rawQuery(query, null); return cursor.getCount(); } finally { CloseUtils.close(cursor); } } /*** * Returns the number of unread chat messages for this contact besides this * network. * * @param localContactId Given contact ID. * @param network SNS name. * @param readableDb Reference to a readable database. * @return Number of unread chat messages. */ public static int getNumberOfUnreadChatMessagesForContactAndNetwork( final long localContactId, final String network, final SQLiteDatabase readableDb) { final String query = "SELECT " + Field.ACTIVITY_ID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVE_ITEM_TYPE + "=" + TimelineNativeTypes.ChatLog.ordinal() + " AND (" + Field.FLAG + "=" + ActivityItem.TIMELINE_ITEM + ") AND (" + Field.LOCAL_CONTACT_ID + "=" + localContactId + ") AND (" + Field.CONTACT_NETWORK + "!=\"" + network + "\")"; Cursor cursor = null; try { cursor = readableDb.rawQuery(query, null); return cursor.getCount(); } finally { CloseUtils.close(cursor); } } /*** * Returns the newest unread chat message. * * @param readableDb Reference to a readable database. * @return TimelineSummaryItem of the newest unread chat message, or NULL if * none are found. */ public static TimelineSummaryItem getNewestUnreadChatMessage( final SQLiteDatabase readableDb) { final String query = "SELECT " + Field.LOCAL_ACTIVITY_ID + "," + Field.TIMESTAMP + "," + Field.CONTACT_NAME + "," + Field.CONTACT_AVATAR_URL + "," + Field.LOCAL_CONTACT_ID + "," + Field.TITLE + "," + Field.DESCRIPTION + "," + Field.CONTACT_NETWORK + "," + Field.NATIVE_ITEM_TYPE + "," + Field.NATIVE_ITEM_ID + "," + Field.TYPE + "," + Field.CONTACT_ID + "," + Field.USER_ID + "," + Field.NATIVE_THREAD_ID + "," + Field.CONTACT_ADDRESS + ","
360/360-Engine-for-Android
34ee029f0fb85a3817d98377cee6a2adcf253d09
fixes for null accounts
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index 5fd5ccd..5f489c1 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,1011 +1,1011 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.accounts.AccountManager; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.OperationApplicationException; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.os.RemoteException; import android.provider.ContactsContract; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.Settings; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Event; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.Website; import android.text.TextUtils; import android.util.SparseArray; import com.vodafone360.people.R; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.VCardHelper.Name; import com.vodafone360.people.datatypes.VCardHelper.Organisation; import com.vodafone360.people.datatypes.VCardHelper.PostalAddress; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * The implementation of the NativeContactsApi for the Android 2.X platform. */ public class NativeContactsApi2 extends NativeContactsApi { /** * Convenience Projection to fetch only a Raw Contact's ID and Native * Account Type */ private static final String[] CONTACTID_PROJECTION = new String[] { RawContacts._ID, RawContacts.ACCOUNT_TYPE }; /** * Raw ID Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_RAW_ID = 0; /** * Account Type Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_ACCOUNT_TYPE = 1; /** * Group ID Projection */ private static final String[] GROUPID_PROJECTION = new String[] { Groups._ID }; /** * Vendor specific account. Only used in 2.x API. */ - private static Account PHONE_ACCOUNT = null; + private static Account sPhoneAccount = null; /** * Regular expression for a date that can be handled by the People Client at * present. Matches the following cases: N-n-n n-n-N Where: - 'n' * corresponds to one or two digits - 'N' corresponds to two or 4 digits */ private static final String COMPLETE_DATE_REGEX = "(?:^\\d{2,4}-\\d{1,2}-\\d{1,2}$|^\\d{1,2}-\\d{1,2}-\\d{2,4}$)"; /** * 'My Contacts' System group where clause */ private static final String MY_CONTACTS_GROUP_WHERE_CLAUSE = Groups.SYSTEM_ID + "=\"Contacts\""; /** * 'My Contacts' System Group Membership where in clause (Multiple 'My * Contacts' IDs) */ private static final String MY_CONTACTS_MULTI_GROUP_MEMBERSHIP = Data.MIMETYPE + "=\"" + GroupMembership.CONTENT_ITEM_TYPE + "\" AND " + Data.DATA1 + " IN ("; /** * Selection where clause for a NULL Account */ private static final String NULL_ACCOUNT_WHERE_CLAUSE = RawContacts.ACCOUNT_NAME + " IS NULL AND " + RawContacts.ACCOUNT_TYPE + " IS NULL"; /** * Selection where clause for an Organization detail. */ private static final String ORGANIZATION_DETAIL_WHERE_CLAUSE = RawContacts.Data.MIMETYPE + "=\"" + Organization.CONTENT_ITEM_TYPE + "\""; /** * The list of Uri that need to be listened to for contacts changes on * native side. */ private static final Uri[] sUri = { ContactsContract.RawContacts.CONTENT_URI, ContactsContract.Data.CONTENT_URI }; /** * Holds mapping from a NAB type (MIME) to a VCard Key */ private static final HashMap<String, Integer> sFromNabContentTypeToKeyMap; /** * Holds mapping from a VCard Key to a NAB type (MIME) */ private static final SparseArray<String> sFromKeyToNabContentTypeArray; static { sFromNabContentTypeToKeyMap = new HashMap<String, Integer>(9, 1); sFromNabContentTypeToKeyMap.put(StructuredName.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NAME); sFromNabContentTypeToKeyMap.put(Nickname.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NICKNAME); sFromNabContentTypeToKeyMap.put(Phone.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_PHONE); sFromNabContentTypeToKeyMap.put(Email.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_EMAIL); sFromNabContentTypeToKeyMap.put(StructuredPostal.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ADDRESS); sFromNabContentTypeToKeyMap .put(Organization.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ORG); sFromNabContentTypeToKeyMap.put(Website.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_URL); sFromNabContentTypeToKeyMap.put(Note.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NOTE); sFromNabContentTypeToKeyMap.put(Event.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_DATE); // sFromNabContentTypeToKeyMap.put( // Photo.CONTENT_ITEM_TYPE, ContactChange.KEY_PHOTO); sFromKeyToNabContentTypeArray = new SparseArray<String>(10); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NAME, StructuredName.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NICKNAME, Nickname.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_PHONE, Phone.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_EMAIL, Email.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ADDRESS, StructuredPostal.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ORG, Organization.CONTENT_ITEM_TYPE); // Special case: VCARD_TITLE maps to the same NAB type as sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_TITLE, Organization.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_URL, Website.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NOTE, Note.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_DATE, Event.CONTENT_ITEM_TYPE); // sFromKeyToNabContentTypeArray.append( // ContactChange.KEY_PHOTO, Photo.CONTENT_ITEM_TYPE); } /** * The observer registered by the upper layer. */ private ContactsObserver mAbstractedObserver; /** * Content values used for writing to NAB. */ private final ContentValues mValues = new ContentValues(); /** * The content observers that listens for native contacts changes. */ private final ContentObserver[] mContentObservers = new ContentObserver[sUri.length]; /** * Array of row ID in the groups table to the "My Contacts" System Group. * The reason for this being an array is because there may be multiple * "My Contacts" groups (Platform Bug!?). */ private long[] mMyContactsGroupRowIds = null; /** * Arguably another example where Organization and Title force us into extra * effort. We use this value to pass the correct detail ID when an 'add * detail' is done for one the two although the other is already present. * Make sure to reset this value for every UpdateContact operation */ private long mExistingOrganizationId = ContactChange.INVALID_ID; /** * Flag to check if we have already read a Birthday detail */ private boolean mHaveReadBirthday = false; /** * Yield value for our ContentProviderOperations. */ private boolean mYield = true; /** * Batch used for Contact Writing operations. */ private BatchOperation mBatch = new BatchOperation(); /** * Inner class for applying batches. TODO: Move to own class if batches * become supported in other areas */ private class BatchOperation { // List for storing the batch mOperations ArrayList<ContentProviderOperation> mOperations; /** * Default constructor */ public BatchOperation() { mOperations = new ArrayList<ContentProviderOperation>(); } /** * Current size of the batch * * @return Size of the batch */ public int size() { return mOperations.size(); } /** * Adds a new operation to the batch * * @param cpo The */ public void add(ContentProviderOperation cpo) { mOperations.add(cpo); } /** * Clears all operations in the batch Effectively resets the batch. */ public void clear() { mOperations.clear(); } public ContentProviderResult[] execute() { ContentProviderResult[] resultArray = null; if (mOperations.size() > 0) { // Apply the mOperations to the content provider try { resultArray = mCr.applyBatch(ContactsContract.AUTHORITY, mOperations); } catch (final OperationApplicationException e1) { LogUtils.logE("storing contact data failed", e1); } catch (final RemoteException e2) { LogUtils.logE("storing contact data failed", e2); } mOperations.clear(); } return resultArray; } } /** * Convenience interface to map the generic DATA column names to the People * profile detail column names. */ private interface PeopleProfileColumns { /** * 360 People profile MIME Type */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/com.vodafone360.people.profile"; /** * 360 People Contact's profile ID (Corresponds to Contact's Internal * Contact ID) */ public static final String DATA_PID = Data.DATA1; /** * 360 People Contact profile Summary */ public static final String DATA_SUMMARY = Data.DATA2; /** * 360 People Contact profile detail */ public static final String DATA_DETAIL = Data.DATA3; } /** * This class holds a native content observer that will be notified in case * of changes on the registered URI. */ private class NativeContentObserver extends ContentObserver { public NativeContentObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { LogUtils.logI("NativeContactsApi2.NativeContentObserver.onChange(" + selfChange + ")"); mAbstractedObserver.onChange(); } } /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { LogUtils.logI("NativeContactsApi2.registerObserver()"); if (mAbstractedObserver != null) { throw new RuntimeException( "Only one observer at a time supported... Please unregister first."); } mAbstractedObserver = observer; final ContentResolver cr = mContext.getContentResolver(); for (int i = 0; i < mContentObservers.length; i++) { mContentObservers[i] = new NativeContentObserver(); cr.registerContentObserver(sUri[i], true, mContentObservers[i]); } } /** * @see NativeContactsApi#unregisterObserver(ContactsObserver) */ @Override public void unregisterObserver() { LogUtils.logI("NativeContactsApi2.unregisterObserver()"); if (mCr != null) { mAbstractedObserver = null; for (int i = 0; i < mContentObservers.length; i++) { if (mContentObservers[i] != null) { mCr.unregisterContentObserver(mContentObservers[i]); mContentObservers[i] = null; } } } } /** * @see NativeContactsApi#initialize() */ @Override protected void initialize() { // perform here any one time initialization - PHONE_ACCOUNT = getVendorSpecificAccount(); + sPhoneAccount = getVendorSpecificAccount(); } /** * @see NativeContactsApi#getAccounts() */ @Override public Account[] getAccounts() { AccountManager accountManager = AccountManager.get(mContext); final android.accounts.Account[] accounts2xApi = accountManager.getAccounts(); Account[] accounts = null; if (accounts2xApi.length > 0) { accounts = new Account[accounts2xApi.length]; for (int i = 0; i < accounts2xApi.length; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } } return accounts; } /** * Reads vendor specific accounts from settings and through accountmanager. * Some phones with custom ui like sense have additional account that we * have to take care of. This method tryes to read them * * @return Account object if vendor specific account is found, null * otherwise */ public Account getVendorSpecificAccount() { // first read the settings String[] PROJECTION = { Settings.ACCOUNT_NAME, Settings.ACCOUNT_TYPE, Settings.UNGROUPED_VISIBLE }; // Get a cursor with all people Cursor cursor = mCr.query(Settings.CONTENT_URI, PROJECTION, null, null, null); // Got no cursor? Return with null! if (null == cursor) { return null; } try { String[] values = new String[cursor.getCount()]; for (int i = 0; i < values.length; i++) { cursor.moveToNext(); if (isVendorSpecificAccount(cursor.getString(1))) { return new Account(cursor.getString(0), cursor.getString(1)); } } } catch (Exception exc) { return null; } CursorUtils.closeCursor(cursor); // nothing found in the settings? try accountmanager Account[] accounts = getAccounts(); if (accounts == null) { return null; } for (Account account : accounts) { if (isVendorSpecificAccount(account.getType())) { return account; } } return null; } /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override public Account[] getAccountsByType(int type) { switch (type) { // people and google type lead to the same block the difference is // then handled inside in two if statements. // Otherwise we would have a lot of redundant code, case PEOPLE_ACCOUNT_TYPE: case GOOGLE_ACCOUNT_TYPE: { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts2xApi = null; // For people account set the people account type string... if (PEOPLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); } // .. and for google the same only with google string. if (GOOGLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(GOOGLE_ACCOUNT_TYPE_STRING); } final int numAccounts = accounts2xApi.length; if (numAccounts > 0) { Account[] accounts = new Account[numAccounts]; for (int i = 0; i < numAccounts; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } return accounts; - }else{ + } else { return null; } } case PHONE_ACCOUNT_TYPE: { - if (PHONE_ACCOUNT==null){ + if (sPhoneAccount == null) { return null; } return new Account[] { - PHONE_ACCOUNT + sPhoneAccount }; } default: return null; } } /** * @see NativeContactsApi#addPeopleAccount(String) */ @Override public boolean addPeopleAccount(String username) { boolean isAdded = false; try { android.accounts.Account account = new android.accounts.Account(username, PEOPLE_ACCOUNT_TYPE_STRING); AccountManager accountMan = AccountManager.get(mContext); isAdded = accountMan.addAccountExplicitly(account, null, null); if (isAdded) { if (VersionUtils.isHtcSenseDevice(mContext)) { createSettingsEntryForAccount(username); } // TODO: RE-ENABLE SYNC VIA SYSTEM ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0); // ContentResolver.setSyncAutomatically(account, // ContactsContract.AUTHORITY, true); } } catch (Exception ex) { LogUtils.logE("People Account creation failed because of exception:\n", ex); } if (isAdded) { // Updating MyContacts Group IDs here for now because it needs to be // done one time just before first time sync. // In the future, this code may change if we modify // the way we retrieve contact IDs. fetchMyContactsGroupRowIds(); } return isAdded; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); return accounts != null && accounts.length > 0; } /** * @see NativeContactsApi#removePeopleAccount() */ @Override public void removePeopleAccount() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); if (accounts != null && accounts.length > 0) { accountMan.removeAccount(accounts[0], null, null); } } /** * @see NativeContactsApi#getContactIds(Account) */ @Override public long[] getContactIds(Account account) { // Need to construct a where clause if (account != null) { final StringBuffer clauseBuffer = new StringBuffer(); clauseBuffer.append(RawContacts.ACCOUNT_NAME); clauseBuffer.append("=\""); clauseBuffer.append(account.getName()); clauseBuffer.append("\" AND "); clauseBuffer.append(RawContacts.ACCOUNT_TYPE); clauseBuffer.append("=\""); clauseBuffer.append(account.getType()); clauseBuffer.append('\"'); return getContactIds(clauseBuffer.toString()); } else { return getContactIds(NULL_ACCOUNT_WHERE_CLAUSE); } } /** * @see NativeContactsApi#getContact(long) */ @Override public ContactChange[] getContact(long nabContactId) { // Reset the boolean flags mHaveReadOrganization = false; mHaveReadBirthday = false; final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, nabContactId); final Uri dataUri = Uri.withAppendedPath(rawContactUri, RawContacts.Data.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(dataUri, null, null, null, null); try { if (cursor != null && cursor.getCount() > 0) { final List<ContactChange> ccList = new ArrayList<ContactChange>(); while (cursor.moveToNext()) { readDetail(cursor, ccList, nabContactId); } return ccList.toArray(new ContactChange[ccList.size()]); } } finally { CursorUtils.closeCursor(cursor); } return null; } /** * @see NativeContactsApi#addContact(Account, ContactChange[]) */ @Override public ContactChange[] addContact(Account account, ContactChange[] ccList) { // Make sure to reset all the member variables we need mYield = true; mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mValues.clear(); mBatch.clear(); mValues.put(RawContacts.ACCOUNT_TYPE, account.getType()); mValues.put(RawContacts.ACCOUNT_NAME, account.getName()); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI)).withYieldAllowed(mYield) .withValues(mValues); mBatch.add(builder.build()); final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc != null) { final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } putDetail(cc); addValuesToBatch(ContactChange.INVALID_ID); } } // Special case for the organization/title if it was flagged in the // putDetail call putOrganization(ccList); addValuesToBatch(ContactChange.INVALID_ID); // Add 360 profile detail addProfileAction(ccList[0].getInternalContactId()); // Execute the batch and Generate ID changes from it return executeNewContactBatch(ccList); } /** * @see NativeContactsApi#updateContact(ContactChange[]) */ @Override public ContactChange[] updateContact(ContactChange[] ccList) { if (ccList == null || ccList.length == 0) { LogUtils.logW("NativeContactsApi2.updateContact() nothing to update - empty ccList!"); return null; } // Make sure to reset all the member variables we need mYield = true; mBatch.clear(); mValues.clear(); mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mExistingOrganizationId = ContactChange.INVALID_ID; final long nabContactId = ccList[0].getNabContactId(); if (nabContactId == ContactChange.INVALID_ID) { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update request because of invalid NAB Contact ID. Internal Contact ID is " + ccList[0].getInternalContactId()); return null; } final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } switch (cc.getType()) { case ContactChange.TYPE_ADD_DETAIL: putDetail(cc); addValuesToBatch(nabContactId); // not a new contact break; case ContactChange.TYPE_UPDATE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { putDetail(cc); addUpdateValuesToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update to detail for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; case ContactChange.TYPE_DELETE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { addDeleteDetailToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring detail deletion for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; default: break; } } updateOrganization(ccList, nabContactId); // Execute the batch and Generate ID changes from it return executeUpdateContactBatch(ccList); } /** * @see NativeContactsApi#removeContact(long) */ @Override public void removeContact(long nabContactId) { mCr.delete(addCallerIsSyncAdapterParameter(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId)), null, null); } /** * @see NativeContactsApi#isKeySupported(int) */ @Override public boolean isKeySupported(int key) { // Only supported if in the SparseArray return sFromKeyToNabContentTypeArray.indexOfKey(key) >= 0; } /** * Inner (private) method for getting contact ids. Allows a cleaner * separation the public API method. * * @param selection The where clause for the operation * @return An array containing the Contact IDs that have been found */ private long[] getContactIds(final String selection) { // Store ids in a temporary array because of possible null values long[] tempIds = null; int idCount = 0; final Cursor cursor = mCr.query(RawContacts.CONTENT_URI, CONTACTID_PROJECTION, selection, null, null); if (cursor == null) { return null; } try { final int cursorCount = cursor.getCount(); if (cursorCount > 0) { tempIds = new long[cursorCount]; while (cursor.moveToNext()) { final long id = cursor.getLong(CONTACTID_PROJECTION_RAW_ID); final String accountType = cursor.getString(CONTACTID_PROJECTION_ACCOUNT_TYPE); // TODO: Remove hardcoding (if statement) if (TextUtils.isEmpty(accountType) || accountType.equals(NativeContactsApi.PEOPLE_ACCOUNT_TYPE_STRING) || isVendorSpecificAccount(accountType) || isContactInMyContactsGroup(id)) { tempIds[idCount] = id; idCount++; } } } } finally { CursorUtils.closeCursor(cursor); } if (idCount > 0) { // Here we copy the array to strip any eventual nulls at the end of // the tempIds array final long[] ids = new long[idCount]; System.arraycopy(tempIds, 0, ids, 0, idCount); return ids; } return null; } /** * Fetches the IDs corresponding to the "My Contacts" System Group The * reason why we return an array is because there may be multiple * "My Contacts" groups. * * @return Array containing all IDs of the "My Contacts" group or null if * none exist */ private void fetchMyContactsGroupRowIds() { final Cursor cursor = mCr.query(Groups.CONTENT_URI, GROUPID_PROJECTION, MY_CONTACTS_GROUP_WHERE_CLAUSE, null, null); if (cursor == null) { return; } try { final int count = cursor.getCount(); if (count > 0) { mMyContactsGroupRowIds = new long[count]; for (int i = 0; i < count; i++) { cursor.moveToNext(); mMyContactsGroupRowIds[i] = cursor.getLong(0); } } } finally { CursorUtils.closeCursor(cursor); } } /** * Checks if a Contact is in the "My Contacts" System Group * * @param nabContactId ID of the Contact to check * @return true if the Contact is in the Group, false if not */ private boolean isContactInMyContactsGroup(long nabContactId) { boolean belongs = false; if (mMyContactsGroupRowIds != null) { final Uri dataUri = Uri.withAppendedPath(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId), RawContacts.Data.CONTENT_DIRECTORY); // build query containing row ID values final StringBuilder sb = new StringBuilder(); sb.append(MY_CONTACTS_MULTI_GROUP_MEMBERSHIP); final int rowIdCount = mMyContactsGroupRowIds.length; for (int i = 0; i < rowIdCount; i++) { sb.append(mMyContactsGroupRowIds[i]); if (i < rowIdCount - 1) { sb.append(','); } } sb.append(')'); final Cursor cursor = mCr.query(dataUri, null, sb.toString(), null, null); try { belongs = cursor != null && cursor.getCount() > 0; } finally { CursorUtils.closeCursor(cursor); } } return belongs; } /** * Reads a Contact Detail from a Cursor into the supplied Contact Change * List. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to read Detail into * @param nabContactId NAB ID of the Contact */ private void readDetail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String mimetype = CursorUtils.getString(cursor, Data.MIMETYPE); final Integer key = sFromNabContentTypeToKeyMap.get(mimetype); if (key != null) { switch (key.intValue()) { case ContactChange.KEY_VCARD_NAME: readName(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_NICKNAME: readNickname(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_PHONE: readPhone(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_EMAIL: readEmail(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ADDRESS: readAddress(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ORG: // Only one Organization can be read (CAB limitation!) if (!mHaveReadOrganization) { readOrganization(cursor, ccList, nabContactId); } break; case ContactChange.KEY_VCARD_URL: readWebsite(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_DATE: if (!mHaveReadBirthday) { readBirthday(cursor, ccList, nabContactId); } break; default: // The default case is also a valid key final String value = CursorUtils.getString(cursor, Data.DATA1); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Data._ID); final ContactChange cc = new ContactChange(key, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } break; } } } /** * Reads an name detail as a {@link ContactChange} from the provided cursor. * For this type of detail we need to use a VCARD (semicolon separated) * value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readName(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using display name only to check if there is a valid name to read final String displayName = CursorUtils.getString(cursor, StructuredName.DISPLAY_NAME); if (!TextUtils.isEmpty(displayName)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredName._ID); // VCard Helper data type (CAB) final Name name = new Name(); // NAB: Given name -> CAB: First name name.firstname = CursorUtils.getString(cursor, StructuredName.GIVEN_NAME); // NAB: Family name -> CAB: Surname name.surname = CursorUtils.getString(cursor, StructuredName.FAMILY_NAME); // NAB: Prefix -> CAB: Title name.title = CursorUtils.getString(cursor, StructuredName.PREFIX); // NAB: Middle name -> CAB: Middle name name.midname = CursorUtils.getString(cursor, StructuredName.MIDDLE_NAME); // NAB: Suffix -> CAB: Suffixes name.suffixes = CursorUtils.getString(cursor, StructuredName.SUFFIX); // NOTE: Ignoring Phonetics (DATA7, DATA8 and DATA9)! // TODO: Need to get middle name and concatenate into value final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NAME, VCardHelper .makeName(name), ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an nickname detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readNickname(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Nickname.NAME); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Nickname._ID); /* * TODO: Decide what to do with nickname: Can only have one in VF360 * but NAB Allows more than one! */ final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NICKNAME, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an phone detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data
360/360-Engine-for-Android
b1c1387aa61807b5c58dbaf69912244bed5a2a85
fixes for null accounts
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index 52cf59d..5fd5ccd 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,1004 +1,1009 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.accounts.AccountManager; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.OperationApplicationException; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.os.RemoteException; import android.provider.ContactsContract; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.Settings; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Event; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.Website; import android.text.TextUtils; import android.util.SparseArray; import com.vodafone360.people.R; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.datatypes.VCardHelper.Name; import com.vodafone360.people.datatypes.VCardHelper.Organisation; import com.vodafone360.people.datatypes.VCardHelper.PostalAddress; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * The implementation of the NativeContactsApi for the Android 2.X platform. */ public class NativeContactsApi2 extends NativeContactsApi { /** * Convenience Projection to fetch only a Raw Contact's ID and Native * Account Type */ private static final String[] CONTACTID_PROJECTION = new String[] { RawContacts._ID, RawContacts.ACCOUNT_TYPE }; /** * Raw ID Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_RAW_ID = 0; /** * Account Type Column for the CONTACTID_PROJECTION Projection */ private static final int CONTACTID_PROJECTION_ACCOUNT_TYPE = 1; /** * Group ID Projection */ private static final String[] GROUPID_PROJECTION = new String[] { Groups._ID }; /** * Vendor specific account. Only used in 2.x API. */ private static Account PHONE_ACCOUNT = null; /** * Regular expression for a date that can be handled by the People Client at * present. Matches the following cases: N-n-n n-n-N Where: - 'n' * corresponds to one or two digits - 'N' corresponds to two or 4 digits */ private static final String COMPLETE_DATE_REGEX = "(?:^\\d{2,4}-\\d{1,2}-\\d{1,2}$|^\\d{1,2}-\\d{1,2}-\\d{2,4}$)"; /** * 'My Contacts' System group where clause */ private static final String MY_CONTACTS_GROUP_WHERE_CLAUSE = Groups.SYSTEM_ID + "=\"Contacts\""; /** * 'My Contacts' System Group Membership where in clause (Multiple 'My * Contacts' IDs) */ private static final String MY_CONTACTS_MULTI_GROUP_MEMBERSHIP = Data.MIMETYPE + "=\"" + GroupMembership.CONTENT_ITEM_TYPE + "\" AND " + Data.DATA1 + " IN ("; /** * Selection where clause for a NULL Account */ private static final String NULL_ACCOUNT_WHERE_CLAUSE = RawContacts.ACCOUNT_NAME + " IS NULL AND " + RawContacts.ACCOUNT_TYPE + " IS NULL"; /** * Selection where clause for an Organization detail. */ private static final String ORGANIZATION_DETAIL_WHERE_CLAUSE = RawContacts.Data.MIMETYPE + "=\"" + Organization.CONTENT_ITEM_TYPE + "\""; /** * The list of Uri that need to be listened to for contacts changes on * native side. */ private static final Uri[] sUri = { ContactsContract.RawContacts.CONTENT_URI, ContactsContract.Data.CONTENT_URI }; /** * Holds mapping from a NAB type (MIME) to a VCard Key */ private static final HashMap<String, Integer> sFromNabContentTypeToKeyMap; /** * Holds mapping from a VCard Key to a NAB type (MIME) */ private static final SparseArray<String> sFromKeyToNabContentTypeArray; static { sFromNabContentTypeToKeyMap = new HashMap<String, Integer>(9, 1); sFromNabContentTypeToKeyMap.put(StructuredName.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NAME); sFromNabContentTypeToKeyMap.put(Nickname.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NICKNAME); sFromNabContentTypeToKeyMap.put(Phone.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_PHONE); sFromNabContentTypeToKeyMap.put(Email.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_EMAIL); sFromNabContentTypeToKeyMap.put(StructuredPostal.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ADDRESS); sFromNabContentTypeToKeyMap .put(Organization.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_ORG); sFromNabContentTypeToKeyMap.put(Website.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_URL); sFromNabContentTypeToKeyMap.put(Note.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_NOTE); sFromNabContentTypeToKeyMap.put(Event.CONTENT_ITEM_TYPE, ContactChange.KEY_VCARD_DATE); // sFromNabContentTypeToKeyMap.put( // Photo.CONTENT_ITEM_TYPE, ContactChange.KEY_PHOTO); sFromKeyToNabContentTypeArray = new SparseArray<String>(10); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NAME, StructuredName.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NICKNAME, Nickname.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_PHONE, Phone.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_EMAIL, Email.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ADDRESS, StructuredPostal.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_ORG, Organization.CONTENT_ITEM_TYPE); // Special case: VCARD_TITLE maps to the same NAB type as sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_TITLE, Organization.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray .append(ContactChange.KEY_VCARD_URL, Website.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_NOTE, Note.CONTENT_ITEM_TYPE); sFromKeyToNabContentTypeArray.append(ContactChange.KEY_VCARD_DATE, Event.CONTENT_ITEM_TYPE); // sFromKeyToNabContentTypeArray.append( // ContactChange.KEY_PHOTO, Photo.CONTENT_ITEM_TYPE); } /** * The observer registered by the upper layer. */ private ContactsObserver mAbstractedObserver; /** * Content values used for writing to NAB. */ private final ContentValues mValues = new ContentValues(); /** * The content observers that listens for native contacts changes. */ private final ContentObserver[] mContentObservers = new ContentObserver[sUri.length]; /** * Array of row ID in the groups table to the "My Contacts" System Group. * The reason for this being an array is because there may be multiple * "My Contacts" groups (Platform Bug!?). */ private long[] mMyContactsGroupRowIds = null; /** * Arguably another example where Organization and Title force us into extra * effort. We use this value to pass the correct detail ID when an 'add * detail' is done for one the two although the other is already present. * Make sure to reset this value for every UpdateContact operation */ private long mExistingOrganizationId = ContactChange.INVALID_ID; /** * Flag to check if we have already read a Birthday detail */ private boolean mHaveReadBirthday = false; /** * Yield value for our ContentProviderOperations. */ private boolean mYield = true; /** * Batch used for Contact Writing operations. */ private BatchOperation mBatch = new BatchOperation(); /** * Inner class for applying batches. TODO: Move to own class if batches * become supported in other areas */ private class BatchOperation { // List for storing the batch mOperations ArrayList<ContentProviderOperation> mOperations; /** * Default constructor */ public BatchOperation() { mOperations = new ArrayList<ContentProviderOperation>(); } /** * Current size of the batch * * @return Size of the batch */ public int size() { return mOperations.size(); } /** * Adds a new operation to the batch * * @param cpo The */ public void add(ContentProviderOperation cpo) { mOperations.add(cpo); } /** * Clears all operations in the batch Effectively resets the batch. */ public void clear() { mOperations.clear(); } public ContentProviderResult[] execute() { ContentProviderResult[] resultArray = null; if (mOperations.size() > 0) { // Apply the mOperations to the content provider try { resultArray = mCr.applyBatch(ContactsContract.AUTHORITY, mOperations); } catch (final OperationApplicationException e1) { LogUtils.logE("storing contact data failed", e1); } catch (final RemoteException e2) { LogUtils.logE("storing contact data failed", e2); } mOperations.clear(); } return resultArray; } } /** * Convenience interface to map the generic DATA column names to the People * profile detail column names. */ private interface PeopleProfileColumns { /** * 360 People profile MIME Type */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/com.vodafone360.people.profile"; /** * 360 People Contact's profile ID (Corresponds to Contact's Internal * Contact ID) */ public static final String DATA_PID = Data.DATA1; /** * 360 People Contact profile Summary */ public static final String DATA_SUMMARY = Data.DATA2; /** * 360 People Contact profile detail */ public static final String DATA_DETAIL = Data.DATA3; } /** * This class holds a native content observer that will be notified in case * of changes on the registered URI. */ private class NativeContentObserver extends ContentObserver { public NativeContentObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { LogUtils.logI("NativeContactsApi2.NativeContentObserver.onChange(" + selfChange + ")"); mAbstractedObserver.onChange(); } } /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { LogUtils.logI("NativeContactsApi2.registerObserver()"); if (mAbstractedObserver != null) { throw new RuntimeException( "Only one observer at a time supported... Please unregister first."); } mAbstractedObserver = observer; final ContentResolver cr = mContext.getContentResolver(); for (int i = 0; i < mContentObservers.length; i++) { mContentObservers[i] = new NativeContentObserver(); cr.registerContentObserver(sUri[i], true, mContentObservers[i]); } } /** * @see NativeContactsApi#unregisterObserver(ContactsObserver) */ @Override public void unregisterObserver() { LogUtils.logI("NativeContactsApi2.unregisterObserver()"); if (mCr != null) { mAbstractedObserver = null; for (int i = 0; i < mContentObservers.length; i++) { if (mContentObservers[i] != null) { mCr.unregisterContentObserver(mContentObservers[i]); mContentObservers[i] = null; } } } } /** * @see NativeContactsApi#initialize() */ @Override protected void initialize() { // perform here any one time initialization PHONE_ACCOUNT = getVendorSpecificAccount(); } /** * @see NativeContactsApi#getAccounts() */ @Override public Account[] getAccounts() { AccountManager accountManager = AccountManager.get(mContext); final android.accounts.Account[] accounts2xApi = accountManager.getAccounts(); Account[] accounts = null; if (accounts2xApi.length > 0) { accounts = new Account[accounts2xApi.length]; for (int i = 0; i < accounts2xApi.length; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } } return accounts; } /** * Reads vendor specific accounts from settings and through accountmanager. * Some phones with custom ui like sense have additional account that we * have to take care of. This method tryes to read them * * @return Account object if vendor specific account is found, null * otherwise */ public Account getVendorSpecificAccount() { // first read the settings String[] PROJECTION = { Settings.ACCOUNT_NAME, Settings.ACCOUNT_TYPE, Settings.UNGROUPED_VISIBLE }; // Get a cursor with all people Cursor cursor = mCr.query(Settings.CONTENT_URI, PROJECTION, null, null, null); // Got no cursor? Return with null! if (null == cursor) { return null; } try { String[] values = new String[cursor.getCount()]; for (int i = 0; i < values.length; i++) { cursor.moveToNext(); if (isVendorSpecificAccount(cursor.getString(1))) { return new Account(cursor.getString(0), cursor.getString(1)); } } } catch (Exception exc) { return null; } CursorUtils.closeCursor(cursor); // nothing found in the settings? try accountmanager Account[] accounts = getAccounts(); if (accounts == null) { return null; } for (Account account : accounts) { if (isVendorSpecificAccount(account.getType())) { return account; } } return null; } /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override public Account[] getAccountsByType(int type) { switch (type) { // people and google type lead to the same block the difference is // then handled inside in two if statements. // Otherwise we would have a lot of redundant code, case PEOPLE_ACCOUNT_TYPE: case GOOGLE_ACCOUNT_TYPE: { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts2xApi = null; // For people account set the people account type string... if (PEOPLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); } // .. and for google the same only with google string. if (GOOGLE_ACCOUNT_TYPE == type) { accounts2xApi = accountMan.getAccountsByType(GOOGLE_ACCOUNT_TYPE_STRING); } final int numAccounts = accounts2xApi.length; if (numAccounts > 0) { Account[] accounts = new Account[numAccounts]; for (int i = 0; i < numAccounts; i++) { accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } return accounts; + }else{ + return null; } } case PHONE_ACCOUNT_TYPE: { + if (PHONE_ACCOUNT==null){ + return null; + } return new Account[] { PHONE_ACCOUNT }; } default: return null; } } /** * @see NativeContactsApi#addPeopleAccount(String) */ @Override public boolean addPeopleAccount(String username) { boolean isAdded = false; try { android.accounts.Account account = new android.accounts.Account(username, PEOPLE_ACCOUNT_TYPE_STRING); AccountManager accountMan = AccountManager.get(mContext); isAdded = accountMan.addAccountExplicitly(account, null, null); if (isAdded) { if (VersionUtils.isHtcSenseDevice(mContext)) { createSettingsEntryForAccount(username); } // TODO: RE-ENABLE SYNC VIA SYSTEM ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0); // ContentResolver.setSyncAutomatically(account, // ContactsContract.AUTHORITY, true); } } catch (Exception ex) { LogUtils.logE("People Account creation failed because of exception:\n", ex); } if (isAdded) { // Updating MyContacts Group IDs here for now because it needs to be // done one time just before first time sync. // In the future, this code may change if we modify // the way we retrieve contact IDs. fetchMyContactsGroupRowIds(); } return isAdded; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); return accounts != null && accounts.length > 0; } /** * @see NativeContactsApi#removePeopleAccount() */ @Override public void removePeopleAccount() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan .getAccountsByType(PEOPLE_ACCOUNT_TYPE_STRING); if (accounts != null && accounts.length > 0) { accountMan.removeAccount(accounts[0], null, null); } } /** * @see NativeContactsApi#getContactIds(Account) */ @Override public long[] getContactIds(Account account) { // Need to construct a where clause if (account != null) { final StringBuffer clauseBuffer = new StringBuffer(); clauseBuffer.append(RawContacts.ACCOUNT_NAME); clauseBuffer.append("=\""); clauseBuffer.append(account.getName()); clauseBuffer.append("\" AND "); clauseBuffer.append(RawContacts.ACCOUNT_TYPE); clauseBuffer.append("=\""); clauseBuffer.append(account.getType()); clauseBuffer.append('\"'); return getContactIds(clauseBuffer.toString()); } else { return getContactIds(NULL_ACCOUNT_WHERE_CLAUSE); } } /** * @see NativeContactsApi#getContact(long) */ @Override public ContactChange[] getContact(long nabContactId) { // Reset the boolean flags mHaveReadOrganization = false; mHaveReadBirthday = false; final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, nabContactId); final Uri dataUri = Uri.withAppendedPath(rawContactUri, RawContacts.Data.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(dataUri, null, null, null, null); try { if (cursor != null && cursor.getCount() > 0) { final List<ContactChange> ccList = new ArrayList<ContactChange>(); while (cursor.moveToNext()) { readDetail(cursor, ccList, nabContactId); } return ccList.toArray(new ContactChange[ccList.size()]); } } finally { CursorUtils.closeCursor(cursor); } return null; } /** * @see NativeContactsApi#addContact(Account, ContactChange[]) */ @Override public ContactChange[] addContact(Account account, ContactChange[] ccList) { // Make sure to reset all the member variables we need mYield = true; mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mValues.clear(); mBatch.clear(); mValues.put(RawContacts.ACCOUNT_TYPE, account.getType()); mValues.put(RawContacts.ACCOUNT_NAME, account.getName()); ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI)).withYieldAllowed(mYield) .withValues(mValues); mBatch.add(builder.build()); final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; if (cc != null) { final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } putDetail(cc); addValuesToBatch(ContactChange.INVALID_ID); } } // Special case for the organization/title if it was flagged in the // putDetail call putOrganization(ccList); addValuesToBatch(ContactChange.INVALID_ID); // Add 360 profile detail addProfileAction(ccList[0].getInternalContactId()); // Execute the batch and Generate ID changes from it return executeNewContactBatch(ccList); } /** * @see NativeContactsApi#updateContact(ContactChange[]) */ @Override public ContactChange[] updateContact(ContactChange[] ccList) { if (ccList == null || ccList.length == 0) { LogUtils.logW("NativeContactsApi2.updateContact() nothing to update - empty ccList!"); return null; } // Make sure to reset all the member variables we need mYield = true; mBatch.clear(); mValues.clear(); mMarkedOrganizationIndex = mMarkedTitleIndex = -1; mExistingOrganizationId = ContactChange.INVALID_ID; final long nabContactId = ccList[0].getNabContactId(); if (nabContactId == ContactChange.INVALID_ID) { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update request because of invalid NAB Contact ID. Internal Contact ID is " + ccList[0].getInternalContactId()); return null; } final int ccListSize = ccList.length; for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; final int key = cc.getKey(); if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; } if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } switch (cc.getType()) { case ContactChange.TYPE_ADD_DETAIL: putDetail(cc); addValuesToBatch(nabContactId); // not a new contact break; case ContactChange.TYPE_UPDATE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { putDetail(cc); addUpdateValuesToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring update to detail for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; case ContactChange.TYPE_DELETE_DETAIL: if (cc.getNabDetailId() != ContactChange.INVALID_ID) { addDeleteDetailToBatch(cc.getNabDetailId()); } else { LogUtils .logW("NativeContactsApi2.updateContact() Ignoring detail deletion for " + cc.getKeyToString() + " because of invalid NAB Detail ID. Internal Contact is " + cc.getInternalContactId() + ", Internal Detail Id is " + cc.getInternalDetailId()); } break; default: break; } } updateOrganization(ccList, nabContactId); // Execute the batch and Generate ID changes from it return executeUpdateContactBatch(ccList); } /** * @see NativeContactsApi#removeContact(long) */ @Override public void removeContact(long nabContactId) { mCr.delete(addCallerIsSyncAdapterParameter(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId)), null, null); } /** * @see NativeContactsApi#isKeySupported(int) */ @Override public boolean isKeySupported(int key) { // Only supported if in the SparseArray return sFromKeyToNabContentTypeArray.indexOfKey(key) >= 0; } /** * Inner (private) method for getting contact ids. Allows a cleaner * separation the public API method. * * @param selection The where clause for the operation * @return An array containing the Contact IDs that have been found */ private long[] getContactIds(final String selection) { // Store ids in a temporary array because of possible null values long[] tempIds = null; int idCount = 0; final Cursor cursor = mCr.query(RawContacts.CONTENT_URI, CONTACTID_PROJECTION, selection, null, null); if (cursor == null) { return null; } try { final int cursorCount = cursor.getCount(); if (cursorCount > 0) { tempIds = new long[cursorCount]; while (cursor.moveToNext()) { final long id = cursor.getLong(CONTACTID_PROJECTION_RAW_ID); final String accountType = cursor.getString(CONTACTID_PROJECTION_ACCOUNT_TYPE); // TODO: Remove hardcoding (if statement) if (TextUtils.isEmpty(accountType) || accountType.equals(NativeContactsApi.PEOPLE_ACCOUNT_TYPE_STRING) || isVendorSpecificAccount(accountType) || isContactInMyContactsGroup(id)) { tempIds[idCount] = id; idCount++; } } } } finally { CursorUtils.closeCursor(cursor); } if (idCount > 0) { // Here we copy the array to strip any eventual nulls at the end of // the tempIds array final long[] ids = new long[idCount]; System.arraycopy(tempIds, 0, ids, 0, idCount); return ids; } return null; } /** * Fetches the IDs corresponding to the "My Contacts" System Group The * reason why we return an array is because there may be multiple * "My Contacts" groups. * * @return Array containing all IDs of the "My Contacts" group or null if * none exist */ private void fetchMyContactsGroupRowIds() { final Cursor cursor = mCr.query(Groups.CONTENT_URI, GROUPID_PROJECTION, MY_CONTACTS_GROUP_WHERE_CLAUSE, null, null); if (cursor == null) { return; } try { final int count = cursor.getCount(); if (count > 0) { mMyContactsGroupRowIds = new long[count]; for (int i = 0; i < count; i++) { cursor.moveToNext(); mMyContactsGroupRowIds[i] = cursor.getLong(0); } } } finally { CursorUtils.closeCursor(cursor); } } /** * Checks if a Contact is in the "My Contacts" System Group * * @param nabContactId ID of the Contact to check * @return true if the Contact is in the Group, false if not */ private boolean isContactInMyContactsGroup(long nabContactId) { boolean belongs = false; if (mMyContactsGroupRowIds != null) { final Uri dataUri = Uri.withAppendedPath(ContentUris.withAppendedId( RawContacts.CONTENT_URI, nabContactId), RawContacts.Data.CONTENT_DIRECTORY); // build query containing row ID values final StringBuilder sb = new StringBuilder(); sb.append(MY_CONTACTS_MULTI_GROUP_MEMBERSHIP); final int rowIdCount = mMyContactsGroupRowIds.length; for (int i = 0; i < rowIdCount; i++) { sb.append(mMyContactsGroupRowIds[i]); if (i < rowIdCount - 1) { sb.append(','); } } sb.append(')'); final Cursor cursor = mCr.query(dataUri, null, sb.toString(), null, null); try { belongs = cursor != null && cursor.getCount() > 0; } finally { CursorUtils.closeCursor(cursor); } } return belongs; } /** * Reads a Contact Detail from a Cursor into the supplied Contact Change * List. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to read Detail into * @param nabContactId NAB ID of the Contact */ private void readDetail(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String mimetype = CursorUtils.getString(cursor, Data.MIMETYPE); final Integer key = sFromNabContentTypeToKeyMap.get(mimetype); if (key != null) { switch (key.intValue()) { case ContactChange.KEY_VCARD_NAME: readName(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_NICKNAME: readNickname(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_PHONE: readPhone(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_EMAIL: readEmail(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ADDRESS: readAddress(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_ORG: // Only one Organization can be read (CAB limitation!) if (!mHaveReadOrganization) { readOrganization(cursor, ccList, nabContactId); } break; case ContactChange.KEY_VCARD_URL: readWebsite(cursor, ccList, nabContactId); break; case ContactChange.KEY_VCARD_DATE: if (!mHaveReadBirthday) { readBirthday(cursor, ccList, nabContactId); } break; default: // The default case is also a valid key final String value = CursorUtils.getString(cursor, Data.DATA1); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Data._ID); final ContactChange cc = new ContactChange(key, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } break; } } } /** * Reads an name detail as a {@link ContactChange} from the provided cursor. * For this type of detail we need to use a VCARD (semicolon separated) * value. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readName(Cursor cursor, List<ContactChange> ccList, long nabContactId) { // Using display name only to check if there is a valid name to read final String displayName = CursorUtils.getString(cursor, StructuredName.DISPLAY_NAME); if (!TextUtils.isEmpty(displayName)) { final long nabDetailId = CursorUtils.getLong(cursor, StructuredName._ID); // VCard Helper data type (CAB) final Name name = new Name(); // NAB: Given name -> CAB: First name name.firstname = CursorUtils.getString(cursor, StructuredName.GIVEN_NAME); // NAB: Family name -> CAB: Surname name.surname = CursorUtils.getString(cursor, StructuredName.FAMILY_NAME); // NAB: Prefix -> CAB: Title name.title = CursorUtils.getString(cursor, StructuredName.PREFIX); // NAB: Middle name -> CAB: Middle name name.midname = CursorUtils.getString(cursor, StructuredName.MIDDLE_NAME); // NAB: Suffix -> CAB: Suffixes name.suffixes = CursorUtils.getString(cursor, StructuredName.SUFFIX); // NOTE: Ignoring Phonetics (DATA7, DATA8 and DATA9)! // TODO: Need to get middle name and concatenate into value final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NAME, VCardHelper .makeName(name), ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an nickname detail as a {@link ContactChange} from the provided * cursor. * * @param cursor Cursor to read from * @param ccList List of Contact Changes to add read detail data * @param nabContactId ID of the NAB Contact */ private void readNickname(Cursor cursor, List<ContactChange> ccList, long nabContactId) { final String value = CursorUtils.getString(cursor, Nickname.NAME); if (!TextUtils.isEmpty(value)) { final long nabDetailId = CursorUtils.getLong(cursor, Nickname._ID); /* * TODO: Decide what to do with nickname: Can only have one in VF360 * but NAB Allows more than one! */ final ContactChange cc = new ContactChange(ContactChange.KEY_VCARD_NICKNAME, value, ContactChange.FLAG_NONE); cc.setNabContactId(nabContactId); cc.setNabDetailId(nabDetailId); ccList.add(cc); } } /** * Reads an phone detail as a {@link ContactChange} from the provided * cursor. * diff --git a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java index 3ba9bb4..95af541 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java @@ -1,849 +1,849 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.contactsync; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import android.text.TextUtils; import com.vodafone360.people.datatypes.VCardHelper; import com.vodafone360.people.engine.contactsync.NativeContactsApi.Account; import com.vodafone360.people.utils.DynamicArrayLong; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; /** * The NativeImporter class is responsible for importing contacts from the * native address book to the people database. To do so, it compares the native * address book and the people database to find new changes and update the * people database accordingly. Usage: - instantiate the class - call the tick() * method until isDone() returns true - current progress can be obtained via * getPosition() / getCount() - check the getResult() to get a status (OK, * KO...) */ public class NativeImporter { /** * The undefined result when the NativeImporter has not been run yet. * * @see #getResult() */ public final static int RESULT_UNDEFINED = -1; /** * The ok result when the NativeImporter has finished successfully. * * @see #getResult() */ public final static int RESULT_OK = 0; /** * The undefined result when the NativeImporter has not been run yet. * * @see #getResult() */ public final static int RESULT_ERROR = 1; /** * Number of contacts to be processed "per tick". * * @see #tick() */ private final static int MAX_CONTACTS_OPERATION_COUNT = 2; /** * Handler to the People Contacts API. */ private PeopleContactsApi mPeopleContactsApi; /** * Handler to the Native Contacts API. */ private NativeContactsApi mNativeContactsApi; /** * Internal state representing the task to perform: gets the list of native * contacts ids and people contacts ids. */ private final static int STATE_GET_IDS_LISTS = 0; /** * Internal state representing the task to perform: iterates through the * list of ids to find differences (i.e. added contact, modified contact, * deleted contact). */ private final static int STATE_ITERATE_THROUGH_IDS = 1; /** * Internal state representing the task to perform: process the list of * deleted contacts (i.e. delete the contacts from the people database). * TODO: remove this state */ private final static int STATE_PROCESS_DELETED = 2; /** * Internal state representing the task to perform: final state, nothing * else to perform. */ private final static int STATE_DONE = 3; /** * The current state. */ private int mState = STATE_GET_IDS_LISTS; /** * The list of native ids from the native side. */ private long[] mNativeContactsIds; /** * The list of native ids from the people side. */ private long[] mPeopleNativeContactsIds; /** * The total count of ids to process (native database + people database). */ private int mTotalIds = 0; /** * The current count of processed ids. */ private int mProcessedIds = 0; /** * The index of the current native id. * * @see #mNativeContactsIds */ private int mCurrentNativeId = 0; /** * The index in the current people id. * * @see #mPeopleNativeContactsIds */ private int mCurrentPeopleId = 0; /** * The index of the current deleted people id. * * @see #mDeletedIds */ private int mCurrentDeletedId = 0; /** * Array to store the people ids of contacts to delete. */ private DynamicArrayLong mDeletedIds = new DynamicArrayLong(10); /** * The result status. */ private int mResult = RESULT_UNDEFINED; /** * Instance of a ContactChange comparator. */ private NCCComparator mNCCC = new NCCComparator(); /** * The array of accounts from where to import the native contacts. Note: if * null, will import from the platform default account. */ private Account[] mAccounts = null; /** * Boolean that tracks if the first time Import for 2.X is ongoing. */ private boolean mIsFirstImportOn2X = false; /** * Constructor. * * @param pca handler to the People contacts Api * @param nca handler to the Native contacts Api * @param firstTimeImport true if we import from native for the first time, * false if not */ public NativeImporter(PeopleContactsApi pca, NativeContactsApi nca, boolean firstTimeImport) { mPeopleContactsApi = pca; mNativeContactsApi = nca; initAccounts(firstTimeImport); } /** * Sets the accounts used to import the native contacs. */ private void initAccounts(boolean firstTimeImport) { /** * In case of Android 2.X, the accounts used are different depending if * it's first time sync or not. On Android 1.X, we can just ignore the * accounts logic as not supported by the platform. At first time sync, * we need to import the native contacts from all the Google accounts. * These native contacts are then stored in the 360 People account and * native changes will be only detected from the 360 People account. */ if (VersionUtils.is2XPlatform()) { // account to import from: 360 account if created, all the google // accounts otherwise if (firstTimeImport) { ArrayList<Account> accountList = new ArrayList<Account>(); - Account googleAccounts[]=mNativeContactsApi.getAccountsByType(NativeContactsApi.GOOGLE_ACCOUNT_TYPE); - if (googleAccounts!=null && googleAccounts.length>0){ - for (Account account : mNativeContactsApi - .getAccountsByType(NativeContactsApi.GOOGLE_ACCOUNT_TYPE)) { + Account googleAccounts[] = mNativeContactsApi.getAccountsByType(NativeContactsApi.GOOGLE_ACCOUNT_TYPE); + if (googleAccounts!=null ){ + for (Account account : googleAccounts) { accountList.add(account); } } - Account phoneAccounts[]=mNativeContactsApi.getAccountsByType(NativeContactsApi.PHONE_ACCOUNT_TYPE); - if (phoneAccounts!=null && phoneAccounts.length>0){ + + Account phoneAccounts[] = mNativeContactsApi.getAccountsByType(NativeContactsApi.PHONE_ACCOUNT_TYPE); + if (phoneAccounts!=null){ for (Account account : phoneAccounts) { accountList.add(account); } } mAccounts = accountList.toArray(new Account[0]); } else { mAccounts = mNativeContactsApi .getAccountsByType(NativeContactsApi.PEOPLE_ACCOUNT_TYPE); } if (firstTimeImport) mIsFirstImportOn2X = true; } } /** * Sets the internal state to DONE with the provided result status. * * @param result the result status to set */ private void complete(int result) { mState = STATE_DONE; mResult = result; } /** * Tick method to call each time there is time for processing the native * contacts import. Note: the method will block for some time to process a * certain amount of contact then will return. It will have to be called * until it returns true meaning that the import is over. * * @return true when the import task is finished, false if not */ public boolean tick() { switch (mState) { case STATE_GET_IDS_LISTS: getIdsLists(); break; case STATE_ITERATE_THROUGH_IDS: iterateThroughNativeIds(); break; case STATE_PROCESS_DELETED: processDeleted(); break; } return isDone(); } /** * Returns the import state. * * @return true if the import is finished, false if not */ public boolean isDone() { return mState == STATE_DONE; } /** * Gets the import result. * * @see #RESULT_OK * @see #RESULT_ERROR * @see #RESULT_UNDEFINED * @return the import result */ public int getResult() { return mResult; } /** * Gets the current position in the list of ids. This can be used to track * the current progress. * * @see #getCount() * @return the last processed id position in the list of ids */ public int getPosition() { return mProcessedIds; } /** * Gets the total number of ids to process. * * @return the number of ids to process */ public int getCount() { return mTotalIds; } /** * Gets the list of native and people contacts ids. */ private void getIdsLists() { LogUtils.logD("NativeImporter.getIdsLists()"); // Get the list of native ids for the contacts - if (mAccounts == null) { + if (mAccounts == null || 0 == mAccounts.length) { // default account LogUtils.logD("NativeImporter.getIdsLists() - using default account"); mNativeContactsIds = mNativeContactsApi.getContactIds(null); } else if (mAccounts.length == 1) { // one account LogUtils.logD("NativeImporter.getIdsLists() - one account found: " + mAccounts[0]); mNativeContactsIds = mNativeContactsApi.getContactIds(mAccounts[0]); } else { // we need to merge the ids from different accounts and sort them final DynamicArrayLong allIds = new DynamicArrayLong(); LogUtils.logD("NativeImporter.getIdsLists() - more than one account found."); for (int i = 0; i < mAccounts.length; i++) { LogUtils.logD("NativeImporter.getIdsLists() - account=" + mAccounts[i]); final long[] ids = mNativeContactsApi.getContactIds(mAccounts[i]); if (ids != null) { allIds.add(ids); } } mNativeContactsIds = allIds.toArray(); // sort the ids // TODO: as the arrays to merge are sorted, consider merging while // keeping the sorting // which is faster than sorting them afterwards if (mNativeContactsIds != null) { Arrays.sort(mNativeContactsIds); } } // check if we have some work to do if (mNativeContactsIds == null) { complete(RESULT_OK); return; } // Get a list of native ids for the contacts we have in the People // database mPeopleNativeContactsIds = mPeopleContactsApi.getNativeContactsIds(); mTotalIds = mNativeContactsIds.length; if (mPeopleNativeContactsIds != null) { mTotalIds += mPeopleNativeContactsIds.length; } mState = STATE_ITERATE_THROUGH_IDS; } /** * Iterates through the list of native and People ids to detect changes. */ private void iterateThroughNativeIds() { LogUtils.logD("NativeImporter.iterateThroughNativeIds()"); final int limit = Math.min(mNativeContactsIds.length, mCurrentNativeId + MAX_CONTACTS_OPERATION_COUNT); // TODO: remove the deleted state / queuing to deleted ids array and // loop with while (mProcessedIds < limit) while (mCurrentNativeId < limit) { if (mPeopleNativeContactsIds == null) { // no native contacts on people side, just add it LogUtils.logD("NativeImporter.iterateThroughNativeIds(): found a new contact"); addNewContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; } else { // both ids lists are ordered by ascending ids so // every people ids that are before the current native ids // are simply deleted contacts while ((mCurrentPeopleId < mPeopleNativeContactsIds.length) && (mPeopleNativeContactsIds[mCurrentPeopleId] < mNativeContactsIds[mCurrentNativeId])) { LogUtils .logD("NativeImporter.iterateThroughNativeIds(): found a contact to delete"); mDeletedIds.add(mPeopleNativeContactsIds[mCurrentPeopleId++]); } if (mCurrentPeopleId == mPeopleNativeContactsIds.length || mPeopleNativeContactsIds[mCurrentPeopleId] > mNativeContactsIds[mCurrentNativeId]) { // has to be a new contact LogUtils.logD("NativeImporter.iterateThroughNativeIds(): found a new contact"); addNewContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; } else { // has to be an existing contact or one that will be deleted LogUtils .logD("NativeImporter.iterateThroughNativeIds(): check existing contact"); checkExistingContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; mCurrentPeopleId++; } } mCurrentNativeId++; } // check if we are done with ids list from native if (mCurrentNativeId == mNativeContactsIds.length) { // we've gone through the native list, any remaining ids from the // people list are deleted ones if (mPeopleNativeContactsIds != null) { while (mCurrentPeopleId < mPeopleNativeContactsIds.length) { LogUtils .logD("NativeImporter.iterateThroughNativeIds(): found a contact to delete"); mDeletedIds.add(mPeopleNativeContactsIds[mCurrentPeopleId++]); } } if (mDeletedIds.size() != 0) { // Some deleted contacts to handle mState = STATE_PROCESS_DELETED; } else { // Nothing else to do complete(RESULT_OK); } } } /** * Deletes the contacts that were added the deleted array. */ private void processDeleted() { LogUtils.logD("NativeImporter.processDeleted()"); final int limit = Math.min(mDeletedIds.size(), mCurrentDeletedId + MAX_CONTACTS_OPERATION_COUNT); while (mCurrentDeletedId < limit) { // we now delete the contacts on people client side // on the 2.X platform, the contact deletion has to be synced back // to native once completed because the // contact is still there on native, just marked as deleted and // waiting for its explicit removal mPeopleContactsApi.deleteNativeContact(mDeletedIds.get(mCurrentDeletedId++), VersionUtils.is2XPlatform()); mProcessedIds++; } if (mCurrentDeletedId == mDeletedIds.size()) { complete(RESULT_OK); } } /** * Adds a new contact to the people database. */ private void addNewContact(long nativeId) { // get the contact data final ContactChange[] contactChanges = mNativeContactsApi.getContact(nativeId); if (contactChanges != null) { if (mIsFirstImportOn2X) { // Override the nativeContactId with an invalid id if we are on // 2.X // and we are doing a first time import because the native id // does not correspond // to the id from the 360 People account where we will export. removeNativeIds(contactChanges); } else { // Force a nativeDetailId to details that have none so that the // comparison // later can be made (see computeDelta method). forceNabDetailId(contactChanges); } // add the contact to the People database if (!mPeopleContactsApi.addNativeContact(contactChanges)) { // TODO: Handle the error case !!! Well how should we handle it: // fail for all remaining contacts or skip the failing contact? LogUtils .logE("NativeImporter.addNewContact() - failed to import native contact id=" + nativeId); } } } /** * Check changes between an existing contact on both native and people * database. * * @param nativeId the native id of the contact to check */ private void checkExistingContact(long nativeId) { // get the native version of that contact final ContactChange[] nativeContact = mNativeContactsApi.getContact(nativeId); // get the people version of that contact final ContactChange[] peopleContact = mPeopleContactsApi.getContact((int)nativeId); if (peopleContact == null) { // we shouldn't be in that situation but nothing to do about it // this means that there were some changes in the meantime between // getting the ids list and now return; } else if (nativeContact == null) { LogUtils .logD("NativeImporter.checkExistingContact(): found a contact marked as deleted"); // this is a 2.X specific case meaning that the contact is marked as // deleted on native side // and waiting for the "syncAdapter" to perform a real delete mDeletedIds.add(nativeId); } else { // general case, find the delta final ContactChange[] delta = computeDelta(peopleContact, nativeContact); if (delta != null) { // update CAB with delta changes mPeopleContactsApi.updateNativeContact(delta); } } } /** * Native ContactChange Comparator class. This class compares ContactChange * and tells which one is greater depending on the key and then the native * detail id. */ private static class NCCComparator implements Comparator<ContactChange> { @Override public int compare(ContactChange change1, ContactChange change2) { // an integer < 0 if object1 is less than object2, 0 if they are // equal, and > 0 if object1 is greater than object2. final int key1 = change1.getKey(); final int key2 = change2.getKey(); if (key1 < key2) { return -1; } else if (key1 > key2) { return 1; } else { // the keys are identical, check the native ids final long id1 = change1.getNabDetailId(); final long id2 = change2.getNabDetailId(); if (id1 < id2) { return -1; } else if (key1 > key2) { return 1; } else { return 0; } } } } /** * Sorts the provided array of ContactChange by key and native id. Note: the * method will rearrange the provided array. * * @param changes the ContactChange array to sort */ private void sortContactChanges(ContactChange[] changes) { if ((changes != null) && (changes.length > 1)) { Arrays.sort(changes, mNCCC); } } /** * Computes the difference between the provided arrays of ContactChange. The * delta are the changes to apply to the master ContactChange array to make * it similar to the new changes ContactChange array. (i.e. delete details, * add details or modify details) NOTE: to help the GC, some provided * ContactChange may be modified and returned by the method instead of * creating new ones. * * @param masterChanges the master array of ContactChange (i.e. the original * one) * @param newChanges the new ContactChange array (i.e. contains the new * version of a contact) * @return null if there are no changes or the contact is being deleted, an * array for ContactChange to apply to the master contact if * differences where found */ private ContactChange[] computeDelta(ContactChange[] masterChanges, ContactChange[] newChanges) { LogUtils.logD("NativeImporter.computeDelta()"); // set the native contact id to details that don't have a native detail // id for the comparison as // this is also done on people database side forceNabDetailId(newChanges); // sort the changes by key then native detail id sortContactChanges(masterChanges); sortContactChanges(newChanges); // if the master contact is being deleted, ignore new changes if ((masterChanges[0].getType() & ContactChange.TYPE_DELETE_CONTACT) == ContactChange.TYPE_DELETE_CONTACT) { return null; } // details comparison, skip deleted master details final ContactChange[] deltaChanges = new ContactChange[masterChanges.length + newChanges.length]; int deltaIndex = 0; int masterIndex = 0; int newIndex = 0; while (newIndex < newChanges.length) { while ((masterIndex < masterChanges.length) && (mNCCC.compare(masterChanges[masterIndex], newChanges[newIndex]) < 0)) { final ContactChange masterChange = masterChanges[masterIndex]; if ((masterChange.getType() & ContactChange.TYPE_DELETE_DETAIL) != ContactChange.TYPE_DELETE_DETAIL && (masterChange.getNabDetailId() != ContactChange.INVALID_ID) && (isContactChangeKeySupported(masterChange))) { // this detail does not exist anymore, is not being deleted // and was synced to native // check if it can be deleted (or has to be updated) setDetailForDeleteOrUpdate(masterChanges, masterIndex); deltaChanges[deltaIndex++] = masterChanges[masterIndex]; } masterIndex++; } if ((masterIndex < masterChanges.length) && (mNCCC.compare(newChanges[newIndex], masterChanges[masterIndex]) == 0)) { // similar key and id, check for differences at value level and // flags final ContactChange masterDetail = masterChanges[masterIndex]; final ContactChange newDetail = newChanges[newIndex]; boolean different = false; if (masterDetail.getFlags() != newDetail.getFlags()) { different = true; } if (!areContactChangeValuesEqualsPlusFix(masterChanges, masterIndex, newChanges, newIndex)) { different = true; } if (different) { // found a detail to update LogUtils.logD("NativeImporter.computeDelta() - found a detail to update"); newDetail.setType(ContactChange.TYPE_UPDATE_DETAIL); newDetail.setInternalContactId(masterDetail.getInternalContactId()); newDetail.setInternalDetailId(masterDetail.getInternalDetailId()); deltaChanges[deltaIndex++] = newDetail; } masterIndex++; } else { LogUtils.logD("NativeImporter.computeDelta() - found a detail to add"); // this is a new detail newChanges[newIndex].setType(ContactChange.TYPE_ADD_DETAIL); newChanges[newIndex].setInternalContactId(masterChanges[0].getInternalContactId()); deltaChanges[deltaIndex++] = newChanges[newIndex]; } newIndex++; } while (masterIndex < masterChanges.length) { final ContactChange masterChange = masterChanges[masterIndex]; if ((masterChange.getType() & ContactChange.TYPE_DELETE_DETAIL) != ContactChange.TYPE_DELETE_DETAIL && (masterChange.getNabDetailId() != ContactChange.INVALID_ID) && (isContactChangeKeySupported(masterChange))) { // this detail does not exist anymore, is not being deleted and // was synced to native // check if it can be deleted (or has to be updated) setDetailForDeleteOrUpdate(masterChanges, masterIndex); deltaChanges[deltaIndex++] = masterChanges[masterIndex]; } masterIndex++; } if (deltaIndex == 0) { // the contact has not changed return null; } else if (deltaChanges.length == deltaIndex) { // give the detail changes return deltaChanges; } else { // give the detail changes but need to trim final ContactChange[] trim = new ContactChange[deltaIndex]; System.arraycopy(deltaChanges, 0, trim, 0, deltaIndex); return trim; } } /** * Removes the native ids in case of a first time import on the Android 2.X * platform. * * @param contact the contact to clear from native ids */ private void removeNativeIds(ContactChange[] contact) { if (contact != null) { final int count = contact.length; for (int i = 0; i < count; i++) { final ContactChange change = contact[i]; change.setNabContactId(ContactChange.INVALID_ID); change.setNabDetailId(ContactChange.INVALID_ID); } } } /** * Forces a native detail id onto a detail that does not have one by setting * it to be the native contact id. * * @param contact the contact to fix */ private void forceNabDetailId(ContactChange[] contact) { if (contact != null && contact.length > 0) { final long nativeContactId = contact[0].getNabContactId(); final int count = contact.length; for (int i = 0; i < count; i++) { final ContactChange change = contact[i]; if (change.getNabDetailId() == ContactChange.INVALID_ID) { change.setNabDetailId(nativeContactId); } } } } /* * Below this point, all the defined methods where added to support the * specific case of KEY_VCARD_ORG on Android 1.X platform. KEY_VCARD_ORG is * defined as followed: "company;department1;department2;...;departmentX" It * is a special case because this VCard key on its own is not fully * supported on the Android 1.X platform: only "company" information is. */ /** * Tells whether or not a master change is equal to a new change and * performs some modifications on the provided new change in the specific * case of KEY_VCARD_ORG on Android 1.X. * * @param masterChanges the array of master changes * @param masterIndex the index of the change within the array of master * changes * @param newChanges the array of new changes * @param newIndex the index of the change within the array of new changes * @return true if the changes are equals, false otherwise */ private boolean areContactChangeValuesEqualsPlusFix(ContactChange[] masterChanges, int masterIndex, ContactChange[] newChanges, int newIndex) { final ContactChange masterChange = masterChanges[masterIndex]; final ContactChange newChange = newChanges[newIndex]; if (VersionUtils.is2XPlatform() || masterChange.getKey() != ContactChange.KEY_VCARD_ORG) { // general case return TextUtils.equals(masterChange.getValue(), newChange.getValue()); } else { // this is a special case of Android 1.X where we have to parse the // value // in case of Organization key final String peopleCompValue = VCardHelper.parseCompanyFromOrganization(masterChange .getValue()); final String nativeCompValue = VCardHelper.parseCompanyFromOrganization(newChange .getValue());
360/360-Engine-for-Android
bde25a8d09d991540e21a2803bc14f315f416229
Adding a lost commit.
diff --git a/src/com/vodafone360/people/engine/login/LoginEngine.java b/src/com/vodafone360/people/engine/login/LoginEngine.java index e538d4d..fa1b67f 100644 --- a/src/com/vodafone360/people/engine/login/LoginEngine.java +++ b/src/com/vodafone360/people/engine/login/LoginEngine.java @@ -20,1375 +20,1391 @@ * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.login; import java.util.ArrayList; import java.util.List; import org.bouncycastle.crypto.InvalidCipherTextException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.telephony.TelephonyManager; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.Intents; import com.vodafone360.people.Settings; import com.vodafone360.people.SettingsManager; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.StateTable; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.PublicKeyDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.datatypes.SimpleText; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.contactsync.NativeContactsApi; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.agent.NetworkAgent.AgentState; import com.vodafone360.people.service.io.ResponseQueue; import com.vodafone360.people.service.io.api.Auth; import com.vodafone360.people.service.receivers.SmsBroadcastReceiver; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.LoginPreferences; /** * Engine handling sign in to existing accounts and sign up to new accounts. */ public class LoginEngine extends BaseEngine { /** * List of states for LoginEngine. */ private enum State { NOT_INITIALISED, NOT_REGISTERED, LOGGED_ON, LOGGED_OFF, LOGGED_OFF_WAITING_FOR_RETRY, LOGGED_OFF_WAITING_FOR_NETWORK, LOGIN_FAILED, LOGIN_FAILED_WRONG_CREDENTIALS, SIGNING_UP, FETCHING_TERMS_OF_SERVICE, FETCHING_PRIVACY_STATEMENT, FETCHING_USERNAME_STATE, REQUESTING_ACTIVATION_CODE, CREATING_SESSION_MANUAL, ACTIVATING_ACCOUNT, CREATING_SESSION_AUTO, RETRIEVING_PUBLIC_KEY } /** * Text coming from the server contains these carriage return characters, * which need to be exchanged with space characters to improve layout. */ private static final char CARRIAGE_RETURN_CHARACTER = (char) 13; /** * Text coming from the server contains carriage return characters, which * need to be exchanged with these space characters to improve layout. */ private static final char SPACE_CHARACTER = (char) 32; /** * used for sending unsolicited ui events */ private final UiAgent mUiAgent = mEventCallback.getUiAgent(); /** * mutex for thread synchronization */ private final Object mMutex = new Object(); /** * To convert between seconds and milliseconds */ private static final int MS_IN_SECONDS = 1000; /** * Current state of the engine */ private State mState = State.NOT_INITIALISED; /** * Context used for listening to SMS events */ private Context mContext; /** * Database used for fetching/storing state information */ private DatabaseHelper mDb; /** * Subscriber ID fetched from SIM card */ private String mCurrentSubscriberId; /** * Android telephony manager used for fetching subscriber ID */ private TelephonyManager mTelephonyManager; /** * Contains the authenticated session information while the user is logged * in */ private static AuthSessionHolder sActivatedSession = null; /** * Contains user login details such as user name and password */ private final LoginDetails mLoginDetails = new LoginDetails(); /** * Contains a public key for encrypting login details to be sent to the * server */ private PublicKeyDetails mPublicKey = new PublicKeyDetails(); /** * Contains user registration details such as name, username, password, etc. */ private final RegistrationDetails mRegistrationDetails = new RegistrationDetails(); /** * Determines if current login information from database can be used to * establish a session. Set to false if login fails repeatedly. */ private boolean mAreLoginDetailsValid = true; /** * Timeout used when waiting for the server to sent an activation SMS. If * this time in milliseconds is exceeded, the login will fail with SMS not * received error. */ private static final long ACTIVATE_LOGIN_TIMEOUT = 72000; /** * Holds the activation code once an activation SMS has been received. */ private String mActivationCode = null; /** * Set to true when sign in or sign up has been completed by the user. When * this is false the landing page will be displayed when the application is * launched. */ private boolean mIsRegistrationComplete = false; /** * Contains a list of login engine observers which will be notified when the * login engine changes state. */ private final ArrayList<ILoginEventsListener> mEventsListener = new ArrayList<ILoginEventsListener>(); /** * Determines if the user is currently logged in with a valid session */ private boolean mCurrentLoginState = false; /** * Listener interface that can be used by clients to receive login state * events from the engine. */ public static interface ILoginEventsListener { void onLoginStateChanged(boolean loggedIn); } /** * Public constructor. * * @param context The service Context * @param eventCallback Provides access to useful engine manager * functionality * @param db The Now+ database used for fetching/storing login state * information */ public LoginEngine(Context context, IEngineEventCallback eventCallback, DatabaseHelper db) { super(eventCallback); LogUtils.logD("LoginEngine.LoginEngine()"); mContext = context; mTelephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); mDb = db; mEngineId = EngineId.LOGIN_ENGINE; } /** * This will be called immediately after creation to perform extra * initialisation. */ @Override public void onCreate() { LogUtils.logD("LoginEngine.OnCreate()"); mState = State.NOT_INITIALISED; mCurrentSubscriberId = mTelephonyManager.getSubscriberId(); IntentFilter filter = new IntentFilter(SmsBroadcastReceiver.ACTION_ACTIVATION_CODE); mContext.registerReceiver(mEventReceiver, filter); mIsRegistrationComplete = StateTable.isRegistrationComplete(mDb.getReadableDatabase()); } /** * This will be called just before the engine is shutdown. Cleans up any * resources used. */ @Override public void onDestroy() { LogUtils.logD("LoginEngine.onDestroy()"); Intent intent = new Intent(); intent.setAction(Intents.HIDE_LOGIN_NOTIFICATION); mContext.sendBroadcast(intent); removeAllListeners(); mContext.unregisterReceiver(mEventReceiver); } /** * Called by the INowPlusService implementation to start a manual login. * Adds a manual login UI request to the queue and kicks the worker thread. * * @param loginDetails The login information entered by the user */ public void addUiLoginRequest(LoginDetails loginDetails) { LogUtils.logD("LoginEngine.addUiLoginRequest()"); addUiRequestToQueue(ServiceUiRequest.LOGIN, loginDetails); } /** * Called by the INowPlusService implementation to remove user data Issues a * UI request to effectively log out. */ public void addUiRemoveUserDataRequest() { LogUtils.logD("LoginEngine.addUiRemoveUserDataRequest()"); addUiRequestToQueue(ServiceUiRequest.REMOVE_USER_DATA, null); } /** * Called by the INowPlusService implementation to start the sign-up * process. Adds a registration UI request to the queue and kicks the worker * thread. * * @param details The registration details entered by the user */ public void addUiRegistrationRequest(RegistrationDetails details) { LogUtils.logD("LoginEngine.addUiRegistrationRequest()"); addUiRequestToQueue(ServiceUiRequest.REGISTRATION, details); } /** * Called by the INowPlusService implementation to fetch terms of service * text for the UI. Adds a fetch terms of service UI request to the queue * and kicks the worker thread. */ public void addUiFetchTermsOfServiceRequest() { LogUtils.logD("LoginEngine.addUiFetchTermsOfServiceRequest()"); addUiRequestToQueue(ServiceUiRequest.FETCH_TERMS_OF_SERVICE, null); } /** * Called by the INowPlusService implementation to privacy statement for the * UI. Adds a fetch privacy statement UI request to the queue and kicks the * worker thread. */ public void addUiFetchPrivacyStatementRequest() { LogUtils.logD("LoginEngine.addUiFetchPrivacyStatementRequest()"); addUiRequestToQueue(ServiceUiRequest.FETCH_PRIVACY_STATEMENT, null); } /** * Called by the INowPlusService implementation to check if a username is * available for registration. Adds a get username state UI request to the * queue and kicks the worker thread. * * @param username Username to fetch the state of * TODO: Not currently used by UI. */ public void addUiGetUsernameStateRequest(String username) { LogUtils.logD("LoginEngine.addUiGetUsernameStateRequest()"); addUiRequestToQueue(ServiceUiRequest.USERNAME_AVAILABILITY, username); } /** * Return the absolute time in milliseconds when the engine needs to run * (based on System.currentTimeMillis). * * @return -1 never needs to run, 0 needs to run as soon as possible, * CurrentTime + 60000 to run in 1 minute, etc. */ @Override public long getNextRunTime() { if (isCommsResponseOutstanding()) { return 0; } if (uiRequestReady()) { return 0; } switch (mState) { case NOT_INITIALISED: return 0; case NOT_REGISTERED: case LOGGED_ON: case LOGIN_FAILED: case LOGIN_FAILED_WRONG_CREDENTIALS: return -1; case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: if (mActivationCode != null) { return 0; } break; case LOGGED_OFF: return 0; case LOGGED_OFF_WAITING_FOR_NETWORK: if (NetworkAgent.getAgentState() == AgentState.CONNECTED) { return 0; } break; case RETRIEVING_PUBLIC_KEY: return 0; default: // Do nothing. break; } return getCurrentTimeout(); } /** * Do some work but anything that takes longer than 1 second must be broken * up. The type of work done includes: * <ul> * <li>If a comms response from server is outstanding, process it</li> * <li>If a timeout is pending, process it</li> * <li>If an SMS activation code has been received, process it</li> * <li>Retry auto login if necessary</li> * </ul> */ @Override public void run() { LogUtils.logD("LoginEngine.run()"); if (isCommsResponseOutstanding() && processCommsInQueue()) { return; } if (processTimeout()) { return; } switch (mState) { case NOT_INITIALISED: initialiseEngine(); return; case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: if (mActivationCode != null) { handleSmsResponse(); return; } break; case RETRIEVING_PUBLIC_KEY: break; case LOGGED_OFF: case LOGGED_OFF_WAITING_FOR_NETWORK: // AA mCurrentNoOfRetries = 0; if (retryAutoLogin()) { return; } default: // do nothing. break; } if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { if (!isUiRequestOutstanding()) { return false; } switch (mState) { case NOT_REGISTERED: case LOGGED_OFF: case LOGGED_ON: case LOGIN_FAILED: case CREATING_SESSION_AUTO: case LOGIN_FAILED_WRONG_CREDENTIALS: case LOGGED_OFF_WAITING_FOR_RETRY: return true; default: return false; } } /** * Determines if the user is currently logged in with a valid session. * * @return true if logged in, false otherwise */ public boolean isLoggedIn() { return mState == State.LOGGED_ON; } /** * Add a listener which will receive events whenever the login state * changes. * * @param listener The callback interface */ public synchronized void addListener(ILoginEventsListener listener) { LogUtils.logD("LoginEngine.addListener()"); if (!mEventsListener.contains(listener)) { mEventsListener.add(listener); } } /** * Remove a listener added by the addListener function. * * @param listener The same callback interface passed in to the add function */ public synchronized void removeListener(ILoginEventsListener listener) { LogUtils.logD("LoginEngine.removeListener()"); mEventsListener.remove(listener); } /** * Remove all ILoginStateChangeListener (done as part of cleanup). */ private synchronized void removeAllListeners() { LogUtils.logD("LoginEngine.removeAllListeners()"); if (mEventsListener != null) { mEventsListener.clear(); } } /** * Once the engine has finished processing a user request, this function is * called to restore the state back to an appropriate value (based on the * user login state). */ private synchronized void restoreLoginState() { LogUtils.logD("LoginEngine.restoreLoginState"); if (mIsRegistrationComplete) { if (sActivatedSession != null) { newState(State.LOGGED_ON); } else { if (mAreLoginDetailsValid) { newState(State.LOGGED_OFF); } else { newState(State.LOGIN_FAILED); } } } else { newState(State.NOT_REGISTERED); } } /** * Called when a server response is received, processes the response based * on the engine state. * * @param resp Response data from server */ @Override protected void processCommsResponse(ResponseQueue.Response resp) { LogUtils.logD("LoginEngine.processCommsResponse() - resp = " + resp); switch (mState) { case SIGNING_UP: handleSignUpResponse(resp.mDataTypes); break; case RETRIEVING_PUBLIC_KEY: handleNewPublicKeyResponse(resp.mDataTypes); break; case CREATING_SESSION_MANUAL: handleCreateSessionManualResponse(resp.mDataTypes); break; case CREATING_SESSION_AUTO: handleCreateSessionAutoResponse(resp.mDataTypes); break; case REQUESTING_ACTIVATION_CODE: handleRequestingActivationResponse(resp.mDataTypes); break; case ACTIVATING_ACCOUNT: handleActivateAccountResponse(resp.mDataTypes); break; case FETCHING_TERMS_OF_SERVICE: case FETCHING_PRIVACY_STATEMENT: case FETCHING_USERNAME_STATE: - handleServerSimpleTextResponse(resp.mDataTypes); + handleServerSimpleTextResponse(resp.mDataTypes, mState); break; default: // do nothing. break; } } /** * Called when a UI request is ready to be processed. Handlers the UI * request based on the type. * * @param requestId UI request type * @param data Interpretation of this data depends on the request type */ @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { LogUtils.logD("LoginEngine.processUiRequest() - reqID = " + requestId); switch (requestId) { case LOGIN: startManualLoginProcess((LoginDetails)data); break; case REGISTRATION: startRegistrationProcessCrypted((RegistrationDetails)data); break; case REMOVE_USER_DATA: startLogout(); // Remove NAB Account at this point (does nothing on 1.X) NativeContactsApi.getInstance().removePeopleAccount(); super.onReset(); // Sets the reset flag as done break; case LOGOUT: startLogout(); break; case FETCH_TERMS_OF_SERVICE: startFetchTermsOfService(); break; case FETCH_PRIVACY_STATEMENT: startFetchPrivacyStatement(); break; case USERNAME_AVAILABILITY: startFetchUsernameState((String)data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); } } /** * Called by the run() function the first time it is executed to perform * non-trivial initialisation such as auto login. */ private void initialiseEngine() { LogUtils.logD("LoginEngine.initialiseEngine()"); if (ServiceStatus.SUCCESS == mDb.fetchLogonCredentialsAndPublicKey(mLoginDetails, mPublicKey)) { if (mLoginDetails.mSubscriberId != null && !mLoginDetails.mSubscriberId.equals(mCurrentSubscriberId)) { LogUtils.logW("SIM card has changed. Login session invalid"); } else { sActivatedSession = StateTable.fetchSession(mDb.getReadableDatabase()); } } mAreLoginDetailsValid = true; restoreLoginState(); clearTimeout(); } /** * Starts the sign-up process where the password is RSA encrypted. A setting * determines if this function is used in preference to * {@link #startRegistrationProcess(RegistrationDetails)} function. * * @param details Registration details received from the UI request */ private void startRegistrationProcessCrypted(RegistrationDetails details) { LogUtils.logD("startRegistrationCrypted"); if (details == null || details.mUsername == null || details.mPassword == null) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } setRegistrationComplete(false); setActivatedSession(null); mRegistrationDetails.copy(details); mLoginDetails.mUsername = mRegistrationDetails.mUsername; mLoginDetails.mPassword = mRegistrationDetails.mPassword; try { final long timestampInSeconds = System.currentTimeMillis() / MS_IN_SECONDS; final byte[] theBytes = prepareBytesForSignup(timestampInSeconds); mLoginDetails.mAutoConnect = true; mLoginDetails.mRememberMe = true; mLoginDetails.mMobileNo = mRegistrationDetails.mMsisdn; mLoginDetails.mSubscriberId = mCurrentSubscriberId; mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); startSignUpCrypted(theBytes, timestampInSeconds); } catch (InvalidCipherTextException e) { e.printStackTrace(); } } /** * Encrypts the sign-up data ready for sending to the server * * @param timeStampInSeconds Current time in milliseconds * @return Raw data that can be sent to the server */ private byte[] prepareBytesForSignup(long timeStampInSeconds) throws InvalidCipherTextException { byte[] theBytes = null; if (mPublicKey != null) { if (mPublicKey.mExponential != null && (mPublicKey.mModulus != null)) { theBytes = RSAEncryptionUtils.encryptRSA(RSAEncryptionUtils.getRSAPubKey( mPublicKey.mModulus, mPublicKey.mExponential), makeSecurePassword( mLoginDetails.mUsername, mLoginDetails.mPassword, timeStampInSeconds)); } } if (theBytes == null) { RSAEncryptionUtils.copyDefaultPublicKey(mPublicKey);// we'll store // the default // public key // into the db theBytes = RSAEncryptionUtils.encryptRSA(RSAEncryptionUtils.getDefaultPublicKey(), makeSecurePassword(mLoginDetails.mUsername, mLoginDetails.mPassword, timeStampInSeconds)); } return theBytes; } /** * Concatenates the username, password, current time and some other data * into a string which can be encrypted and sent to the server. * * @param userName User name for sign-in or sign-up * @param password Password as entered by user * @param ts Current time in milliseconds * @return Concatenated data */ private static String makeSecurePassword(String userName, String password, long ts) { String appSecret = SettingsManager.getProperty(Settings.APP_SECRET_KEY);// RSAEncrypter.testAppSecretThrottled; final char amp = '&'; if (ts <= 0 || // userName == null || userName.trim().length() == 0 || // password == null || password.trim().length() == 0 || // // set application key somewhere appSecret == null || appSecret.trim().length() == 0) return null; final String passwordT = password.trim(); final String userNameT = userName.trim(); final StringBuffer sb = new StringBuffer(); sb.append(appSecret).append(amp).append(Long.toString(ts)).append(amp).append(userNameT) .append(amp).append(passwordT); return sb.toString(); } /** * Puts the engine into the signing up state and sends an encrypted sign-up * request to the server. * * @param theBytes byte-array containing encrypted password data. * @param timestamp Current timestamp. */ private void startSignUpCrypted(byte[] theBytes, long timestamp) { LogUtils.logD("startSignUpCrypted()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } mActivationCode = null; newState(State.SIGNING_UP); if (!validateRegistrationDetails()) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } int reqId = Auth.signupUserCrypted( this, mRegistrationDetails.mFullname, mRegistrationDetails.mUsername, theBytes, // what is encrypted timestamp, mRegistrationDetails.mEmail, mRegistrationDetails.mBirthdayDate, mRegistrationDetails.mMsisdn, mRegistrationDetails.mAcceptedTAndC, mRegistrationDetails.mCountrycode, mRegistrationDetails.mTimezone, mRegistrationDetails.mLanguage, mRegistrationDetails.mMobileOperatorId, mRegistrationDetails.mMobileModelId, mRegistrationDetails.mSendConfirmationMail, mRegistrationDetails.mSendConfirmationSms, mRegistrationDetails.mSubscribeToNewsLetter); if (!setReqId(reqId)) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Basic check to determine if the registration details given by the user * are valid * * @return true if the details are valid, false otherwise. */ private boolean validateRegistrationDetails() { if (mRegistrationDetails.mFullname == null || mRegistrationDetails.mEmail == null || mRegistrationDetails.mBirthdayDate == null || mRegistrationDetails.mMsisdn == null || mRegistrationDetails.mAcceptedTAndC == null || mRegistrationDetails.mCountrycode == null || mRegistrationDetails.mTimezone == null || mRegistrationDetails.mLanguage == null || mRegistrationDetails.mMobileOperatorId == null || mRegistrationDetails.mMobileModelId == null || mRegistrationDetails.mSendConfirmationMail == null || mRegistrationDetails.mSendConfirmationSms == null || mRegistrationDetails.mSubscribeToNewsLetter == null) { return false; } return true; } /** * Requests a new Public Key from the server. */ public void getNewPublicKey() { LogUtils.logD("LoginEngine.getNewPublicKey"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } mActivationCode = null; newState(State.RETRIEVING_PUBLIC_KEY); if (!setReqId(Auth.getPublicKey(this))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch terms of service request to the server. */ private void startFetchTermsOfService() { LogUtils.logD("LoginEngine.startFetchTermsOfService()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } newState(State.FETCHING_TERMS_OF_SERVICE); if (!setReqId(Auth.getTermsAndConditions(this))) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch privacy statement request to the server. */ private void startFetchPrivacyStatement() { LogUtils.logD("LoginEngine.startFetchPrivacyStatement()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } newState(State.FETCHING_PRIVACY_STATEMENT); if (!setReqId(Auth.getPrivacyStatement(this))) { updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a fetch user-name state request to the server. * * @param username, the user-name to retrieve information for. */ private void startFetchUsernameState(String username) { LogUtils.logD("LoginEngine.startFetchUsernameState()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } mLoginDetails.mUsername = username; newState(State.FETCHING_USERNAME_STATE); if (!setReqId(Auth.getUsernameState(this, username))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sets registration complete flag to false then starts a new sign-in * request. * * @param details Login details received from the UI request */ private void startManualLoginProcess(LoginDetails details) { LogUtils.logD("LoginEngine.startManualLoginProcess()"); setRegistrationComplete(false); setActivatedSession(null); if (details == null) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, null); return; } mLoginDetails.copy(details); mLoginDetails.mSubscriberId = mCurrentSubscriberId; mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); if (Settings.ENABLE_ACTIVATION) { startRequestActivationCode(); } else { startGetSessionManual(); } } /** * Sends a request activation code request to the server. */ private void startRequestActivationCode() { LogUtils.logD("LoginEngine.startRequestActivationCode()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } mActivationCode = null; newState(State.REQUESTING_ACTIVATION_CODE); if (!setReqId(Auth.requestActivationCode(this, mLoginDetails.mUsername, mLoginDetails.mMobileNo))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a get session by credentials request to the server. */ private void startGetSessionManual() { LogUtils.logD("LoginEngine.startGetSessionManual()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } newState(State.CREATING_SESSION_MANUAL); if (!setReqId(Auth.getSessionByCredentials(this, mLoginDetails.mUsername, mLoginDetails.mPassword, null))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } /** * Sends a activate account request to the server. */ private void startActivateAccount() { LogUtils.logD("LoginEngine.startActivateAccount()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } if (Settings.ENABLE_ACTIVATION) { newState(State.ACTIVATING_ACCOUNT); if (!setReqId(Auth.activate(this, mActivationCode))) { completeUiRequest(ServiceStatus.ERROR_COMMS, null); return; } } else { setRegistrationComplete(true); completeUiRequest(ServiceStatus.SUCCESS, null); } } /** * Clears the session and registration complete information so that the user * will need to manually login again to use the now+ services. Does not * currently send a request to the server to log out. */ private void startLogout() { LogUtils.logD("LoginEngine.startLogout()"); setRegistrationComplete(false); setActivatedSession(null); completeUiRequest(ServiceStatus.SUCCESS, null); } /** * Clears the session and registration complete information so that the user * will need to manually login again to use the now+ services. Does not * currently send a request to the server to log out. */ public final void logoutAndRemoveUser() { LogUtils.logD("LoginEngine.startLogout()"); addUiRemoveUserDataRequest(); LoginPreferences.clearPreferencesFile(mContext); mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UNSOLICITED_GO_TO_LANDING_PAGE, null); } /** * Retries to log the user in based on credential information stored in the * database. * * @return true if the login process was able to start */ public boolean retryAutoLogin() { LogUtils.logD("LoginEngine.retryAutoLogin()"); setActivatedSession(null); if (ServiceStatus.SUCCESS != mDb.fetchLogonCredentialsAndPublicKey(mLoginDetails, mPublicKey)) { LogUtils .logE("LoginEngine.retryAutoLogin() - Unable to fetch credentials from database"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } // AA: commented the condition out if (Settings.ENABLE_ACTIVATION) { // AA: the old version if (mCurrentSubscriberId == null || // !mCurrentSubscriberId.equals(mLoginDetails.mSubscriberId)) { // // logging off/fail will be done in another way according to bug 8288 if (mCurrentSubscriberId != null && !mCurrentSubscriberId.equals(mLoginDetails.mSubscriberId)) { LogUtils.logV("LoginEngine.retryAutoLogin() -" + " SIM card has changed or is missing (old subId = " + mLoginDetails.mSubscriberId + ", new subId = " + mCurrentSubscriberId + ")"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } // } if (mLoginDetails.mUsername == null || mLoginDetails.mPassword == null || mLoginDetails.mMobileNo == null) { LogUtils.logV("LoginEngine.retryAutoLogin() - Username, password " + "or mobile number are missing (old username = " + mLoginDetails.mUsername + ", mobile no = " + mLoginDetails.mMobileNo + ")"); mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED); return false; } mAreLoginDetailsValid = true; if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { newState(State.LOGGED_OFF_WAITING_FOR_NETWORK); LogUtils.logV("LoginEngine.retryAutoLogin() - Internet connection down. " + "Will try again when connection is available"); return false; } newState(State.CREATING_SESSION_AUTO); if (!setReqId(Auth.getSessionByCredentials(this, mLoginDetails.mUsername, mLoginDetails.mPassword, null))) { return false; } return true; } /** * Helper function to set the registration complete flag and update the * database with the new state. * * @param value true if registration is completed */ private void setRegistrationComplete(boolean value) { LogUtils.logD("LoginEngine.setRegistrationComplete(" + value + ")"); if (value != mIsRegistrationComplete) { StateTable.setRegistrationComplete(value, mDb.getWritableDatabase()); mIsRegistrationComplete = value; if (mIsRegistrationComplete) { // Create NAB Account at this point (does nothing on 1.X // devices) final NativeContactsApi nabApi = NativeContactsApi.getInstance(); if (!nabApi.isPeopleAccountCreated()) { // TODO: React upon failure to create account nabApi.addPeopleAccount(LoginPreferences.getUsername()); } } } } /** * Changes the state of the engine. Also displays the login notification if * necessary. * * @param newState The new state */ private void newState(State newState) { State oldState = mState; synchronized (mMutex) { if (newState == mState) { return; } mState = newState; } LogUtils.logV("LoginEngine.newState: " + oldState + " -> " + mState); Intent intent = null; // Update notification switch (mState) { case LOGIN_FAILED_WRONG_CREDENTIALS: intent = new Intent(); intent.setAction(Intents.START_LOGIN_ACTIVITY); mContext.sendBroadcast(intent); setRegistrationComplete(false); break; // here should be no break case NOT_REGISTERED: case LOGIN_FAILED: intent = new Intent(); intent.setAction(Intents.LOGIN_FAILED); mContext.sendBroadcast(intent); setRegistrationComplete(false); // startLogout(); // mDb.removeUserData(); // sending user to login screen again // should be done by UI itself because // when it's done from here it cause problems when user tries to // login // giving wrong credentials, ui flow will be broken break; case LOGGED_OFF: case LOGGED_OFF_WAITING_FOR_NETWORK: case LOGGED_OFF_WAITING_FOR_RETRY: case LOGGED_ON: intent = new Intent(); intent.setAction(Intents.HIDE_LOGIN_NOTIFICATION); mContext.sendBroadcast(intent); break; default:// do nothing break; } // Update listeners with any state changes switch (mState) { case NOT_REGISTERED: case LOGIN_FAILED: case LOGIN_FAILED_WRONG_CREDENTIALS: case LOGGED_OFF: onLoginStateChanged(false); break; case LOGGED_ON: onLoginStateChanged(true); break; default: // do nothing. break; } } /** * Called when the engine transitions between the logged in and logged out * states. Notifies listeners. * * @param loggedIn true if the user is now logged in, false otherwise. */ private synchronized void onLoginStateChanged(boolean loggedIn) { LogUtils.logD("LoginEngine.onLoginStateChanged() Login state changed to " + (loggedIn ? "logged in." : "logged out.")); if (loggedIn == mCurrentLoginState) { return; } mCurrentLoginState = loggedIn; for (ILoginEventsListener listener : mEventsListener) { listener.onLoginStateChanged(loggedIn); } } /** * A helper function which determines which activity should be displayed * when the UI is loaded. * * @return true if landing page should be displayed, false otherwise */ public synchronized boolean getLoginRequired() { LogUtils.logD("LoginEngine.getLoginRequired() - " + !mIsRegistrationComplete); return !mIsRegistrationComplete; } /** * Retrieves the active comms session. * * @return The session or NULL if the user is logged out. */ public static AuthSessionHolder getSession() { return sActivatedSession; } /** * Helper function to store the new session in the database and inform * clients that the session has changed. * * @param session The new session or NULL if the user has logged off. */ public synchronized void setActivatedSession(AuthSessionHolder session) { LogUtils.logD("LoginEngine.setActivatedSession() session[" + session + "]"); sActivatedSession = session; if (session != null) { LogUtils.logD("LoginEngine.setActivatedSession() Login successful"); } else { LogUtils.logW("LoginEngine.setActivatedSession() " + "Login unsuccessful, the session is NULL"); } StateTable.setSession(session, mDb.getWritableDatabase()); } /** * Called when a response to the sign-up API is received. In case of success * sets a timeout value waiting for the activation SMS to arrive. * * @param data The received data */ private void handleSignUpResponse(List<BaseDataType> data) { ServiceStatus errorStatus = getResponseStatus(BaseDataType.CONTACT_DATA_TYPE, data); LogUtils.logD("LoginEngine.handleSignUpResponse() errorStatus[" + errorStatus.name() + "]"); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils.logD("LoginEngine.handleSignUpResponse() - Registration successful"); if (!Settings.ENABLE_ACTIVATION) { startGetSessionManual(); } else { // Now waiting for SMS... setTimeout(ACTIVATE_LOGIN_TIMEOUT); } // AA } else if (errorStatus == ServiceStatus.ERROR_INVALID_PUBLIC_KEY) { // start new key retrieval and make the new cycle getNewPublicKey(); } else { completeUiRequest(errorStatus, null); } } /** * Called when a response to the server fetch public key request is * received. Validates the response and stores the new public key details. * * @param mDataTypes Response data from server. */ private void handleNewPublicKeyResponse(List<BaseDataType> mDataTypes) { LogUtils.logD("LoginEngine.handleNewPublicKeyResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.PUBLIC_KEY_DETAILS_DATA_TYPE, mDataTypes); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils.logD("LoginEngine.handleNewPublicKeyResponse() - Succesfully retrieved"); // AA // 1. save to DB; save the flag that we aren't using default and // have to use one from DB // 2. start registration again mPublicKey = (PublicKeyDetails)mDataTypes.get(0); // done in startRegistrationProcessCrypted already // mDb.modifyCredentialsAndPublicKey(mLoginDetails, mPublicKey); startRegistrationProcessCrypted(mRegistrationDetails); } else { completeUiRequest(errorStatus, null); } } /** * Called when a response to the GetSessionByCredentials API is received * (manual login). In case of success, tries to activate the account using * the activation code received by SMS. * * @param data The received data */ private void handleCreateSessionManualResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleCreateSessionManualResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AUTH_SESSION_HOLDER_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS && (data.size() > 0)) { setActivatedSession((AuthSessionHolder)data.get(0)); startActivateAccount(); return; } completeUiRequest(errorStatus, null); } /** * Called when a response to the GetSessionByCredentials API is received * (auto login). In case of success, moves to the logged in state * * @param data The received data */ private void handleCreateSessionAutoResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleCreateSessionResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AUTH_SESSION_HOLDER_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { clearTimeout(); setActivatedSession((AuthSessionHolder)data.get(0)); newState(State.LOGGED_ON); } else { LogUtils.logE("LoginEngine.handleCreateSessionResponse() - Auto Login Failed Error " + errorStatus); // AA:the 1st retry failed, just go to the start page, // if (loginAttemptsRemaining() // && errorStatus!=ServiceStatus.ERROR_INVALID_PASSWORD) { // newState(State.LOGGED_OFF_WAITING_FOR_RETRY); // setTimeout(LOGIN_RETRY_TIME); // } else { // mAreLoginDetailsValid = false; if (errorStatus == ServiceStatus.ERROR_INVALID_PASSWORD) { mAreLoginDetailsValid = false; newState(State.LOGIN_FAILED_WRONG_CREDENTIALS); } else { newState(State.LOGIN_FAILED); } // } } } /** * Called when a response to the RequestActivationCode API is received * (manual login). In case of success, tries to fetch a login session from * the server. * * @param data The received data */ private void handleRequestingActivationResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleRequestingActivationResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { // Now waiting for SMS... setTimeout(ACTIVATE_LOGIN_TIMEOUT); return; } completeUiRequest(errorStatus, null); } /** * Called when a response to the Activate API is received (manual login or * sign-up). In case of success, moves to the logged in state and completes * the manual login or sign-up request. * * @param data The received data */ private void handleActivateAccountResponse(List<BaseDataType> data) { LogUtils.logD("LoginEngine.handleActivateAccountResponse()"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.STATUS_MSG_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { LogUtils .logD("LoginEngine.handleActivateAccountResponse: ** Mobile number activated **"); setRegistrationComplete(true); completeUiRequest(ServiceStatus.SUCCESS, null); return; } setActivatedSession(null); completeUiRequest(ServiceStatus.ERROR_ACCOUNT_ACTIVATION_FAILED, null); } /** * Called when a response to the GetTermsAndConditions, GetPrivacyStatement * and GetUsernameState APIs are received. In case of success, completes the * request and passes the response data to the UI. * * @param data The received data */ - private void handleServerSimpleTextResponse(List<BaseDataType> data) { - LogUtils.logD("LoginEngine.handleServerSimpleTextResponse()"); - ServiceStatus errorStatus = getResponseStatus(BaseDataType.SIMPLE_TEXT_DATA_TYPE, data); - if (errorStatus == ServiceStatus.SUCCESS) { - SimpleText simpleText = (SimpleText)data.get(0); - completeUiRequest(ServiceStatus.SUCCESS, simpleText.mValue.toString()); - return; + private void handleServerSimpleTextResponse(List<BaseDataType> data, State type) { + LogUtils.logV("LoginEngine.handleServerSimpleTextResponse()"); + ServiceStatus serviceStatus = getResponseStatus(BaseDataType.SIMPLE_TEXT_DATA_TYPE, data); + + String result = null; + if (serviceStatus == ServiceStatus.SUCCESS) { + result = ((SimpleText) data.get(0)).mValue.toString().replace( + CARRIAGE_RETURN_CHARACTER, SPACE_CHARACTER); + + switch (type) { + case FETCHING_TERMS_OF_SERVICE: + LogUtils.logD("LoginEngine.handleServerSimpleTextResponse() Terms of Service"); + ApplicationCache.setTermsOfService(result, mContext); + break; + case FETCHING_PRIVACY_STATEMENT: + LogUtils.logD("LoginEngine.handleServerSimpleTextResponse() Privacy Statemet"); + ApplicationCache.setPrivacyStatemet(result, mContext); + break; + case FETCHING_USERNAME_STATE: + // TODO: Unused by UI. + break; + } } - completeUiRequest(errorStatus, null); + + updateTermsState(serviceStatus, result); } - + /*** - * Informs the UI to update any terms which are being shown on screen. - * - * @param serviceStatus Current ServiceStatus. - * @param messageText Legacy call for old UI (TODO: remove after UI-Refresh - * merge). NULL when combined with a ServiceStatus of - * ERROR_COMMS, or contains the Privacy or Terms and Conditions - * text to be displayed in the UI. - */ - private void updateTermsState(ServiceStatus serviceStatus, String messageText) { - ApplicationCache.setTermsStatus(serviceStatus); - - /** Trigger UiAgent. **/ - mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.TERMS_CHANGED_EVENT, null); - - /** Clear this request from the UI queue. **/ - completeUiRequest(serviceStatus, messageText); - } + * Informs the UI to update any terms which are being shown on screen. + * + * @param serviceStatus Current ServiceStatus. + * @param messageText Legacy call for old UI (TODO: remove after UI-Refresh + * merge). NULL when combined with a ServiceStatus of + * ERROR_COMMS, or contains the Privacy or Terms and Conditions + * text to be displayed in the UI. + */ + private void updateTermsState(ServiceStatus serviceStatus, String messageText) { + ApplicationCache.setTermsStatus(serviceStatus); + + /** Trigger UiAgent. **/ + mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.TERMS_CHANGED_EVENT, null); + + /** Clear this request from the UI queue. **/ + completeUiRequest(serviceStatus, messageText); + } /** * A broadcast receiver which is used to receive notifications when a data * SMS arrives. */ private final BroadcastReceiver mEventReceiver = new BroadcastReceiver() { /** * Called when an SMS arrives. The activation code is extracted from the * given intent and the worker thread kicked. * * @param context Context from which the intent was broadcast * @param intent Will only process the SMS which the action is * {@link SmsBroadcastReceiver#ACTION_ACTIVATION_CODE}. */ @Override public void onReceive(Context context, Intent intent) { LogUtils.logD("LoginEngine.BroadcastReceiver.onReceive - Processing data sms"); if (intent.getAction().equals(SmsBroadcastReceiver.ACTION_ACTIVATION_CODE)) { String activationCode = intent.getStringExtra("code"); LogUtils .logD("LoginEngine.BroadcastReceiver.onReceive - Activation code Received: " + activationCode); synchronized (LoginEngine.this) { mActivationCode = activationCode; } mEventCallback.kickWorkerThread(); } } }; /** * Called when an SMS is received during sign-up or manual login. Starts * requesting a session from the server. */ private void handleSmsResponse() { LogUtils.logD("LoginEngine.handleSmsResponse(" + mActivationCode + ")"); clearTimeout(); startGetSessionManual(); } /** * Called by the base engine implementation whenever a UI request is * completed to do any necessary cleanup. We use it to restore our state to * a suitable value. */ @Override protected void onRequestComplete() { LogUtils.logD("LoginEngine.onRequestComplete()"); restoreLoginState(); } /** * Handles timeouts for SMS activation and auto login retries. */ protected synchronized void onTimeoutEvent() { LogUtils.logD("LoginEngine.onTimeoutEvent()"); switch (mState) { case REQUESTING_ACTIVATION_CODE: case SIGNING_UP: completeUiRequest(ServiceStatus.ERROR_SMS_CODE_NOT_RECEIVED, null); break; case LOGGED_OFF_WAITING_FOR_RETRY: retryAutoLogin(); break; default: // do nothing. break; } } /** * Called by the framework before a remove user data operation takes place. * Initiates a suitable UI request which will kick the worker thread. */ @Override public void onReset() { addUiRemoveUserDataRequest(); } /** * Set 'dummy' auth session for test purposes only. * * @param session 'dummy' session supplied to LoginEngine */ public static void setTestSession(AuthSessionHolder session) { sActivatedSession = session; } }
360/360-Engine-for-Android
32829fef8fbf74f893539a210dd56892dc084a80
Code review comments by Rudy
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index fe5bfc6..05b54aa 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,792 +1,792 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.engine.presence; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import android.text.TextUtils; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.ChatMessage; import com.vodafone360.people.datatypes.Conversation; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.PresenceList; import com.vodafone360.people.datatypes.PushAvailabilityEvent; import com.vodafone360.people.datatypes.PushChatMessageEvent; import com.vodafone360.people.datatypes.PushClosedConversationEvent; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.datatypes.SystemNotification.Tags; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener; import com.vodafone360.people.engine.meprofile.SyncMeDbUtils; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.agent.UiAgent; import com.vodafone360.people.service.io.ResponseQueue.Response; import com.vodafone360.people.service.io.api.Chat; import com.vodafone360.people.service.io.api.Presence; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener; import com.vodafone360.people.utils.HardcodedUtils; import com.vodafone360.people.utils.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, ITcpConnectionListener { /** Check every 24 hours **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private List<TimelineSummaryItem> mFailedMessagesList; // (to, network) /** The list of Users still to be processed. **/ private List<User> mUsers = null; /** * This state indicates there are no more pending presence payload * information to be processed. **/ private static final int IDLE = 0; /** * This state indicates there are some pending presence payload information * to be processed. **/ private static final int UPDATE_PROCESSING_GOING_ON = 1; /** Timeout between each presence update processing. **/ private static final long UPDATE_PRESENCE_TIMEOUT_MILLS = 0; /** The page size i.e the number of presence updates processed at a time. **/ private static final int UPDATE_PRESENCE_PAGE_SIZE = 10; /** The number of pages after which the HandlerAgent is notified. **/ private static final int NOTIFY_AGENT_PAGE_INTERVAL = 5; /** The state of the presence Engine. **/ private int mState = IDLE; /** * Number of pages of presence Updates done. This is used to control when a * notification is sent to the UI. **/ private int mIterations = 0; /** * True if the engine runs for the 1st time. */ private boolean firstRun = true; /** * * @param eventCallback * @param databaseHelper */ public PresenceEngine(IEngineEventCallback eventCallback, DatabaseHelper databaseHelper) { super(eventCallback); mEngineId = EngineId.PRESENCE_ENGINE; mDbHelper = databaseHelper; mSendMessagesHash = new Hashtable<String, ChatMessage>(); mFailedMessagesList = new ArrayList<TimelineSummaryItem>(); } @Override public void onCreate() { } @Override public void onDestroy() { if (mDbHelper != null && SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper) != null) { PresenceDbUtils.resetPresenceStatesAcceptForMe(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper), mDbHelper); } EngineManager.getInstance().getLoginEngine().removeListener(this); } /** - * checks the external conditions which have to be happen before the engine - * can run + * Checks if the SyncMe and ContactSync Engines have both completed first time sync. * - * @return true if everything is ready + * @return true if both engines have completed first time sync */ - private boolean canRun() { + private boolean isFirstTimeSyncComplete() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; - if (!canRun()) { - mNextRuntime = -1; - LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" - + mNextRuntime); - return mNextRuntime; + } + + if (!isFirstTimeSyncComplete()) { + LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"); + return -1; } /** * need isUiRequestOutstanding() because currently the worker thread is * running and finishing before PresenceEngine.setNextRuntime is called */ if (isCommsResponseOutstanding() || isUiRequestOutstanding()) { LogUtils.logV("PresenceEngine getNextRunTime() comms response outstanding"); return 0; } if (firstRun) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); firstRun = false; } return getCurrentTimeout(); } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + getCurrentTimeout() + "]"); if (isCommsResponseOutstanding() && processCommsInQueue()) { LogUtils.logV("PresenceEngine.run() handled processCommsInQueue()"); return; } if (processTimeout()) { LogUtils.logV("PresenceEngine.run() handled processTimeout()"); return; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logV("PresenceEngine.run(): AgentState.DISCONNECTED"); setPresenceOffline(); } /** * and the getNextRunTime must check the uiRequestReady() function and * return 0 if it is true */ if (uiRequestReady() && processUiQueue()) { return; } } /** * Helper function which returns true if a UI request is waiting on the * queue and we are ready to process it. * * @return true if the request can be processed now. */ private boolean uiRequestReady() { return isUiRequestOutstanding(); } private User getMyAvailabilityStatusFromDatabase() { return PresenceDbUtils.getMeProfilePresenceStatus(mDbHelper); } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { - if (canRun()) { + if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setTimeout(CHECK_FREQUENCY); } } else { firstRun = true; mFailedMessagesList.clear(); mSendMessagesHash.clear(); setPresenceOffline(); } } /*** * Set the Global presence status to offline. */ private synchronized void setPresenceOffline() { PresenceDbUtils.setPresenceOfflineInDatabase(mDbHelper); // We clear the mUsers of any pending presence updates because this // Offline presence update request should take the highest priority. mUsers = null; mState = IDLE; - mEventCallback.getUiAgent().updatePresence(-1); + mEventCallback.getUiAgent().updatePresence(UiAgent.ALL_USERS); } @Override protected void onRequestComplete() { LogUtils.logI("PresenceEngine.onRequestComplete()"); } @Override protected void onTimeoutEvent() { LogUtils.logI("PresenceEngine.onTimeoutEvent()"); switch (mState) { case UPDATE_PROCESSING_GOING_ON: updatePresenceDatabaseNextPage(); break; case IDLE: default: if (mLoggedIn) { - if (canRun()) { + if (isFirstTimeSyncComplete()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setTimeout(CHECK_FREQUENCY); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); setTimeout(CHECK_FREQUENCY / 20); } } } } @Override protected void processCommsResponse(Response resp) { handleServerResponse(resp.mDataTypes); } private void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg) { UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && uiAgent.isSubscribedWithChat()) { uiAgent.sendUnsolicitedUiEvent(errorEvent, null); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users List of users that require updating. */ private synchronized void updatePresenceDatabase(List<User> users) { if (users == null || users.size() == 0) { LogUtils.logW("PresenceEngine.updatePresenceDatabase() users is NULL or zero size"); } else { if (mUsers == null) { mUsers = users; } else { // Doing an add one by one is not an efficient way but then // there is an issue in the addAll API. It crashes sometimes. // And the java code for the AddAll API seems to be erroneous. // More investigation is needed on this. for (User user : users) { mUsers.add(user); } } } mState = UPDATE_PROCESSING_GOING_ON; updatePresenceDatabaseNextPage(); } /** * This API makes the presence updates in pages of 10 with a timeout * after each page. The HandlerAgent is notified after every 10 pages. */ private synchronized void updatePresenceDatabaseNextPage(){ UiAgent uiAgent = mEventCallback.getUiAgent(); if(mUsers == null){ mState = IDLE; return; } int listSize = mUsers.size(); int start = 0; int end = UPDATE_PRESENCE_PAGE_SIZE; if(listSize == 0){ mState = IDLE; mUsers = null; return; } else if(listSize < end) { end = listSize; } List<User> userSubset = mUsers.subList(start, end); if ((userSubset != null)) { long idListeningTo = UiAgent.ALL_USERS; if (uiAgent != null) { idListeningTo = uiAgent.getLocalContactId(); } boolean updateUI = PresenceDbUtils.updateDatabase(userSubset, idListeningTo, mDbHelper); userSubset.clear(); // Send the update notification to UI for every UPDATE_PRESENCE_PAGE_SIZE*NOTIFY_AGENT_PAGE_INTERVAL updates. if (updateUI) { if (mUsers.size() == 0 || NOTIFY_AGENT_PAGE_INTERVAL == mIterations) { if (uiAgent != null) { uiAgent.updatePresence(idListeningTo); } mIterations = 0; } else { mIterations++; } } this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); } } /** * Updates the database with the given ChatMessage and Type. * * @param message ChatMessage. * @param type TimelineSummaryItem.Type. */ private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) { ChatDbUtils.convertUserIds(message, mDbHelper); LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message"); if (message.getLocalContactId() == null || message.getLocalContactId() < 0) { LogUtils.logE("PresenceEngine.updateChatDatabase() " + "WILL NOT UPDATE THE DB! - INVALID localContactId = " + message.getLocalContactId()); return; } /** We mark all incoming messages as unread. **/ ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper); UiAgent uiAgent = mEventCallback.getUiAgent(); if (uiAgent != null && (message.getLocalContactId() != -1)) { uiAgent.updateChat(message.getLocalContactId(), true); } } /** * Here we update the PresenceTable, and the ContactSummaryTable afterwards * the HandlerAgent receives the notification of presence states changes. * * @param users User that requires updating. */ private void updateMyPresenceInDatabase(User myself) { LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]"); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { mEventCallback.getUiAgent().updatePresence(myself.getLocalContactId()); } } /** * This method handles incoming presence status change push events and the * whole PresenceList * * @param dataTypes */ private void handleServerResponse(List<BaseDataType> dataTypes) { if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { int type = mBaseDataType.getType(); if (type == BaseDataType.PRESENCE_LIST_DATA_TYPE) { handlePresenceList((PresenceList)mBaseDataType); } else if (type == BaseDataType.PUSH_EVENT_DATA_TYPE) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (type == BaseDataType.CONVERSATION_DATA_TYPE) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (type == BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (type == BaseDataType.SERVER_ERROR_DATA_TYPE) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + type); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { updatePresenceDatabase(presenceList.getUsers()); } private void handleServerError(ServerError srvError) { LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError); ServiceStatus errorStatus = srvError.toServiceStatus(); if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) { LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { String to = conversation.getTos().get(0); if (mSendMessagesHash.containsKey(to)) { ChatMessage message = mSendMessagesHash.get(to); message.setConversationId(conversation.getConversationId()); /** Update the DB with an outgoing message. **/ updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING); Chat.sendChatMessage(message); // clean check if DB needs a cleaning (except for // the current conversation id) ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(), mDbHelper); } } } private void handlePushEvent(PushEvent event) { switch (event.mMessageType) { case AVAILABILITY_STATE_CHANGE: PushAvailabilityEvent pa = (PushAvailabilityEvent)event; updatePresenceDatabase(pa.mChanges); break; case CHAT_MESSAGE: PushChatMessageEvent pc = (PushChatMessageEvent)event; // update the DB with an incoming message updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING); break; case CLOSED_CONVERSATION: PushClosedConversationEvent pcc = (PushClosedConversationEvent)event; // delete the conversation in DB if (pcc.getConversation() != null) { ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper); } break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.getType()); } } private void handleSystemNotification(SystemNotification sn) { LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn); switch (sn.getSysCode()) { case SEND_MESSAGE_FAILED: ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString())); if (msg != null) { ChatDbUtils.deleteUnsentMessage(mDbHelper, msg); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null); break; case CONVERSATION_NULL: if (!mSendMessagesHash.isEmpty()) { mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString())); } showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null); break; case COMMUNITY_LOGOUT_SUCCESSFUL: break; default: LogUtils.logE("PresenceEngine.handleServerResponse()" + " - unhandled notification: " + sn); } } @Override protected void processUiRequest(ServiceUiRequest requestId, Object data) { - if (!canRun()) { + if (!isFirstTimeSyncComplete()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); if(data == null && requestId != ServiceUiRequest.GET_PRESENCE_LIST) { LogUtils.logW("PresenceEngine.processUiRequest() skipping processing for request with no data!"); return; } switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String,String>)data); break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); break; case CREATE_CONVERSATION: List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: ChatMessage msg = (ChatMessage)data; updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING); LogUtils.logW("PresenceEngine processUiRequest() SEND_CHAT_MESSAGE :" + msg); //cache the message (necessary for failed message sending failures) mSendMessagesHash.put(msg.getTos().get(0), msg); Chat.sendChatMessage(msg); break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); return; // don't complete with success and schedule the next runtime } completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } /** * Method used to jump start setting the availability. * This is primarily used for reacting to login/connection state changes. * @param me Our User */ private void initSetMyAvailabilityRequest(User me) { if (me == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) - || !canRun()) { + || !isFirstTimeSyncComplete()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param status Availability to set for all identities we have. */ public void setMyAvailability(OnlineStatus status) { if (status == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+status.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } // Get presences // TODO: Fill up hashtable with identities and online statuses Hashtable<String, String> presenceList = HardcodedUtils.createMyAvailabilityHashtable(status); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presenceList); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } /** * Changes the user's availability and therefore the state of the engine. * Also displays the login notification if necessary. * * @param presence Network-presence to set */ public void setMyAvailability(NetworkPresence presence) { if (presence == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with network presence:"+presence.toString()); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(); presenceList.add(presence); User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), null); me.setPayload(presenceList); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } private void createConversation(ChatMessage msg) { LogUtils.logW("PresenceEngine.createConversation():" + msg); // as we currently support sending msgs to just one person getting the 0 // element of "Tos" must be acceptable mSendMessagesHash.put(msg.getTos().get(0), msg); addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg); } /** * This method should be used to send a message to a contact * * @param tos - tlocalContactId of ContactSummary items the message is * intended for. Current protocol version only supports a single * recipient. * @param body the message text */ public void sendMessage(long toLocalContactId, String body, int networkId) { LogUtils.logW("PresenceEngine.sendMessage() to:" + toLocalContactId + ", body:" + body + ", at:" + networkId); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION"); return; } ChatMessage msg = new ChatMessage(); msg.setBody(body); // TODO: remove the hard code - go to UI and check what is there if (networkId == SocialNetwork.MOBILE.ordinal() || (networkId == SocialNetwork.PC.ordinal())) { msg.setNetworkId(SocialNetwork.VODAFONE.ordinal()); } else { msg.setNetworkId(networkId); } msg.setLocalContactId(toLocalContactId); ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper); if (msg.getConversationId() != null) { // TODO: re-factor this if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) { String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString() + ChatDbUtils.COLUMNS + msg.getUserId(); msg.setUserId(fullUserId); } addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg); } else { // if the conversation was not found that means it didn't exist, // need start a new one if (msg.getUserId() == null) { ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper); createConversation(msg); } } } - + + @Override public void onConnectionStateChanged(int state) { - if (mLoggedIn && canRun()) { + if (mLoggedIn && isFirstTimeSyncComplete()) { switch (state) { case STATE_CONNECTED: getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } /** * This method gets the availability information for Me Profile from the Presence * table and updates the same to the server. */ public final void setMyAvailability() { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); } /** * Convenience method. * Constructs a Hash table object containing My identities mapped against the provided status. * @param status Presence status to set for all identities * @return The resulting Hash table, is null if no identities are present */ public Hashtable<String, String> getPresencesForStatus(OnlineStatus status) { // Get cached identities from the presence engine ArrayList<Identity> identities = EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyChattableIdentities(); if(identities == null) { // No identities, just return null return null; } Hashtable<String, String> presences = new Hashtable<String, String>(); String statusString = status.toString(); for(Identity identity : identities) { presences.put(identity.mNetwork, statusString); } return presences; } } diff --git a/src/com/vodafone360/people/service/agent/UiAgent.java b/src/com/vodafone360/people/service/agent/UiAgent.java index 3be0b27..b2958a8 100644 --- a/src/com/vodafone360/people/service/agent/UiAgent.java +++ b/src/com/vodafone360/people/service/agent/UiAgent.java @@ -1,351 +1,351 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and * limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. */ package com.vodafone360.people.service.agent; import java.security.InvalidParameterException; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.Intents; import com.vodafone360.people.MainApplication; import com.vodafone360.people.engine.upgrade.UpgradeStatus; import com.vodafone360.people.engine.upgrade.VersionCheck; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.transport.ConnectionManager; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.WidgetUtils; /** * The UiAgent is aware when any "Live" Activities are currently on screen, and * contains business logic for sending unsolicited messages to the UI. This is * useful for knowing when to send chat messages, presence updates, * notifications, error messages, etc to an on screen Activity. */ public class UiAgent { /** UI Notification identifier. **/ public static final int UI_AGENT_NOTIFICATION_ID = 1; /** Pointer to MainApplication. **/ private MainApplication mMainApplication; /** * Store for pending UiEvents while no People Activities are currently on * screen. */ private ServiceUiRequest mUiEventQueue = null; /** * Store for pending UiEvent Bundles while no People Activities are * currently on screen. */ private Bundle mUiBundleQueue = null; /** * Handler object from a subscribed UI Activity. Note: This object is * nullified by a separate thread and is thereby declared volatile. */ private volatile Handler mHandler; /** * Local ID of the contact the Handler is tracking (-1 when tracking all). */ private long mLocalContactId; /** TRUE if the subscribed UI Activity expects chat messages. **/ private boolean mShouldHandleChat; /** Reference to Android Context. **/ private Context mContext = null; /** * This constant is used to indicate the UiAgent is now subscribed * to refresh events related to all local contact ids. */ public static final int ALL_USERS = -1; /** * Constructor. * * @param mainApplication Pointer to MainApplication. * @param context Reference to Android Context. */ public UiAgent(final MainApplication mainApplication, final Context context) { mMainApplication = mainApplication; mContext = context; mHandler = null; mLocalContactId = -1; mShouldHandleChat = false; } /*** * Send an unsolicited UI Event to the UI. If there are no on screen * Activities, then queue the message for later. The queue is of size one, * so higher priority messages will simply overwrite older ones. * * @param uiEvent Event to send. * @param bundle Optional Bundle to send to UI, usually set to NULL. */ public final void sendUnsolicitedUiEvent(final ServiceUiRequest uiEvent, final Bundle bundle) { if (uiEvent == null) { throw new InvalidParameterException("UiAgent." + "sendUnsolicitedUiEvent() UiEvent cannot be NULL"); } LogUtils.logW("UiAgent.sendUnsolicitedUiEvent() uiEvent[" + uiEvent.name() + "]"); if (mHandler != null) { /* * Send now. */ try { mHandler.sendMessage(mHandler.obtainMessage(uiEvent.ordinal(), bundle)); LogUtils.logV("UiAgent.sendUnsolicitedUiEvent() " + "Sending uiEvent[" + uiEvent + "]"); } catch (NullPointerException e) { LogUtils.logW("UiAgent.sendUnsolicitedUiEvent() Caught a race " + "condition where mHandler was set to NULL after " + "being explicitly checked"); /** Send later anyway. **/ addUiEventToQueue(uiEvent, bundle); } } else { /* * Send later. */ addUiEventToQueue(uiEvent, bundle); } } /*** * Add the given UiEvent and Bundle pair to the send later queue. * * @param uiEvent ServiceUiRequest to queue. * @param bundle Bundle to queue. */ private void addUiEventToQueue(final ServiceUiRequest uiEvent, final Bundle bundle) { if (mUiEventQueue == null || uiEvent.ordinal() < mUiEventQueue.ordinal()) { LogUtils.logV("UiAgent.sendUnsolicitedUiEvent() Sending uiEvent[" + uiEvent.name() + "] later"); mUiEventQueue = uiEvent; mUiBundleQueue = bundle; } else { LogUtils.logV("UiAgent.sendUnsolicitedUiEvent() Ignoring uiEvent[" + uiEvent.name() + "], as highter priority UiEvent[" + mUiEventQueue.name() + "] is already pending"); } } /** * Subscribes a UI Handler to receive unsolicited events. * * @param handler UI handler to receive unsolicited events. * @param localContactId Provide a local contact ID to receive updates for * the given contact only, or set this to -1 to receive updates * for every contact, or set this to NULL not to receive contact * updates. * @param shouldHandleChat TRUE if the Handler expects chat messages. */ public final void subscribe(final Handler handler, final Long localContactId, final boolean shouldHandleChat) { LogUtils.logV("UiAgent.subscribe() handler[" + handler + "] localContactId[" + localContactId + "] chat[" + shouldHandleChat + "]"); if (handler == null) { throw new NullPointerException("UiAgent.subscribe()" + "Handler cannot be NULL"); } mHandler = handler; mLocalContactId = localContactId; mShouldHandleChat = shouldHandleChat; if (mShouldHandleChat) { updateChatNotification(false); } if (mUiEventQueue != null) { LogUtils.logV("UiAgent.subscribe() Send pending uiEvent[" + mUiEventQueue + "]"); mHandler.sendMessage(mHandler.obtainMessage( mUiEventQueue.ordinal(), mUiBundleQueue)); mUiEventQueue = null; mUiBundleQueue = null; } UpgradeStatus upgradeStatus = new VersionCheck( mMainApplication.getApplicationContext(), false).getCachedUpdateStatus(); if (upgradeStatus != null) { sendUnsolicitedUiEvent(ServiceUiRequest.UNSOLICITED_DIALOG_UPGRADE, null); } ConnectionManager.getInstance().notifyOfUiActivity(); } /** * This method ends the UI Handler's subscription. This will have no effect * if a different handler is currently subscribed. * * @param handler - UI handler to no longer receive unsolicited events. */ public final void unsubscribe(final Handler handler) { if (handler == null) { throw new NullPointerException("UiAgent.unsubscribe() Handler" + "cannot be NULL."); } if (handler != mHandler) { LogUtils.logW("UiAgent.unsubscribe() Activity is trying to " + "unsubscribe with a different handler"); } else { mHandler = null; mLocalContactId = -1; mShouldHandleChat = false; } } /** * This method returns the local ID of the contact the HandlerAgent is * tracking. * * @return LocalContactId of the contact the HandlerAgent is tracking */ public final long getLocalContactId() { return mLocalContactId; } /** * Returns TRUE if an Activity is currently listening out for unsolicited * events (i.e. a "Live" activity is currently on screen). * * @return TRUE if any subscriber is listening the presence state/chat * events */ public final boolean isSubscribed() { return mHandler != null; } /** * Returns TRUE if an Activity is currently listening out for unsolicited * events (i.e. a "Live" activity is currently on screen). * * @return TRUE if any subscriber is listening the presence chat events */ public final boolean isSubscribedWithChat() { return mHandler != null && mShouldHandleChat; } /** * This method is called by the Presence engine to notify a subscribed * Activity of updates. * * @param contactId Update an Activity that shows this contact ID only, or - * set this to -1 to send updates relevant to all contacts. + * set this to ALL_USERS to send updates relevant to all contacts. */ public final void updatePresence(final long contactId) { WidgetUtils.kickWidgetUpdateNow(mMainApplication); if (mHandler != null) { if (mLocalContactId == -1 || mLocalContactId == contactId) { mHandler.sendMessage(mHandler.obtainMessage( ServiceUiRequest.UNSOLICITED_PRESENCE.ordinal(), null)); } else { LogUtils.logV("UiAgent.updatePresence() No Activities are " + "interested in contactId[" + contactId + "]"); } } else { LogUtils.logW("UiAgent.updatePresence() No subscribed Activities"); } } /** * <p>Notifies an on screen Chat capable Activity of a relevant update. If the * wrong Activity is on screen, this update will be shown as a Notification.</p> * * <p><b>Please note that this method takes care of notification for adding AND * removing chat message notifications</b></p>! * * @param contactId Update an Activity that shows Chat information for this * localContact ID only. * @param isNewChatMessage True if this is a new chat message that we are notifying * for. False if we are for instance just deleting a notification. */ public final void updateChat(final long contactId, final boolean isNewChatMessage) { if (mHandler != null && mShouldHandleChat && mLocalContactId == contactId) { LogUtils.logV("UiAgent.updateChat() Send message to UI (i.e. " + "update the screen)"); mHandler.sendMessage(mHandler.obtainMessage( ServiceUiRequest.UNSOLICITED_CHAT.ordinal(), null)); /* * Note: Do not update the chat notification at this point, as the * UI must update the database (e.g. mark messages as read) before * calling subscribe() to trigger a refresh. */ } else if (mHandler != null && mShouldHandleChat && mLocalContactId == -1) { LogUtils.logV("UiAgent.updateChat() Send message to UI (i.e. " + "update the screen) and do a noisy notification"); /* * Note: this was added because TimelineListActivity listens to all * localIds (i.e. localContactId = -1) */ mHandler.sendMessage(mHandler.obtainMessage( ServiceUiRequest.UNSOLICITED_CHAT.ordinal(), null)); updateChatNotification(isNewChatMessage); } else { LogUtils.logV("UiAgent.updateChat() Do a noisy notification only"); updateChatNotification(isNewChatMessage); } } /*** * Update the Notification bar with Chat information directly from the * database. * * @param isNewChatMessage True if we have a new chat message and want to * display a noise and notification, false if we for instance just delete a * chat message or update a multiple-user notification silently. * */ private void updateChatNotification(final boolean isNewChatMessage) { mContext.sendBroadcast(new Intent(Intents.NEW_CHAT_RECEIVED).putExtra( ApplicationCache.sIsNewMessage, isNewChatMessage)); } }