com.vodafone360.people.engine.presence
Class PresenceEngine

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

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

Handles the Presence life cycle


Nested Class Summary
 
Nested classes/interfaces inherited from class com.vodafone360.people.engine.BaseEngine
BaseEngine.IEngineEventCallback
 
Field Summary
private static long CHECK_FREQUENCY
          Check every 10 minutes.
private static int IDLE
          This state indicates there are no more pending presence payload information to be processed.
private static int MAX_RETRY_COUNT
          Max attempts to try.
private  boolean mContObsAdded
           
private  DatabaseHelper mDbHelper
           
private  java.util.List<ActivitiesTable.TimelineSummaryItem> mFailedMessagesList
           
private  int mIterations
          Number of pages of presence Updates done.
private  boolean mLoggedIn
          Reconnecting before firing offline state to the handlers.
private  NetworkAgent.AgentState mNetworkAgentState
           
private  long mNextRuntime
           
private  int mRetryNumber
           
private  java.util.Hashtable<java.lang.String,ChatMessage> mSendMessagesHash
           
private  int mState
          The state of the presence Engine.
private  java.util.List<User> mUsers
          The list of Users still to be processed.
private static int NOTIFY_AGENT_PAGE_INTERVAL
          The number of pages after which the HandlerAgent is notified.
private static int UPDATE_PRESENCE_PAGE_SIZE
          The page size i.e the number of presence updates processed at a time.
private static long UPDATE_PRESENCE_TIMEOUT_MILLS
          Timeout between each presence update processing.
private static int UPDATE_PROCESSING_GOING_ON
          This state indicates there are some pending presence payload information to be processed.
 
Fields inherited from class com.vodafone360.people.engine.BaseEngine
mActiveUiRequest, mCurrentTimeout, mEngineId, mEventCallback
 
Constructor Summary
PresenceEngine(BaseEngine.IEngineEventCallback eventCallback, DatabaseHelper databaseHelper)
           
 
Method Summary
private  void addAsContactSyncObserver()
          Add ActivitiesEngine as an observer of the ContactSyncEngine.
private  boolean canRun()
          checks the external conditions which have to be happen before the engine can run
private  void createConversation(ChatMessage msg)
           
private  User getMyAvailabilityStatusFromDatabase()
           
 long getNextRunTime()
          Return the absolute time in milliseconds when the engine needs to run (based on System.currentTimeMillis).
 void getPresenceList()
          Initiate the "get presence list" request sending to server.
private  void handleNewConversationId(Conversation conversation)
           
private  void handlePresenceList(PresenceList presenceList)
           
private  void handlePushEvent(PushEvent event)
           
private  void handleServerError(ServerError srvError)
           
private  void handleServerResponse(java.util.List<BaseDataType> dataTypes)
          This method handles incoming presence status change push events and the whole PresenceList
private  void handleSystemNotification(SystemNotification sn)
           
private  void initSetMyAvailabilityRequest(User myself)
           
 void onContactSyncStateChange(ContactSyncEngine.Mode mode, ContactSyncEngine.State oldState, ContactSyncEngine.State newState)
          Called when the contact sync engine changes state or mode
 void onCreate()
          This will be called immediately after creation.
 void onDestroy()
          This will be called just before the engine is shutdown.
 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)
          Called a contact sync finishes.
protected  void onTimeoutEvent()
          The derived engine implementation must call the processTimeout() function (normally from within the run() implementation), otherwise this will not be called.
protected  void processCommsResponse(ResponseQueue.Response resp)
          The derived engine implementation must call the processCommsInQueue() function (normally from within the run() implementation), otherwise this will not be called.
protected  void processUiRequest(ServiceUiRequest requestId, java.lang.Object data)
          The derived engine implementation must call the processUiQueue() function (normally from within the run() implementation), otherwise this will not be called.
 void run()
          Do some work but anything that takes longer than 1 second must be broken up.
 void sendMessage(long toLocalContactId, java.lang.String body, int networkId)
          This method should be used to send a message to a contact
 void setMyAvailability(java.util.Hashtable<java.lang.String,java.lang.String> myselfPresence)
          Changes the state of the engine.
private  void setNextRuntime()
           
private  void setPresenceOffline()
          Set the Global presence status to offline.
private  void setRunNow()
           
private  void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg)
           
private  boolean uiRequestReady()
          Helper function which returns true if a UI request is waiting on the queue and we are ready to process it.
