com.vodafone360.people.engine.activities
Class ActivitiesEngine

java.lang.Object
  extended by com.vodafone360.people.engine.BaseEngine
      extended by com.vodafone360.people.engine.activities.ActivitiesEngine
All Implemented Interfaces:
ContactSyncEngine.IContactSyncObserver, LoginEngine.ILoginEventsListener

public class ActivitiesEngine
extends BaseEngine
implements ContactSyncEngine.IContactSyncObserver, LoginEngine.ILoginEventsListener

Engine response for handling of Activities (i.e Timeline and Status events). It also interfaces to the native Call and Message logs to allow these events to be handled within the People Client's Timeline.


Nested Class Summary
(package private) static interface ActivitiesEngine.ISyncHelper
          Interface for Native call and message log sync classes.
private static class ActivitiesEngine.State
          Definitions of Activities engines states; IDLE - engine is inactive FETCH_STATUSES_FIRST_TIME: 1st time sync of statuses, FETCH_CALLOG_FIRST_TIME: first time sync of phone calls, UPDATE_STATUSES: updating statuses from server (user has pressed the "refresh button" or push event's triggered the sync), UPDATE_CALLOG_FROM_NATIVE: new timeline item appeared on the phone, FETCH_OLDER_CALLLOG_FROM_NATIVE_DB: user has pressed "more timelines" button, FETCH_SMS_FROM_NATIVE_DB: fetching SMS/MMS
 
Nested classes/interfaces inherited from class com.vodafone360.people.engine.BaseEngine
BaseEngine.IEngineEventCallback
 
Field Summary
private static java.lang.String ACTIVITY_ITEM
           
static java.lang.String FETCHING_OLDER_STATUSES
           
static java.lang.String FETCHING_OLDER_TIMELINE
           
private static java.lang.String FILTER_GT
           
private static java.lang.String FILTER_LIDS
          Identifier for filtering against local ids (LIDs)
private static java.lang.String FILTER_NUM
          maximum number of identities fetched at the same time
private static java.lang.String FILTER_SORT
           
private static java.lang.String FILTER_STATUS
           
private static java.lang.String FILTER_TRUE
           
private static java.lang.String FILTER_UPDATED
          filter definitions
private static java.lang.String FILTER_UPDATED_REV
           
private  java.util.Hashtable<java.lang.Integer,java.lang.String> mActiveRequests
           
private  ActivitiesEngine.ISyncHelper mActiveSyncHelper
          current processor (fetching timelines), is null if no action for timelines is taken
private  Context mContext
           
private  DatabaseHelper mDb
           
private  long mLastStatusUpdated
          Timestamp for most recent Status event update
private  java.lang.Object mMutex
          mutex for thread synchronization
private  long mOldestStatusUpdated
          Timestamp for oldest Status event update
private  java.lang.Object mQueueMutex
           
private  boolean mRequestActivitiesRequired
           
private static long MS_IN_SECOND
           
private  ActivitiesEngine.State mState
          engine's current state
private  TimelineEventWatcher mTimelineEventWatcher
          Instance of TimelineEventWatcher which listens for native call and message logs events that ActivitiesEngine should sync.
private  boolean mTimelinesUpdated
           
private static long READ_TIMELINES_TIMEOUT_MILLS
           
private static long STATUSES_SYNC_TIMEOUT_MILLIS
           
static java.lang.String UPDATING_STATUSES
          below are the constants to communicate the engine state states to UI: 3 buttons (update statuses, load older statuses, older timelines)
private static long WEEK_OLD_MILLIS
           
 
Fields inherited from class com.vodafone360.people.engine.BaseEngine
mActiveUiRequest, mCurrentTimeout, mEngineId, mEventCallback
 
Constructor Summary
ActivitiesEngine(Context context, BaseEngine.IEngineEventCallback eventCallback, DatabaseHelper db)
          Constructor
 
Method Summary
protected  void addGetNewPhonesCallsRequest()
          This method adds a request to get latest timelines.
protected  void addGetNewSMSRequest()
          This method adds a request to get latest timelines.
 void addGetOlderStatusesRequest()
          This method adds a request to start sync of older statuses from Now+ server.
 void addOlderTimelinesRequest()
          This method adds a request to get older timelines.
 void addStatusesSyncRequest()
          This method adds a request to start sync of the most recent statuses from Now+ server.
private  java.util.Map<java.lang.String,java.util.List<java.lang.String>> applyActivitiesFilter(boolean refresh)
           
private  boolean checkConnectivity()
          Get current connectivity state from the NetworkAgent.
private  void cleanDatabase()
          Trigger the ActivitiesTable cleanup when the Engine is in "CLEANUP_DATABASE" state.
private  void dequeueRequest(int requestId)
          This method stores removes a busy state of engine and males the change available to UI through the ApplicationCache.
private  void enqueueRequest(int requestId, java.lang.String requestType)
          This method stores the current busy state of engine in ApplicationCache to make it available to UI.
private  java.lang.Long findFirstStatusUpdateTime(java.util.ArrayList<ActivityItem> activityList)
          Find oldest item in list of Activities retrieved from server.
private  java.lang.Long findLastStatusUpdateTime(java.util.ArrayList<ActivityItem> activityList)
           
private  void fireNewState(ServiceUiRequest request)
          This method fires states change of an engine to UI (between "busy" and IDLE).
 long getNextRunTime()
          Return next run time for ActivitiesEngine.
private  void handleGetActivitiesResponse(java.util.List<BaseDataType> data)
          Handle GetActivities response message received from Server
private  void handlePushRequest(PushMessageTypes evt)
          Handle Status or Timeline Activity change Push message
private  boolean isContactSyncReady()
          This method is necessary for the tests.
 boolean isTimelinesUpdated()
          This method returns if the timelines have been updated with the previous "show more" call or push message.
private  void newState(ActivitiesEngine.State newState)
          Changes the state of the engine.
 void onContactSyncStateChange(ContactSyncEngine.Mode mode, ContactSyncEngine.State oldState, ContactSyncEngine.State newState)
          Called when the contact sync engine changes state or mode
 void onCreate()
          onCreate.
 void onDestroy()
          On destruction of ActivitiesEngine stop the timeline event watcher.
 void onLoginStateChanged(boolean loggedIn)
           
 void onProgressEvent(ContactSyncEngine.State currentState, int percent)
          Called to update interested parties on contact sync progress.
protected  void onRequestComplete()
          This function must be implemented in the derived engine implementation.
 void onSyncComplete(ServiceStatus status)
          Receive notification from ContactSyncEngine that a Contact sync has completed.
protected  void onSyncHelperComplete(ServiceStatus status)
          Function called when helper classes ends their work.
protected  void onTimeoutEvent()
          Drive state machine for Activities sync.
protected  void processCommsResponse(ResponseQueue.Response resp)
          Handle response received from transport layer (via EngineManager)
protected  void processUiRequest(ServiceUiRequest requestId, java.lang.Object data)
          Handle an outstanding UI request.
private  void removeDuplicates(java.util.ArrayList<ActivityItem> activityList)
          TODO: investigate why duplicates here can appear. this method might be not necessary.
private  void requestStatusesFromServer(boolean refresh)
          Request Activities (Status/Timeline) events from Server.
 void run()
          ActivitiesEngine run implementation Processes a response if one is available, Processes any events in engine's UI queue.
 void setTimelinesUpdated(boolean timelinesUpdated)
          This method sets the state - if the timelines have been updated or not.
private  void startCallLogSync(boolean refresh)
          Start sync of call log from native call log data base
private  ServiceStatus updateDatabase(java.util.ArrayList<ActivityItem> activityList)
           
private  void updateLatestStatusUpdateTime()
           
private  void updateOldestStatusUpdateTime()
           
 
Methods inherited from class com.vodafone360.people.engine.BaseEngine
addUiRequestToQueue, clearTimeout, completeUiRequest, completeUiRequest, deactivateEngine, emptyUiRequestQueue, engineId, genericHandleResponseType, getCurrentTimeout, isCommsResponseOutstanding, isDeactivated, isUiRequestOutstanding, onCommsInMessage, onReset, processCommsInQueue, processTimeout, processUiQueue, setReqId, setTimeout
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

UPDATING_STATUSES

public static final java.lang.String UPDATING_STATUSES
below are the constants to communicate the engine state states to UI: 3 buttons (update statuses, load older statuses, older timelines)

See Also:
Constant Field Values

FETCHING_OLDER_STATUSES

public static final java.lang.String FETCHING_OLDER_STATUSES
See Also:
Constant Field Values

FETCHING_OLDER_TIMELINE

public static final java.lang.String FETCHING_OLDER_TIMELINE
See Also:
Constant Field Values

FILTER_UPDATED

private static final java.lang.String FILTER_UPDATED
filter definitions

See Also:
Constant Field Values

FILTER_GT

private static final java.lang.String FILTER_GT
See Also:
Constant Field Values

FILTER_LIDS

private static final java.lang.String FILTER_LIDS
Identifier for filtering against local ids (LIDs)

See Also:
Constant Field Values

FILTER_NUM

private static final java.lang.String FILTER_NUM
maximum number of identities fetched at the same time

See Also:
Constant Field Values

FILTER_SORT

private static final java.lang.String FILTER_SORT
See Also:
Constant Field Values

FILTER_UPDATED_REV

private static final java.lang.String FILTER_UPDATED_REV
See Also:
Constant Field Values

FILTER_STATUS

private static final java.lang.String FILTER_STATUS
See Also:
Constant Field Values

FILTER_TRUE

private static final java.lang.String FILTER_TRUE
See Also:
Constant Field Values

MS_IN_SECOND

private static final long MS_IN_SECOND
See Also:
Constant Field Values

STATUSES_SYNC_TIMEOUT_MILLIS

private static final long STATUSES_SYNC_TIMEOUT_MILLIS
See Also:
Constant Field Values

READ_TIMELINES_TIMEOUT_MILLS

private static final long READ_TIMELINES_TIMEOUT_MILLS
See Also:
Constant Field Values

WEEK_OLD_MILLIS

private static final long WEEK_OLD_MILLIS
See Also:
Constant Field Values

ACTIVITY_ITEM

private static final java.lang.String ACTIVITY_ITEM
See Also:
Constant Field Values

mLastStatusUpdated

private long mLastStatusUpdated
Timestamp for most recent Status event update


mOldestStatusUpdated

private long mOldestStatusUpdated
Timestamp for oldest Status event update


mContext

private Context mContext

mState

private ActivitiesEngine.State mState
engine's current state


mRequestActivitiesRequired

private boolean mRequestActivitiesRequired

mActiveRequests

private final java.util.Hashtable<java.lang.Integer,java.lang.String> mActiveRequests

mTimelineEventWatcher

private TimelineEventWatcher mTimelineEventWatcher
Instance of TimelineEventWatcher which listens for native call and message logs events that ActivitiesEngine should sync.


mDb

private DatabaseHelper mDb

mQueueMutex

private final java.lang.Object mQueueMutex

mTimelinesUpdated

private boolean mTimelinesUpdated

mActiveSyncHelper

private ActivitiesEngine.ISyncHelper mActiveSyncHelper
current processor (fetching timelines), is null if no action for timelines is taken


mMutex

private final java.lang.Object mMutex
mutex for thread synchronization

Constructor Detail

ActivitiesEngine

public ActivitiesEngine(Context context,
                        BaseEngine.IEngineEventCallback eventCallback,
                        DatabaseHelper db)
Constructor

Parameters:
context - - valid context
eventCallback - - callback object
db - - DatabaseHepler object
Method Detail

getNextRunTime

public long getNextRunTime()
Return next run time for ActivitiesEngine. Determined by whether we have a request we wish to issue, or there is a response that needs processing.

Specified by:
getNextRunTime in class BaseEngine
Returns:
-1 never needs to run, 0 needs to run as soon as possible, CurrentTime + 60000 to run in 1 minute, etc.

onCreate

public void onCreate()
onCreate. Instruct the timeline event watcher to start watching for native events the Activities engine may need to handle (call and message events).

Specified by:
onCreate in class BaseEngine

onDestroy

public void onDestroy()
On destruction of ActivitiesEngine stop the timeline event watcher.

Specified by:
onDestroy in class BaseEngine

onRequestComplete

protected void onRequestComplete()
This function must be implemented in the derived engine implementation. It can do any post-request complete cleanup.

Specified by:
onRequestComplete in class BaseEngine

onTimeoutEvent

protected void onTimeoutEvent()
Drive state machine for Activities sync. If we are currently fetching native events run the appropriated ISyncHelper. Otherwise request retrieval of Activities from Server.

Specified by:
onTimeoutEvent in class BaseEngine

processCommsResponse

protected void processCommsResponse(ResponseQueue.Response resp)
Handle response received from transport layer (via EngineManager)

Specified by:
processCommsResponse in class BaseEngine
Parameters:
resp - Received Response item either a Status/Timeline related push message or a response to a get activities request.

processUiRequest

protected void processUiRequest(ServiceUiRequest requestId,
                                java.lang.Object data)
Handle an outstanding UI request.

Specified by:
processUiRequest in class BaseEngine
Parameters:
requestId - The UI request ID
data - Request data (object type is request specific)

run

public void run()
ActivitiesEngine run implementation Processes a response if one is available, Processes any events in engine's UI queue. Issues get-activities request to server as part of sync.

Specified by:
run in class BaseEngine

startCallLogSync

private void startCallLogSync(boolean refresh)
Start sync of call log from native call log data base


isContactSyncReady

private boolean isContactSyncReady()
This method is necessary for the tests. It catches the InvalidParameterException coming from EngineManager.getInstance(), when the instance is null

Returns:
boolean - TRUE if ContactSyncEngine is not null

requestStatusesFromServer

private void requestStatusesFromServer(boolean refresh)
Request Activities (Status/Timeline) events from Server.

Parameters:
refresh - boolean - is true when fetching latest statuses, false - when older

applyActivitiesFilter

private java.util.Map<java.lang.String,java.util.List<java.lang.String>> applyActivitiesFilter(boolean refresh)

cleanDatabase

private void cleanDatabase()
Trigger the ActivitiesTable cleanup when the Engine is in "CLEANUP_DATABASE" state.


handlePushRequest

private void handlePushRequest(PushMessageTypes evt)
Handle Status or Timeline Activity change Push message

Parameters:
evt - Push message type (Status change or Timeline change).

handleGetActivitiesResponse

private void handleGetActivitiesResponse(java.util.List<BaseDataType> data)
Handle GetActivities response message received from Server

Parameters:
reqId - Request ID contained in response. This should match an ID of a request we have issued to the Server.
data - List array of ActivityItem items returned from Server.

updateDatabase

private ServiceStatus updateDatabase(java.util.ArrayList<ActivityItem> activityList)

updateLatestStatusUpdateTime

private void updateLatestStatusUpdateTime()

updateOldestStatusUpdateTime

private void updateOldestStatusUpdateTime()

findLastStatusUpdateTime

private java.lang.Long findLastStatusUpdateTime(java.util.ArrayList<ActivityItem> activityList)

findFirstStatusUpdateTime

private java.lang.Long findFirstStatusUpdateTime(java.util.ArrayList<ActivityItem> activityList)
Find oldest item in list of Activities retrieved from server.

Returns:
Time-stamp of oldest event.

removeDuplicates

private void removeDuplicates(java.util.ArrayList<ActivityItem> activityList)
TODO: investigate why duplicates here can appear. this method might be not necessary. Remove Activities from list of Activities with Activity IDS matching ones we have already retrieved (i.e .duplicates).


onContactSyncStateChange

public void onContactSyncStateChange(ContactSyncEngine.Mode mode,
                                     ContactSyncEngine.State oldState,
                                     ContactSyncEngine.State newState)
Called when the contact sync engine changes state or mode

Specified by:
onContactSyncStateChange in interface ContactSyncEngine.IContactSyncObserver
Parameters:
mode - Current mode
oldState - Previous state
newState - New state

onSyncComplete

public void onSyncComplete(ServiceStatus status)
Receive notification from ContactSyncEngine that a Contact sync has completed. Start Activity sync if we have not previously synced.

Specified by:
onSyncComplete in interface ContactSyncEngine.IContactSyncObserver
Parameters:
status - SUCCESS if the sync was successful, a suitable error code otherwise.

onProgressEvent

public void onProgressEvent(ContactSyncEngine.State currentState,
                            int percent)
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.

Specified by:
onProgressEvent in interface ContactSyncEngine.IContactSyncObserver
Parameters:
currentState - What the contact sync engine is currently doing
percent - Percentage complete for the current task

checkConnectivity

private boolean checkConnectivity()
Get current connectivity state from the NetworkAgent. If not connected completed UI request with COMMs error.

Returns:
true NetworkAgent reports we are connected, false otherwise.

onSyncHelperComplete

protected void onSyncHelperComplete(ServiceStatus status)
Function called when helper classes ends their work. Currently supported helpers are FetchCallLogEvents and FetchSmsLogEvents

Parameters:
status - - ServiceStatus of completed operation.

addGetNewPhonesCallsRequest

protected void addGetNewPhonesCallsRequest()
This method adds a request to get latest timelines.


addGetNewSMSRequest

protected void addGetNewSMSRequest()
This method adds a request to get latest timelines.


addOlderTimelinesRequest

public void addOlderTimelinesRequest()
This method adds a request to get older timelines.


addStatusesSyncRequest

public void addStatusesSyncRequest()
This method adds a request to start sync of the most recent statuses from Now+ server.


addGetOlderStatusesRequest

public void addGetOlderStatusesRequest()
This method adds a request to start sync of older statuses from Now+ server.


newState

private void newState(ActivitiesEngine.State newState)
Changes the state of the engine.

Parameters:
newState - The new state

fireNewState

private void fireNewState(ServiceUiRequest request)
This method fires states change of an engine to UI (between "busy" and IDLE). This method is normally called after the new state has been changed and published to ApplicationCache. The UI should refer to ApplicationCache when processing this new ServiceRequest

Parameters:
request - ServiceUIRequest UPDATING_UI or UPDATING_UI_FINISHED

enqueueRequest

private void enqueueRequest(int requestId,
                            java.lang.String requestType)
This method stores the current busy state of engine in ApplicationCache to make it available to UI. This method is normally called before setting new state of the engine.

Parameters:
requestId - int - the request Id for network communications, or the ServiceUIRequest ordinal for fetching/updating timelines
requestType - one of UPDATING_STATUSES, FETCHING_OLDER_STATUSES, FETCHING_OLDER_TIMELINE

dequeueRequest

private void dequeueRequest(int requestId)
This method stores removes a busy state of engine and males the change available to UI through the ApplicationCache. This method is normally called before setting new state of the engine.

Parameters:
requestId - int - the request Id for network communications, or the ServiceUIRequest ordinal for fetching/updating timelines
requestType - one of UPDATING_STATUSES, FETCHING_OLDER_STATUSES, FETCHING_OLDER_TIMELINE

onLoginStateChanged

public void onLoginStateChanged(boolean loggedIn)
Specified by:
onLoginStateChanged in interface LoginEngine.ILoginEventsListener

isTimelinesUpdated

public boolean isTimelinesUpdated()
This method returns if the timelines have been updated with the previous "show more" call or push message.

Returns:
boolean TRUE if they timelines have been updated with the previous "show more" call or push message.

setTimelinesUpdated

public void setTimelinesUpdated(boolean timelinesUpdated)
This method sets the state - if the timelines have been updated or not.

Parameters:
timelinesUpdated - boolean


JavaDoc