private  void updateChatDatabase(ChatMessage message, ActivitiesTable.TimelineSummaryItem.Type type)
          Updates the database with the given ChatMessage and Type.
private  void updateMyPresenceInDatabase(User myself)
          Here we update the PresenceTable, and the ContactSummaryTable afterwards the HandlerAgent receives the notification of presence states changes.
private  void updatePresenceDatabase(java.util.List<User> users)
          Here we update the PresenceTable, and the ContactSummaryTable afterwards the HandlerAgent receives the notification of presence states changes.
private  void updatePresenceDatabaseNextPage()
          This API makes the presence updates in pages of 10 with a timeout after each page.
 
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

CHECK_FREQUENCY

private static final long CHECK_FREQUENCY
Check every 10 minutes.

See Also:
Constant Field Values

MAX_RETRY_COUNT

private static final int MAX_RETRY_COUNT
Max attempts to try.

See Also:
Constant Field Values

mLoggedIn

private boolean mLoggedIn
Reconnecting before firing offline state to the handlers.


mNextRuntime

private long mNextRuntime

mNetworkAgentState

private NetworkAgent.AgentState mNetworkAgentState

mDbHelper

private DatabaseHelper mDbHelper

mRetryNumber

private int mRetryNumber

mSendMessagesHash

private final java.util.Hashtable<java.lang.String,ChatMessage> mSendMessagesHash

mFailedMessagesList

private java.util.List<ActivitiesTable.TimelineSummaryItem> mFailedMessagesList

mContObsAdded

private boolean mContObsAdded

mUsers

private java.util.List<User> mUsers
The list of Users still to be processed.


IDLE

private static final int IDLE
This state indicates there are no more pending presence payload information to be processed.

See Also:
Constant Field Values

UPDATE_PROCESSING_GOING_ON

private static final int UPDATE_PROCESSING_GOING_ON
This state indicates there are some pending presence payload information to be processed.

See Also:
Constant Field Values

UPDATE_PRESENCE_TIMEOUT_MILLS

private static final long UPDATE_PRESENCE_TIMEOUT_MILLS
Timeout between each presence update processing.

See Also:
Constant Field Values

UPDATE_PRESENCE_PAGE_SIZE

private static final int UPDATE_PRESENCE_PAGE_SIZE
The page size i.e the number of presence updates processed at a time.

See Also:
Constant Field Values

NOTIFY_AGENT_PAGE_INTERVAL

private static final int NOTIFY_AGENT_PAGE_INTERVAL
The number of pages after which the HandlerAgent is notified.

See Also:
Constant Field Values

mState

private int mState
The state of the presence Engine.


mIterations

private int mIterations
Number of pages of presence Updates done. This is used to control when a notification is sent to the UI.

Constructor Detail

PresenceEngine

public PresenceEngine(BaseEngine.IEngineEventCallback eventCallback,
                      DatabaseHelper databaseHelper)
Parameters:
eventCallback -
databaseHelper -
Method Detail

onCreate

public void onCreate()
Description copied from class: BaseEngine
This will be called immediately after creation.

Specified by:
onCreate in class BaseEngine

onDestroy

public void onDestroy()
Description copied from class: BaseEngine
This will be called just before the engine is shutdown.

Specified by:
onDestroy in class BaseEngine

canRun

private boolean canRun()
checks the external conditions which have to be happen before the engine can run

Returns:
true if everything is ready

getNextRunTime

public long getNextRunTime()
Description copied from class: BaseEngine
Return the absolute time in milliseconds when the engine needs to run (based on System.currentTimeMillis). (Maybe add currentTime in the future to use as the current time, to enable JUnit tests to validate timeout functionality).

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.

run

public void run()
Description copied from class: BaseEngine
Do some work but anything that takes longer than 1 second must be broken up. (Maybe add currentTime as parameter, to enable JUnit tests to validate timeout functionality)

Specified by:
run in class BaseEngine

uiRequestReady

private boolean uiRequestReady()
Helper function which returns true if a UI request is waiting on the queue and we are ready to process it.

Returns:
true if the request can be processed now.

getMyAvailabilityStatusFromDatabase

private User getMyAvailabilityStatusFromDatabase()

setNextRuntime

private void setNextRuntime()

setRunNow

private void setRunNow()

onLoginStateChanged

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

setPresenceOffline

private void setPresenceOffline()
Set the Global presence status to offline.


onRequestComplete

protected void onRequestComplete()
Description copied from class: BaseEngine
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()
Description copied from class: BaseEngine
The derived engine implementation must call the processTimeout() function (normally from within the run() implementation), otherwise this will not be called. This function will be called when a timeout occurs (started by setTimeout and cancelled by clearTimeout). If this function takes longer than 1 second to complete it should be broken up.

Specified by:
onTimeoutEvent in class BaseEngine

processCommsResponse

protected void processCommsResponse(ResponseQueue.Response resp)
Description copied from class: BaseEngine
The derived engine implementation must call the processCommsInQueue() function (normally from within the run() implementation), otherwise this will not be called. This function is called for each Comms response that arrives on the in queue.

Specified by:
processCommsResponse in class BaseEngine
Parameters:
resp - The comms response

showErrorNotification

private void showErrorNotification(ServiceUiRequest errorEvent,
                                   ChatMessage msg)

updatePresenceDatabase

private void updatePresenceDatabase(java.util.List<User> users)
Here we update the PresenceTable, and the ContactSummaryTable afterwards the HandlerAgent receives the notification of presence states changes.

Parameters:
users - List of users that require updating.

updatePresenceDatabaseNextPage

private void 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.


updateChatDatabase

private void updateChatDatabase(ChatMessage message,
                                ActivitiesTable.TimelineSummaryItem.Type type)
Updates the database with the given ChatMessage and Type.

Parameters:
message - ChatMessage.
type - TimelineSummaryItem.Type.

updateMyPresenceInDatabase

private void updateMyPresenceInDatabase(User myself)
Here we update the PresenceTable, and the ContactSummaryTable afterwards the HandlerAgent receives the notification of presence states changes.

Parameters:
users - User that requires updating.

handleServerResponse

private void handleServerResponse(java.util.List<BaseDataType> dataTypes)
This method handles incoming presence status change push events and the whole PresenceList

Parameters:
dataTypes -

handlePresenceList

private void handlePresenceList(PresenceList presenceList)

handleServerError

private void handleServerError(ServerError srvError)

handleNewConversationId

private void handleNewConversationId(Conversation conversation)

handlePushEvent

private void handlePushEvent(PushEvent event)

handleSystemNotification

private void handleSystemNotification(SystemNotification sn)

processUiRequest

protected void processUiRequest(ServiceUiRequest requestId,
                                java.lang.Object data)
Description copied from class: BaseEngine
The derived engine implementation must call the processUiQueue() function (normally from within the run() implementation), otherwise this will not be called. This function is called for each UI request that arrives on the queue. It should start processing the request. If this function takes longer than 1 second to complete, it should be broken up. Once a request is finished the processUiRequest function must be called.

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

getPresenceList

public void getPresenceList()
Initiate the "get presence list" request sending to server. Makes the engine run asap.


initSetMyAvailabilityRequest

private void initSetMyAvailabilityRequest(User myself)

setMyAvailability

public void setMyAvailability(java.util.Hashtable<java.lang.String,java.lang.String> myselfPresence)
Changes the state of the engine. Also displays the login notification if necessary.

Parameters:
accounts -

createConversation

private void createConversation(ChatMessage msg)

sendMessage

public void sendMessage(long toLocalContactId,
                        java.lang.String body,
                        int networkId)
This method should be used to send a message to a contact

Parameters:
tos - - tlocalContactId of ContactSummary items the message is intended for. Current protocol version only supports a single recipient.
body - the message text

addAsContactSyncObserver

private void addAsContactSyncObserver()
Add ActivitiesEngine as an observer of the ContactSyncEngine. Need to be able to obtain a handle to the EngineManager and a handle to the ContactSyncEngine.


onContactSyncStateChange

public void onContactSyncStateChange(ContactSyncEngine.Mode mode,
                                     ContactSyncEngine.State oldState,
                                     ContactSyncEngine.State newState)
Description copied from interface: ContactSyncEngine.IContactSyncObserver
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

onProgressEvent

public void onProgressEvent(ContactSyncEngine.State currentState,
                            int percent)
Description copied from interface: ContactSyncEngine.IContactSyncObserver
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

onSyncComplete

public void onSyncComplete(ServiceStatus status)
Description copied from interface: ContactSyncEngine.IContactSyncObserver
Called a contact sync finishes.

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


JavaDoc