repo
string
commit
string
message
string
diff
string
360/360-Engine-for-Android
02b9dc3ef06a5c85c2ee2f46a3e08ac2e3737ca0
Fixing up the broken code caused by previous failed merge
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index c971b96..fe5bfc6 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -28,768 +28,765 @@ 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 * * @return true if everything is ready */ private boolean canRun() { 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; } /** * 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()) { 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); } @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()) { 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()) { 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(((OnlineStatus)data).toString()); + Presence.setMyAvailability((Hashtable<String,String>)data); break; - case SET_MY_AVAILABILITY_FOR_COMMUNITY: - Presence.setMyAvailabilityForCommunity(); - 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()) { 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); } } } public void onConnectionStateChanged(int state) { if (mLoggedIn && canRun()) { 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/ServiceUiRequest.java b/src/com/vodafone360/people/service/ServiceUiRequest.java index caf24d7..3221220 100644 --- a/src/com/vodafone360/people/service/ServiceUiRequest.java +++ b/src/com/vodafone360/people/service/ServiceUiRequest.java @@ -1,267 +1,263 @@ /* * 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, - /** - * Request to set the presence availability status for a single community - */ - SET_MY_AVAILABILITY_FOR_COMMUNITY, /** 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, /* * 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/io/api/Presence.java b/src/com/vodafone360/people/service/io/api/Presence.java index 012f9fc..5dbe2d9 100644 --- a/src/com/vodafone360/people/service/io/api/Presence.java +++ b/src/com/vodafone360/people/service/io/api/Presence.java @@ -1,139 +1,110 @@ /* * 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; } 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(); } - - /** - * 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(); - } - - public static void setMyAvailabilityForCommunity() { - if (LoginEngine.getSession() == null) { - LogUtils.logE("Presence.setMyAvailabilityForCommunity() No session, so return"); - return; - } - } }
360/360-Engine-for-Android
e186e561e305d690c1056142b7288bb7cb0b24cd
fixed broken unit tests
diff --git a/tests/src/com/vodafone360/people/tests/datatypes/NowPlusDatatypesTests.java b/tests/src/com/vodafone360/people/tests/datatypes/NowPlusDatatypesTests.java index 511470c..d9c78b1 100644 --- a/tests/src/com/vodafone360/people/tests/datatypes/NowPlusDatatypesTests.java +++ b/tests/src/com/vodafone360/people/tests/datatypes/NowPlusDatatypesTests.java @@ -1,425 +1,426 @@ /* * 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.datatypes; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Vector; import com.vodafone360.people.datatypes.ActivityContact; +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.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.ItemList; import com.vodafone360.people.datatypes.PublicKeyDetails; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.datatypes.UserProfile; import com.vodafone360.people.datatypes.IdentityCapability.CapabilityID; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.io.rpg.RpgPushMessage; import android.test.AndroidTestCase; public class NowPlusDatatypesTests extends AndroidTestCase { public void testActivityContact() { ActivityContact input = new ActivityContact(); input.mAddress = "foo"; input.mAvatarUrl = "foo"; input.mContactId = 1L; input.mName = "bar"; input.mNetwork = "mob"; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("address", input.mAddress); hash.put("avatarurl", input.mAvatarUrl); hash.put("contactid", input.mContactId); hash.put("name", input.mName); hash.put("network", input.mNetwork); ActivityContact output = ActivityContact.createFromHashTable(hash); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mAddress, output.mAddress); assertEquals(input.mAvatarUrl, output.mAvatarUrl); assertEquals(input.mContactId, output.mContactId); assertEquals(input.mName, output.mName); assertEquals(input.mNetwork, output.mNetwork); } public void testContactChanges() { List<Contact> contacts = new ArrayList<Contact>(); long currentServerVersion = 1; long versionAnchor = 2; int numberOfPages = 3; long serverRevisionBefore = 4; long serverRevisionAfter = 5; Hashtable<String, Object> hashUserProfile = new Hashtable<String, Object>(); ContactChanges input = new ContactChanges(); input.mContacts = contacts; input.mCurrentServerVersion = ((Long) currentServerVersion).intValue(); input.mVersionAnchor = ((Long) versionAnchor).intValue(); input.mNumberOfPages = numberOfPages; input.mServerRevisionBefore = ((Long) serverRevisionBefore).intValue(); input.mServerRevisionAfter = ((Long) serverRevisionAfter).intValue(); input.mUserProfile = UserProfile.createFromHashtable(hashUserProfile); Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("contact", contacts); hash.put("currentserverrevision", currentServerVersion); hash.put("serverrevisionanchor", versionAnchor); hash.put("numpages", numberOfPages); hash.put("serverrevisionbefore", serverRevisionBefore); hash.put("serverrevisionafter", serverRevisionAfter); hash.put("userprofile", hashUserProfile); ContactChanges helper = new ContactChanges(); ContactChanges output = helper.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mContacts, output.mContacts); assertEquals(input.mCurrentServerVersion, output.mCurrentServerVersion); assertEquals(input.mNumberOfPages, output.mNumberOfPages); assertEquals(input.mServerRevisionBefore, output.mServerRevisionBefore); assertEquals(input.mServerRevisionAfter, output.mServerRevisionAfter); } public void testContactDetailDeletion() { long serverVersionBefore = 1; long serverVersionAfter = 2; long contactId = 3; ContactDetailDeletion input = new ContactDetailDeletion(); input.mServerVersionBefore = ((Long) serverVersionBefore).intValue(); input.mServerVersionAfter = ((Long) serverVersionAfter).intValue(); input.mContactId = ((Long) contactId).intValue(); Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("serverrevisionbefore", serverVersionBefore); hash.put("serverrevisionafter", serverVersionAfter); hash.put("contactid", contactId); ContactDetailDeletion helper = new ContactDetailDeletion(); ContactDetailDeletion output = helper.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mServerVersionBefore, output.mServerVersionBefore); assertEquals(input.mServerVersionAfter, output.mServerVersionAfter); assertEquals(input.mContactId, output.mContactId); } public void testContactListResponse() { long serverRevisionBefore = 1; long serverRevisionAfter = 2; List<Integer> contactIdList = new ArrayList<Integer>(); Integer contactId = 3; ContactListResponse input = new ContactListResponse(); input.mServerRevisionBefore = ((Long) serverRevisionBefore).intValue(); input.mServerRevisionAfter = ((Long) serverRevisionAfter).intValue(); input.mContactIdList = contactIdList; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("serverrevisionbefore", serverRevisionBefore); hash.put("serverrevisionafter", serverRevisionAfter); hash.put("contactidlist", contactIdList); hash.put("contactid", contactId); ContactListResponse helper = new ContactListResponse(); ContactListResponse output = helper.createFromHashTable(hash); // createFromHashTable should be static input.mContactIdList.add(contactId); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mServerRevisionBefore, output.mServerRevisionBefore); assertEquals(input.mServerRevisionAfter, output.mServerRevisionAfter); assertEquals(input.mContactIdList, output.mContactIdList); } public void testGroupItem() { int groupType = 1; boolean isReadOnly = true; boolean requiresLocalisation = true; boolean isSystemGroup = true; boolean isSmartGroup = true; long id = 3; long userId = 4; String name = "foo"; GroupItem input = new GroupItem(); input.mGroupType = (Integer) groupType; input.mIsReadOnly = (Boolean) isReadOnly; input.mRequiresLocalisation = (Boolean) requiresLocalisation; input.mIsSystemGroup = (Boolean) isSystemGroup; input.mIsSmartGroup = (Boolean) isSmartGroup; input.mId = (Long) id; input.mUserId = (Long) userId; input.mName = name; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("grouptype", groupType); hash.put("isreadonly", isReadOnly); hash.put("requireslocalisation", requiresLocalisation); hash.put("issystemgroup", isSystemGroup); hash.put("issmartgroup", isSmartGroup); hash.put("id", id); hash.put("userid", userId); hash.put("name", name); GroupItem helper = new GroupItem(); GroupItem output = helper.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mGroupType, output.mGroupType); assertEquals(input.mIsReadOnly, output.mIsReadOnly); assertEquals(input.mRequiresLocalisation, output.mRequiresLocalisation); assertEquals(input.mIsSystemGroup, output.mIsSystemGroup); assertEquals(input.mIsSmartGroup, output.mIsSmartGroup); assertEquals(input.mId, output.mId); assertEquals(input.mUserId, output.mUserId); assertEquals(input.mName, output.mName); } public void testIdentityCapability() { IdentityCapability input = new IdentityCapability(); input.mCapability = CapabilityID.share_media; input.mDescription = "des"; input.mName = "name"; input.mValue = true; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("capabilityid", input.mCapability.name()); hash.put("description", input.mDescription); hash.put("name", input.mName); hash.put("value", input.mValue); IdentityCapability helper = new IdentityCapability(); IdentityCapability output = helper.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.describeContents(), output.describeContents()); assertEquals(input.mCapability, output.mCapability); assertEquals(input.mDescription, output.mDescription); assertEquals(input.mName, output.mName); assertEquals(input.mValue, output.mValue); } public void testIdentity() { Identity input = new Identity(); input.mPluginId = "pluginid"; input.mNetwork = "network"; input.mIdentityId = "identityId"; input.mDisplayName = "displayname"; input.mCreated = new Long(12); input.mUpdated = new Long(23); input.mActive = true; input.mAuthType = "none"; input.mIdentityType = "chat"; input.mUserId = new Integer(1234); input.mUserName = "bob"; input.mCountryList = new ArrayList<String>(); String urlString = "http://www.mobica.com/"; try { input.mNetworkUrl = new URL(urlString); } catch (MalformedURLException e) { input.mNetworkUrl = null; } Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("pluginid", input.mPluginId); hash.put("network", input.mNetwork); hash.put("identityid", input.mIdentityId); hash.put("displayname", input.mDisplayName); hash.put("networkurl", urlString); hash.put("created", input.mCreated); hash.put("updated", input.mUpdated); hash.put("active", true); hash.put("authtype",input.mAuthType); hash.put("identitytype",input.mIdentityType); hash.put("userid",new Long(1234)); hash.put("username",input.mUserName); hash.put("countrylist",input.mCountryList); Identity helper = new Identity(); Identity output = helper.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertTrue(input.isSameAs(output)); } public void testItemList() { ItemList groupPriv = new ItemList(ItemList.Type.group_privacy); int groupType = 1; boolean isReadOnly = true; boolean requiresLocalisation = true; boolean isSystemGroup = true; boolean isSmartGroup = true; long id = 3; long userId = 4; String name = "foo"; Hashtable<String, Object> hashGroup = new Hashtable<String, Object>(); hashGroup.put("grouptype", groupType); hashGroup.put("isreadonly", isReadOnly); hashGroup.put("requireslocalisation", requiresLocalisation); hashGroup.put("issystemgroup", isSystemGroup); hashGroup.put("issmartgroup", isSmartGroup); hashGroup.put("id", id); hashGroup.put("userid", userId); hashGroup.put("name", name); Vector<Hashtable<String, Object>> vect = new Vector<Hashtable<String, Object>>(); vect.add(hashGroup); Hashtable<String, Object> hashItemListGroup = new Hashtable<String, Object>(); hashItemListGroup.put("itemlist", vect); groupPriv.populateFromHashtable(hashItemListGroup); GroupItem helper = new GroupItem(); GroupItem input = helper.createFromHashtable(hashGroup); GroupItem output = (GroupItem) groupPriv.mItemList.get(0); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mGroupType, output.mGroupType); assertEquals(input.mIsReadOnly, output.mIsReadOnly); assertEquals(input.mRequiresLocalisation, output.mRequiresLocalisation); assertEquals(input.mIsSystemGroup, output.mIsSystemGroup); assertEquals(input.mIsSmartGroup, output.mIsSmartGroup); assertEquals(input.mId, output.mId); assertEquals(input.mUserId, output.mUserId); assertEquals(input.mName, output.mName); } public void testPublicKeyDetails() { byte[] modulo = new byte[] {0, 0}; byte[] exponential = new byte[] {0, 1}; byte[] key = new byte[] {1, 1}; String keyBase64 = "64"; PublicKeyDetails input = new PublicKeyDetails(); input.mModulus = modulo; input.mExponential = exponential; input.mKeyX509 = key; input.mKeyBase64 = keyBase64; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("modulo", modulo); hash.put("exponential", exponential); hash.put("key", key); hash.put("keybase64", keyBase64); PublicKeyDetails output = PublicKeyDetails.createFromHashtable(hash); assertEquals(input.describeContents(), output.describeContents()); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mModulus, output.mModulus); assertEquals(input.mExponential, output.mExponential); assertEquals(input.mKeyX509, output.mKeyX509); assertEquals(input.mKeyBase64, output.mKeyBase64); } public void testCreatePushEvent() { RpgPushMessage msg = new RpgPushMessage(); msg.mType = PushMessageTypes.CONTACTS_CHANGE; EngineId engId = EngineId.ACTIVITIES_ENGINE; PushEvent input = (PushEvent) PushEvent.createPushEvent(msg, engId); - assertEquals("PushEvent", input.name()); + assertEquals(BaseDataType.PUSH_EVENT_DATA_TYPE, input.getType()); assertEquals(msg.mType, input.mMessageType); assertEquals(engId, input.mEngineId); } public void testStatusMsg() { boolean status = true; boolean dryRun = true; StatusMsg input = new StatusMsg(); input.mStatus = (Boolean) status; input.mDryRun = (Boolean) dryRun; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("status", status); hash.put("dryrun", dryRun); StatusMsg helper = new StatusMsg(); StatusMsg output = helper.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(BaseDataType.STATUS_MSG_DATA_TYPE, output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mStatus, output.mStatus); assertEquals(input.mDryRun, output.mDryRun); } public void testUserProfile() { UserProfile input = new UserProfile(); input.userID = 50L; input.aboutMe = "newAboutMe"; input.contactID = 10L; input.gender = 1; input.profilePath = "foo"; input.updated = 2L; ContactDetail contactDetail = new ContactDetail(); contactDetail.value = "00000000"; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("userid", input.userID); hash.put("aboutme", input.aboutMe); hash.put("contactid", input.contactID); hash.put("gender", input.gender); hash.put("profilepath", input.profilePath); hash.put("updated", input.updated); UserProfile output = UserProfile.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(BaseDataType.USER_PROFILE_DATA_TYPE, output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.userID, output.userID); assertEquals(input.aboutMe, output.aboutMe); assertEquals(input.contactID, output.contactID); assertEquals(input.gender, output.gender); assertEquals(input.profilePath, output.profilePath); assertEquals(input.updated, output.updated); } } diff --git a/tests/src/com/vodafone360/people/tests/engine/ActivitiesEngineTest.java b/tests/src/com/vodafone360/people/tests/engine/ActivitiesEngineTest.java index 070c543..0d3e910 100644 --- a/tests/src/com/vodafone360/people/tests/engine/ActivitiesEngineTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/ActivitiesEngineTest.java @@ -1,504 +1,502 @@ /* * 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.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(0, data, mEng.engineId()); 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(reqId, data, engine); 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(); data.add(item2); respQueue.addToResponseQueue(reqId, data, engine); 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"; 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(); for (int i = 0; i < 23; i++) { item4.mPreview.putChar((char)i); } item4.mPreviewMime = "jepg"; item4.mPreviewUrl = "storeurl"; item4.mStore = "google"; item4.mVisibilityFlags = 0; data.add(item4); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; case GET_ACTIVITIES_SERVER_ERR: - ServerError err = new ServerError(); - err.errorType = "Catastrophe"; - err.errorValue = "Fail"; + ServerError err = new ServerError("Catastrophe"); + err.errorDescription = "Fail"; data.add(err); respQueue.addToResponseQueue(reqId, data, engine); 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(reqId, data, engine); mEng.onCommsInMessage(); break; case SET_STATUS: Identity id3 = new Identity(); data.add(id3); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; case ON_SYNC_COMPLETE: - ServerError err2 = new ServerError(); - err2.errorType = "Catastrophe"; - err2.errorValue = "Fail"; + ServerError err2 = new ServerError("Catastrophe"); + err2.errorDescription = "Fail"; data.add(err2); respQueue.addToResponseQueue(reqId, data, engine); 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/EngineTestFramework.java b/tests/src/com/vodafone360/people/tests/engine/EngineTestFramework.java index acb5ed9..5d7eaa8 100644 --- a/tests/src/com/vodafone360/people/tests/engine/EngineTestFramework.java +++ b/tests/src/com/vodafone360/people/tests/engine/EngineTestFramework.java @@ -1,265 +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.tests.engine; import java.util.ArrayList; import java.util.List; import android.util.Log; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine; 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.ResponseQueue; import com.vodafone360.people.service.transport.IConnection; import com.vodafone360.people.tests.IPeopleTestFramework; import com.vodafone360.people.tests.PeopleTestConnectionThread; public class EngineTestFramework implements IEngineEventCallback, IPeopleTestFramework { private Thread mEngineWorkerThread = null; private BaseEngine mEngine = null; private boolean mActive = false; private IEngineTestFrameworkObserver mObserver; private PeopleTestConnectionThread mConnThread = null; private Object mEngReqLock = new Object(); private Object mObjectLock = new Object(); private AuthSessionHolder mSession = new AuthSessionHolder(); private int mStatus; private Object mData = null; private boolean mRequestCompleted; private static int K_REQ_TIMEOUT_MSA = 60000; public EngineTestFramework(IEngineTestFrameworkObserver observer) { Log.d("TAG", "EngineTestFramework.EngineTestFramework"); mObserver = observer; // setup dummy session mSession.userID = 0; mSession.sessionSecret = new String("sssh"); mSession.userName = new String("bob"); mSession.sessionID = new String("session"); LoginEngine.setTestSession(mSession); // create a 'worker' thread for engines to kick mEngineWorkerThread = new Thread(new Runnable() { @Override public void run() { Log.d("TAG", "run"); while (mActive) { // Log.d("TAG", "eng framework active"); long mCurrentTime = System.currentTimeMillis(); long nextRunTime = -1; try { nextRunTime = mEngine.getNextRunTime(); } catch (Exception e) { onEngineException(e); } if (nextRunTime != -1 && nextRunTime <= mCurrentTime) { Log.d("TAG", "run the engine"); try { mEngine.run(); } catch (Exception e) { onEngineException(e); } } else { // Log.d("TAG", "eng framework inactive"); synchronized (mObjectLock) { try { // Log.d("TAG", "lock the engine"); mObjectLock.wait(500); } catch (Exception e) { } } } } } }); } public void setEngine(BaseEngine eng) { Log.d("TAG", "enginetestframework.setEngine"); if (eng == null) { throw (new RuntimeException("Engine is null")); } mEngine = eng; // start our 'worker' thread mActive = true; // start the connection thread mConnThread = new PeopleTestConnectionThread(this); mConnThread.startThread(); // start the worker thread mEngineWorkerThread.start(); QueueManager.getInstance().addQueueListener(mConnThread); } public ServiceStatus waitForEvent() { return waitForEvent(K_REQ_TIMEOUT_MSA); } public ServiceStatus waitForEvent(int ts) { Log.d("TAG", "EngineTestFramework waitForEvent"); NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); kickWorkerThread(); long endTime = System.nanoTime() + (((long)ts) * 1000000); ServiceStatus returnStatus = ServiceStatus.ERROR_UNEXPECTED_RESPONSE; mStatus = 5; // ERROR_COMMS_TIMEOUT synchronized (mEngReqLock) { while (!mRequestCompleted && System.nanoTime() < endTime) { try { mEngReqLock.wait(ts); } catch (InterruptedException e) { } } returnStatus = ServiceStatus.fromInteger(mStatus); } mRequestCompleted = false; return returnStatus; } @Override public void kickWorkerThread() { Log.d("TAG", "kickWorkerThread"); synchronized (mObjectLock) { mObjectLock.notify(); } } @Override public void onUiEvent(ServiceUiRequest event, int request, int status, Object data) { mRequestCompleted = true; // mActive = false; mStatus = status; mData = data; synchronized (mEngReqLock) { mEngReqLock.notify(); } } public Object data() { return mData; } @Override public void reportBackToFramework(int reqId, EngineId engine) { Log.d("TAG", "EngineTestFramework.reportBackToFramework"); mObserver.reportBackToEngine(reqId, engine); final QueueManager reqQ = QueueManager.getInstance(); final ResponseQueue respQ = ResponseQueue.getInstance(); if (reqQ.getRequest(reqId) != null) { List<BaseDataType> dataTypeList = new ArrayList<BaseDataType>(); - ServerError err = new ServerError(); - err.errorType = ServerError.ErrorTypes.UNKNOWN.toString(); + ServerError err = new ServerError(ServerError.ErrorType.UNKNOWN); dataTypeList.add(err); respQ.addToResponseQueue(reqId, dataTypeList, engine); } } @Override public IConnection testConnectionThread() { // TODO Auto-generated method stub return null; } public void callRun(int reqId, List<BaseDataType> data) { ResponseQueue.getInstance().addToResponseQueue(reqId, data, mEngine.engineId()); try { mEngine.onCommsInMessage(); mEngine.run(); } catch (Exception e) { onEngineException(e); } } public void stopEventThread() { QueueManager.getInstance().removeQueueListener(mConnThread); synchronized (mObjectLock) { mActive = false; mObjectLock.notify(); } mConnThread.stopThread(); } private void onEngineException(Exception e) { String strExceptionInfo = e + "\n"; for (int i = 0; i < e.getStackTrace().length; i++) { StackTraceElement v = e.getStackTrace()[i]; strExceptionInfo += "\t" + v + "\n"; } Log.e("TAG", "Engine exception occurred\n" + strExceptionInfo); mObserver.onEngineException(e); synchronized (mEngReqLock) { mActive = false; mStatus = ServiceStatus.ERROR_UNKNOWN.ordinal(); mData = e; mEngReqLock.notify(); } } @Override public UiAgent getUiAgent() { // TODO Auto-generated method stub return null; } @Override public ApplicationCache getApplicationCache() { // TODO Auto-generated method stub return null; } } \ No newline at end of file diff --git a/tests/src/com/vodafone360/people/tests/engine/IdentityEngineTest.java b/tests/src/com/vodafone360/people/tests/engine/IdentityEngineTest.java index 5b9521b..8c93a11 100644 --- a/tests/src/com/vodafone360/people/tests/engine/IdentityEngineTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/IdentityEngineTest.java @@ -1,352 +1,350 @@ /* * 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.net.URL; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.identities.IdentityEngine; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.io.ResponseQueue; public class IdentityEngineTest extends InstrumentationTestCase implements IEngineTestFrameworkObserver { /** * States for test harness */ enum IdentityTestState { IDLE, FETCH_IDENTITIES, GET_MY_IDENTITIES, FETCH_IDENTITIES_FAIL, FETCH_IDENTITIES_POPULATED, GET_CHATABLE_IDENTITIES, SET_IDENTITY_CAPABILTY, VALIDATE_ID_CREDENTIALS_SUCCESS, VALIDATE_ID_CREDENTIALS_FAIL, GET_NEXT_RUNTIME } EngineTestFramework mEngineTester = null; IdentityEngine mEng = null; IdentityTestState mState = IdentityTestState.IDLE; @Override protected void setUp() throws Exception { super.setUp(); mEngineTester = new EngineTestFramework(this); mEng = new IdentityEngine(mEngineTester); mEngineTester.setEngine(mEng); mState = IdentityTestState.IDLE; } @Override protected void tearDown() throws Exception { // stop our dummy thread? mEngineTester.stopEventThread(); mEngineTester = null; mEng = null; // call at the end!!! super.tearDown(); } @Suppress // Takes too long @MediumTest public void testFetchIdentities() { mState = IdentityTestState.FETCH_IDENTITIES; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.addUiFetchIdentities(); + mEng.getAvailableThirdPartyIdentities(); // mEng.run(); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); 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 @Suppress // Takes too long. public void testAddUiGetMyIdentities() { mState = IdentityTestState.GET_MY_IDENTITIES; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.addUiGetMyIdentities(); + mEng.getMyThirdPartyIdentities(); // mEng.run(); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); Object data = mEngineTester.data(); assertNull(null); try { ArrayList<Identity> identityList = ((Bundle)data).getParcelableArrayList("data"); assertEquals(identityList.size(), 1); } catch (Exception e) { throw (new RuntimeException("Expected identity list with 1 item")); } } @MediumTest @Suppress // Takes to long public void testFetchIdentitiesFail() { mState = IdentityTestState.FETCH_IDENTITIES_FAIL; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.addUiFetchIdentities(); + mEng.getAvailableThirdPartyIdentities(); // mEng.run(); ServiceStatus status = mEngineTester.waitForEvent(); assertFalse(ServiceStatus.SUCCESS == status); Object data = mEngineTester.data(); assertNull(data); } @MediumTest @Suppress // Breaks tests. public void testFetchIdentitiesPopulated() { mState = IdentityTestState.FETCH_IDENTITIES_POPULATED; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.addUiFetchIdentities(); + mEng.getAvailableThirdPartyIdentities(); // mEng.run(); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); Object data = mEngineTester.data(); assertTrue(data != null); } @MediumTest @Suppress // Breaks tests. 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); // AA mEng.addUiSetIdentityCapabilityStatus(network, identityId, fbund); mEng.addUiSetIdentityStatus(network, identityId, true); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); 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 @Suppress // Breaks tests. 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(); assertEquals(ServiceStatus.SUCCESS, status); Object data = mEngineTester.data(); assertTrue(data != null); } @MediumTest @Suppress // Breaks tests. public void testGetMyChatableIdentities() { mState = IdentityTestState.GET_CHATABLE_IDENTITIES; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.getMyChatableIdentities(); + mEng.getMy360AndThirdPartyChattableIdentities(); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); Object data = mEngineTester.data(); assertTrue(data != null); } @MediumTest @Suppress // Breaks tests. 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(); assertFalse(ServiceStatus.SUCCESS == status); 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 GET_MY_IDENTITIES: Log.d("TAG", "IdentityEngineTest.reportBackToEngine Get ids"); Identity myId = new Identity(); data.add(myId); 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"; + ServerError err = new ServerError("Catastrophe"); + err.errorDescription = "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"; + ServerError err2 = new ServerError("Catastrophe"); + err2.errorDescription = "Fail"; data.add(err2); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; case GET_NEXT_RUNTIME: break; case GET_CHATABLE_IDENTITIES: case FETCH_IDENTITIES_POPULATED: Identity id2 = new Identity(); id2.mActive = true; id2.mAuthType = "auth"; List<String> clist = new ArrayList<String>(); clist.add("uk"); clist.add("fr"); id2.mCountryList = clist; id2.mCreated = new Long(0); id2.mDisplayName = "Facebook"; // id2.mIcon2Mime = "jpeg"; id2.mIconMime = "jpeg"; try { id2.mIcon2Url = new URL("url2"); id2.mIconUrl = new URL("url"); id2.mNetworkUrl = new URL("network"); } catch (Exception e) { } id2.mIdentityId = "fb"; id2.mIdentityType = "type"; id2.mName = "Facebook"; id2.mNetwork = "Facebook"; id2.mOrder = 0; id2.mPluginId = ""; id2.mUpdated = new Long(0); id2.mUserId = 23; id2.mUserName = "user"; data.add(id2); List<IdentityCapability> capList = new ArrayList<IdentityCapability>(); IdentityCapability idcap = new IdentityCapability(); idcap.mCapability = IdentityCapability.CapabilityID.sync_contacts; idcap.mDescription = "sync cont"; idcap.mName = "sync cont"; idcap.mValue = true; capList.add(idcap); id2.mCapabilities = capList; data.add(id2); respQueue.addToResponseQueue(reqId, data, engine); Log.d("TAG", "IdentityEngineTest.reportBackToEngine add to Q"); mEng.onCommsInMessage(); break; default: } } @Override public void onEngineException(Exception exp) { // TODO Auto-generated method stub } } diff --git a/tests/src/com/vodafone360/people/tests/engine/LoginEngineTest.java b/tests/src/com/vodafone360/people/tests/engine/LoginEngineTest.java index a7d3a52..2c53fc9 100644 --- a/tests/src/com/vodafone360/people/tests/engine/LoginEngineTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/LoginEngineTest.java @@ -54,548 +54,548 @@ import com.vodafone360.people.tests.TestModule; @Suppress public class LoginEngineTest extends InstrumentationTestCase implements IEngineTestFrameworkObserver, ILoginEventsListener { /** * States for test harness */ enum LoginTestState { IDLE, ON_CREATE, ON_DESTROY, LOGIN_REQUEST, LOGIN_REQUEST_VALID, REMOVE_USER_DATA_REQ, LOGOUT_REQ, REGISTRATION, REGISTRATION_ERROR, GET_T_AND_C, FETCH_PRIVACY, USER_NAME_STATE, GET_NEXT_RUN_TIME, SERVER_ERROR, SMS_RESPONSE_SIGNIN, ON_REMOVE_USERDATA } EngineTestFramework mEngineTester = null; LoginEngine mEng = null; LoginTestState mState = LoginTestState.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(); mEngineTester = new EngineTestFramework(this); mEng = new LoginEngine(getInstrumentation().getTargetContext(), mEngineTester, mApplication .getDatabase()); mEngineTester.setEngine(mEng); mState = LoginTestState.IDLE; mEng.addListener(this); } @Override protected void tearDown() throws Exception { // stop our dummy thread? mEngineTester.stopEventThread(); mEngineTester = null; mEng.removeListener(this); mEng = null; // call at the end!!! super.tearDown(); } @MediumTest public void testOnCreate() { boolean testPassed = true; mState = LoginTestState.ON_CREATE; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { mEng.onCreate(); } catch (Exception e) { testPassed = false; } assertTrue(testPassed == true); } @MediumTest public void testOnDestroy() { boolean testPassed = true; mState = LoginTestState.ON_DESTROY; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { mEng.onCreate(); } catch (Exception e) { testPassed = false; } try { mEng.onDestroy(); } catch (Exception e) { Log.d("TAG", e.toString()); testPassed = false; } // expect failure as we've not assertTrue(testPassed == true); } @MediumTest @Suppress // Breaks tests. public void testLoginNullDetails() { mState = LoginTestState.LOGIN_REQUEST; LoginDetails loginDetails = null; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { synchronized (mEngineTester) { mEng.addUiLoginRequest(loginDetails); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, status); } } catch (Exception e) { displayException(e); fail("testLoginNullDetails test 1 failed with exception"); } loginDetails = new LoginDetails(); try { synchronized (mEngineTester) { mEng.addUiLoginRequest(loginDetails); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_COMMS, status); } } catch (Exception e) { displayException(e); fail("testLoginNullDetails test 2 failed with exception"); } } private void displayException(Exception e) { String strExceptionInfo = e + "\n"; for (int i = 0; i < e.getStackTrace().length; i++) { StackTraceElement v = e.getStackTrace()[i]; strExceptionInfo += "\t" + v + "\n"; } Log.e("TAG", "General exception occurred State = " + mState + "\n" + strExceptionInfo); } @MediumTest @Suppress // Breaks tests. public void testLoginValidDetails() { mState = LoginTestState.LOGIN_REQUEST; LoginDetails loginDetails = new LoginDetails(); loginDetails.mMobileNo = "123456789"; loginDetails.mUsername = "bob"; loginDetails.mPassword = "ajob"; try { synchronized (mEngineTester) { mEng.addUiLoginRequest(loginDetails); ServiceStatus status = mEngineTester.waitForEvent(120000); assertEquals(ServiceStatus.ERROR_SMS_CODE_NOT_RECEIVED, status); } // test actually receiving the SMS } catch (Exception e) { displayException(e); fail("testLoginValidDetails test 1 failed with exception"); } } @MediumTest public void testRemoveUserData() { boolean testPassed = true; mState = LoginTestState.REMOVE_USER_DATA_REQ; try { synchronized (mEngineTester) { mEng.addUiRemoveUserDataRequest(); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("SUCCESS")); } } // test actually receiving the SMS } catch (Exception e) { testPassed = false; } try { synchronized (mEngineTester) { mEng.onReset(); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("SUCCESS")); } } // test actually receiving the SMS } catch (Exception e) { testPassed = false; } assertTrue(testPassed == true); } @MediumTest public void testLogout() { boolean testPassed = true; mState = LoginTestState.LOGOUT_REQ; try { synchronized (mEngineTester) { mEng.addUiRequestToQueue(ServiceUiRequest.LOGOUT, null); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("SUCCESS")); } } // test actually receiving the SMS } catch (Exception e) { testPassed = false; } assertTrue(testPassed == true); } /* * addUiRegistrationRequest(non-Javadoc) * @seecom.vodafone360.people.tests.engine.IEngineTestFrameworkObserver# * reportBackToEngine(int, * com.vodafone360.people.engine.EngineManager.EngineId) */ @MediumTest @Suppress // Breaks tests. public void testRegistration() { mState = LoginTestState.REGISTRATION; NetworkAgent.setAgentState(NetworkAgent.AgentState.DISCONNECTED); RegistrationDetails details = null; try { synchronized (mEngineTester) { mEng.addUiRegistrationRequest(details); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, status); } } catch (Exception e) { displayException(e); fail("testRegistration test 1 failed with exception"); } NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { synchronized (mEngineTester) { mEng.addUiRegistrationRequest(details); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, status); } } catch (Exception e) { displayException(e); fail("testRegistration test 2 failed with exception"); } details = new RegistrationDetails(); try { synchronized (mEngineTester) { mEng.addUiRegistrationRequest(details); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, status); } } catch (Exception e) { displayException(e); fail("testRegistration test 3 failed with exception"); } details.mUsername = "bwibble"; details.mPassword = "qqqqqq"; try { synchronized (mEngineTester) { mEng.addUiRegistrationRequest(details); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, status); } } catch (Exception e) { displayException(e); fail("testRegistration test 4 failed with exception"); } details.mFullname = "Billy Wibble"; details.mBirthdayDate = "12345678"; details.mEmail = "[email protected]"; details.mMsisdn = "123456"; details.mAcceptedTAndC = true; details.mCountrycode = "uk"; details.mTimezone = "gmt"; details.mLanguage = "english"; details.mSendConfirmationMail = true; details.mSendConfirmationSms = true; details.mSubscribeToNewsLetter = true; details.mMobileOperatorId = new Long(1234); details.mMobileModelId = new Long(12345); try { synchronized (mEngineTester) { mEng.addUiRegistrationRequest(details); ServiceStatus status = mEngineTester.waitForEvent(120000); assertEquals(ServiceStatus.ERROR_SMS_CODE_NOT_RECEIVED, status); } } catch (Exception e) { displayException(e); fail("testRegistration test 5 failed with exception"); } } @MediumTest @Suppress // Breaks tests. public void testGetTermsAndConditions() { boolean testPassed = true; mState = LoginTestState.GET_T_AND_C; NetworkAgent.setAgentState(NetworkAgent.AgentState.DISCONNECTED); try { synchronized (mEngineTester) { mEng.addUiFetchTermsOfServiceRequest(); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("Expected SUCCESS")); } } } catch (Exception e) { testPassed = false; } NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { synchronized (mEngineTester) { mEng.addUiFetchTermsOfServiceRequest(); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("Expected SUCCESS")); } } } catch (Exception e) { testPassed = false; } assertTrue(testPassed == true); } @MediumTest @Suppress // Breaks tests. public void testFetchPrivacy() { boolean testPassed = true; mState = LoginTestState.FETCH_PRIVACY; NetworkAgent.setAgentState(NetworkAgent.AgentState.DISCONNECTED); try { synchronized (mEngineTester) { mEng.addUiFetchPrivacyStatementRequest(); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("Expected SUCCESS")); } } } catch (Exception e) { testPassed = false; } NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { synchronized (mEngineTester) { mEng.addUiFetchPrivacyStatementRequest(); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("Expected SUCCESS")); } } } catch (Exception e) { testPassed = false; } assertTrue(testPassed == true); } @MediumTest @Suppress // Breaks tests. public void testFetchUserNameState() { mState = LoginTestState.USER_NAME_STATE; String userName = null; try { synchronized (mEngineTester) { mEng.addUiGetUsernameStateRequest(userName); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_COMMS, status); } } catch (Exception e) { displayException(e); fail("testFetchUserNameState test 1 failed with exception"); } userName = "bwibble"; try { synchronized (mEngineTester) { mEng.addUiGetUsernameStateRequest(userName); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); } } catch (Exception e) { displayException(e); fail("testFetchUserNameState test 2 failed with exception"); } } @MediumTest public void testGetNextRuntime() { boolean testPassed = true; mState = LoginTestState.GET_NEXT_RUN_TIME; long nt = mEng.getNextRunTime(); if (nt != 0) { testPassed = false; } assertTrue(testPassed == true); } // @MediumTest // public void testSmsResponse(){ // LoginDetails loginDetails = new LoginDetails(); // loginDetails.mMobileNo = "123456789"; // loginDetails.mUsername = "bob"; // loginDetails.mPassword = "ajob"; // // mState = LoginTestState.LOGIN_REQUEST; // NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); // synchronized(mEngineTester){ // mEng.addUiLoginRequest(loginDetails); // // ServiceStatus status = mEngineTester.waitForEvent(); // assertEquals(ServiceStatus.SUCCESS, status); // } // // test actually receiving the SMS // mState = LoginTestState.SMS_RESPONSE_SIGNIN; // // mEng.handleSmsResponse(); // // ServiceStatus status = mEngineTester.waitForEvent(30000); // assertEquals(ServiceStatus.SUCCESS, status); // } @MediumTest public void testPublicFunctions() { mEng.getLoginRequired(); NetworkAgent.setAgentState(NetworkAgent.AgentState.DISCONNECTED); mEng.getNewPublicKey(); NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); mEng.getNewPublicKey(); mEng.isDeactivated(); mEng.setActivatedSession(new AuthSessionHolder()); } @Override public void reportBackToEngine(int reqId, EngineId engine) { Log.d("TAG", "LoginEngineTest.reportBackToEngine"); ResponseQueue respQueue = ResponseQueue.getInstance(); List<BaseDataType> data = new ArrayList<BaseDataType>(); // Request Activation code switch (mState) { case IDLE: break; case LOGIN_REQUEST: case SMS_RESPONSE_SIGNIN: Log.d("TAG", "IdentityEngineTest.reportBackToEngine FETCH ids"); StatusMsg msg = new StatusMsg(); data.add(msg); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); mState = LoginTestState.LOGIN_REQUEST_VALID; break; case LOGIN_REQUEST_VALID: Log.d("TAG", "IdentityEngineTest.reportBackToEngine FETCH ids"); AuthSessionHolder sesh = new AuthSessionHolder(); data.add(sesh); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); mState = LoginTestState.SMS_RESPONSE_SIGNIN; break; case REGISTRATION: Log.d("TAG", "IdentityEngineTest.reportBackToEngine Registration"); data.add(mTestModule.createDummyContactData()); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; case REGISTRATION_ERROR: - data.add(new ServerError()); + data.add(new ServerError(ServerError.ErrorType.UNKNOWN)); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; case GET_T_AND_C: case FETCH_PRIVACY: case USER_NAME_STATE: SimpleText txt = new SimpleText(); txt.addText("Simple text"); data.add(txt); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; case SERVER_ERROR: - data.add(new ServerError()); + data.add(new ServerError(ServerError.ErrorType.UNKNOWN)); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; default: } } @Override public void onLoginStateChanged(boolean loggedIn) { // TODO Auto-generated method stub } @Override public void onEngineException(Exception exp) { // TODO Auto-generated method stub } } diff --git a/tests/src/com/vodafone360/people/tests/engine/contactsync/DownloadServerContactsTest.java b/tests/src/com/vodafone360/people/tests/engine/contactsync/DownloadServerContactsTest.java index 7b00321..e7d93c6 100644 --- a/tests/src/com/vodafone360/people/tests/engine/contactsync/DownloadServerContactsTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/contactsync/DownloadServerContactsTest.java @@ -1,779 +1,778 @@ /* * 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.util.ArrayList; import java.util.List; import android.app.Instrumentation; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; 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.ContactSummaryTable; 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.ContactSummary; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.contactsync.DownloadServerContacts; import com.vodafone360.people.engine.contactsync.IContactSyncCallback; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.io.ResponseQueue; import com.vodafone360.people.tests.TestModule; import com.vodafone360.people.tests.engine.EngineTestFramework; import com.vodafone360.people.tests.engine.IEngineTestFrameworkObserver; public class DownloadServerContactsTest extends InstrumentationTestCase implements IEngineTestFrameworkObserver { private static final String LOG_TAG = "DownloadServerContactsTest"; private static final long MAX_PROCESSOR_TIME = 30000000; private static final int CURRENT_SERVER_VERSION = 50; private static final long FIRST_MODIFIED_CONTACT_ID = 293822; private static final String MODIFIED_NICKNAME_STRING = "ModNickname"; private static final String MODIFIED_PHONE_STRING = "441292832827"; private static final ContactDetail.DetailKeyTypes MODIFIED_PHONE_TYPE = ContactDetail.DetailKeyTypes.MOBILE; private static final Integer MODIFIED_PHONE_ORDER = 60; private static final String NEW_PHONE_STRING = "10203040498"; private static final ContactDetail.DetailKeyTypes NEW_PHONE_TYPE = null; private static final Integer NEW_PHONE_ORDER = 0; private static final String NEW_EMAIL_STRING = "AddEmail"; private static final ContactDetail.DetailKeyTypes NEW_EMAIL_TYPE = ContactDetail.DetailKeyTypes.WORK; private static final Integer NEW_EMAIL_ORDER = 40; private static final String DEL_EMAIL_STRING2 = "1239383333"; private static final Long NEW_EMAIL_DETAIL_ID = 202033L; private static final Long NEW_PHONE_DETAIL_ID = 301020L; private static final Long OLD_PHONE_DETAIL_ID = 502292L; private static final Long ALT_PHONE_DETAIL_ID = 602292L; private static final String OLD_PHONE_DETAIL_VALUE = "OldPhoneValue"; private static final long WAIT_FOR_PAGE_MS = 100; private static final long MAX_WAIT_FOR_PAGE_MS = 10000L; private static final int BULK_TEST_NO_CONTACTS = 100; enum State { IDLE, RUN_WITH_NO_CHANGES, RUN_WITH_NEW_CONTACTS, RUN_WITH_DELETED_CONTACTS, RUN_WITH_MODIFIED_CONTACTS, RUN_WITH_DELETED_DETAILS } EngineTestFramework mEngineTester = null; MainApplication mApplication = null; DummyContactSyncEngine mEng = null; Context mContext; class DownloadServerContactProcessorTest extends DownloadServerContacts { DownloadServerContactProcessorTest(IContactSyncCallback callback, DatabaseHelper db) { super(callback, db); } public Integer testGetPageFromReqId(int reqId) { switch (mInternalState) { case FETCHING_NEXT_BATCH: long endTime = System.nanoTime() + (MAX_WAIT_FOR_PAGE_MS * 1000000); while (mPageReqIds.get(reqId) == null && System.nanoTime() < endTime) { try { synchronized (this) { wait(WAIT_FOR_PAGE_MS); } } catch (InterruptedException e) { e.printStackTrace(); } } return mPageReqIds.get(reqId); case FETCHING_FIRST_PAGE: return 0; default: return null; } } public int getDownloadPageSize() { return MAX_DOWN_PAGE_SIZE; } } DownloadServerContactProcessorTest mProcessor; DatabaseHelper mDb = null; State mState = State.IDLE; int mInitialCount; int mItemCount; int mPageCount; Contact mLastNewContact; TestModule mTestModule = new TestModule(); int mTestStep; @Override protected void setUp() throws Exception { super.setUp(); mApplication = (MainApplication)Instrumentation.newApplication(MainApplication.class, getInstrumentation().getTargetContext()); mApplication.onCreate(); mDb = mApplication.getDatabase(); mDb.removeUserData(); mEngineTester = new EngineTestFramework(this); mEng = new DummyContactSyncEngine(mEngineTester); mProcessor = new DownloadServerContactProcessorTest(mEng, mApplication.getDatabase()); mEng.setProcessor(mProcessor); mEngineTester.setEngine(mEng); mState = State.IDLE; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); } @Override protected void tearDown() throws Exception { // stop our dummy thread? mEngineTester.stopEventThread(); mEngineTester = null; mEng = null; SQLiteDatabase db = mDb.getReadableDatabase(); if (db.inTransaction()) { db.endTransaction(); } db.close(); super.tearDown(); } private void startSubTest(String function, String description) { Log.i(LOG_TAG, function + " - step " + mTestStep + ": " + description); mTestStep++; } private void runProcessor(int count, State state) { mInitialCount = count; mPageCount = 0; nextState(state); mLastNewContact = null; mEng.mProcessorCompleteFlag = false; mProcessor.start(); ServiceStatus status = mEng.waitForProcessorComplete(MAX_PROCESSOR_TIME); assertEquals(ServiceStatus.SUCCESS, status); } private void nextState(State state) { mItemCount = mInitialCount; if (mItemCount == 0) { mState = State.IDLE; } else { mState = state; } } @Override public void reportBackToEngine(int reqId, EngineId engine) { Log.d(LOG_TAG, "reportBackToEngine"); ResponseQueue respQueue = ResponseQueue.getInstance(); List<BaseDataType> data = new ArrayList<BaseDataType>(); try { assertEquals(mEng.engineId(), engine); switch (mState) { case RUN_WITH_NO_CHANGES: reportBackWithNoChanges(reqId, data); break; case RUN_WITH_NEW_CONTACTS: reportBackWithNewContacts(reqId, data); break; case RUN_WITH_DELETED_CONTACTS: reportBackWithDeletedContacts(reqId, data); break; case RUN_WITH_MODIFIED_CONTACTS: reportBackWithModifiedContacts(reqId, data); break; case RUN_WITH_DELETED_DETAILS: reportBackWithDeletedDetails(reqId, data); break; default: fail("Unexpected request rom processor"); } } catch (Throwable err) { - ServerError serverError = new ServerError(); - serverError.errorType = ServerError.ErrorTypes.INTERNALERROR.toString(); - serverError.errorValue = err + "\n"; + ServerError serverError = new ServerError(ServerError.ErrorType.INTERNALERROR); + serverError.errorDescription = err + "\n"; for (int i = 0; i < err.getStackTrace().length; i++) { StackTraceElement v = err.getStackTrace()[i]; - serverError.errorValue += "\t" + v + "\n"; + serverError.errorDescription += "\t" + v + "\n"; } - Log.e(LOG_TAG, "Exception:\n" + serverError.errorValue); + Log.e(LOG_TAG, "Exception:\n" + serverError.errorDescription); data.clear(); data.add(serverError); } respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); Log.d(LOG_TAG, "reportBackToEngine - message added to response queue"); } private void reportBackWithNoChanges(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackWithNoChanges"); Integer pageNo = mProcessor.testGetPageFromReqId(reqId); assertTrue(pageNo != null); assertEquals(Integer.valueOf(0), pageNo); ContactChanges contactChanges = new ContactChanges(); data.add(contactChanges); contactChanges.mCurrentServerVersion = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionBefore = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionAfter = CURRENT_SERVER_VERSION; contactChanges.mVersionAnchor = CURRENT_SERVER_VERSION; contactChanges.mNumberOfPages = 1; mItemCount--; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportBackWithNewContacts(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackWithNewContacts"); Integer pageNo = mProcessor.testGetPageFromReqId(reqId); int pageSize = mProcessor.getDownloadPageSize(); assertTrue(pageNo != null); assertEquals(Integer.valueOf(mPageCount), pageNo); ContactChanges contactChanges = new ContactChanges(); data.add(contactChanges); contactChanges.mCurrentServerVersion = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionBefore = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionAfter = CURRENT_SERVER_VERSION; contactChanges.mVersionAnchor = CURRENT_SERVER_VERSION; assertTrue(pageSize > 0); if (pageSize > 0) { contactChanges.mNumberOfPages = 1 + mPageCount + (mItemCount / pageSize); } int noOfContacts = Math.min(pageSize, mItemCount); for (int i = 0; i < noOfContacts; i++) { Contact newContact = mTestModule.createDummyContactData(); if (mLastNewContact == null) { mLastNewContact = newContact; } newContact.contactID = FIRST_MODIFIED_CONTACT_ID + mItemCount - 1; newContact.userID = generateTestUserID(newContact.contactID); ContactDetail detail1 = new ContactDetail(); detail1.key = ContactDetail.DetailKeys.VCARD_PHONE; detail1.unique_id = OLD_PHONE_DETAIL_ID + mItemCount - 1; detail1.value = OLD_PHONE_DETAIL_VALUE; newContact.details.add(detail1); for (int j = 0; j < newContact.details.size(); j++) { ContactDetail detail = newContact.details.get(j); switch (detail.key) { case VCARD_PHONE: case VCARD_EMAIL: if (detail.unique_id == null) { detail.unique_id = ALT_PHONE_DETAIL_ID + j; } break; } } contactChanges.mContacts.add(newContact); mItemCount--; } mPageCount++; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportBackWithDeletedContacts(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackWithDeletedContacts"); Integer pageNo = mProcessor.testGetPageFromReqId(reqId); int pageSize = mProcessor.getDownloadPageSize(); assertTrue(pageNo != null); assertEquals(Integer.valueOf(mPageCount), pageNo); ContactChanges contactChanges = new ContactChanges(); data.add(contactChanges); contactChanges.mCurrentServerVersion = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionBefore = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionAfter = CURRENT_SERVER_VERSION; contactChanges.mVersionAnchor = CURRENT_SERVER_VERSION; assertTrue(pageSize > 0); if (pageSize > 0) { contactChanges.mNumberOfPages = 1 + mPageCount + (mItemCount / pageSize); } int noOfContacts = Math.min(pageSize, mItemCount); for (int i = 0; i < noOfContacts; i++) { Contact deletedContact = new Contact(); deletedContact.contactID = FIRST_MODIFIED_CONTACT_ID + mItemCount - 1; deletedContact.deleted = true; contactChanges.mContacts.add(deletedContact); mItemCount--; } mPageCount++; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportBackWithModifiedContacts(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackWithModifiedContacts"); Integer pageNo = mProcessor.testGetPageFromReqId(reqId); int pageSize = mProcessor.getDownloadPageSize(); assertTrue(pageNo != null); assertEquals(Integer.valueOf(mPageCount), pageNo); ContactChanges contactChanges = new ContactChanges(); data.add(contactChanges); contactChanges.mCurrentServerVersion = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionBefore = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionAfter = CURRENT_SERVER_VERSION; contactChanges.mVersionAnchor = CURRENT_SERVER_VERSION; assertTrue(pageSize > 0); if (pageSize > 0) { contactChanges.mNumberOfPages = 1 + mPageCount + (mItemCount / pageSize); } int noOfContacts = Math.min(pageSize, mItemCount); for (int i = 0; i < noOfContacts; i++) { Contact modifiedContact = new Contact(); modifiedContact.contactID = FIRST_MODIFIED_CONTACT_ID + mItemCount - 1; // Modified details ContactDetail detail1 = new ContactDetail(); detail1.key = ContactDetail.DetailKeys.VCARD_NICKNAME; detail1.value = generateModifiedString(MODIFIED_NICKNAME_STRING, mItemCount - 1); modifiedContact.details.add(detail1); ContactDetail detail2 = new ContactDetail(); detail2.key = ContactDetail.DetailKeys.VCARD_PHONE; detail2.keyType = MODIFIED_PHONE_TYPE; detail2.order = MODIFIED_PHONE_ORDER; detail2.value = generateModifiedString(MODIFIED_PHONE_STRING, mItemCount - 1); detail2.unique_id = OLD_PHONE_DETAIL_ID + mItemCount - 1; modifiedContact.details.add(detail2); // New details ContactDetail detail3 = new ContactDetail(); detail3.key = ContactDetail.DetailKeys.VCARD_PHONE; detail3.keyType = NEW_PHONE_TYPE; detail3.order = NEW_PHONE_ORDER; detail3.value = generateModifiedString(NEW_PHONE_STRING, mItemCount - 1); detail3.unique_id = NEW_PHONE_DETAIL_ID + mItemCount - 1; modifiedContact.details.add(detail3); ContactDetail detail4 = new ContactDetail(); detail4.key = ContactDetail.DetailKeys.VCARD_EMAIL; detail4.keyType = NEW_EMAIL_TYPE; detail4.order = NEW_EMAIL_ORDER; detail4.value = generateModifiedString(NEW_EMAIL_STRING, mItemCount - 1); detail4.unique_id = NEW_EMAIL_DETAIL_ID + mItemCount - 1; modifiedContact.details.add(detail4); Log.d(LOG_TAG, "Contact " + modifiedContact.contactID + " has details " + detail1.unique_id + ", " + detail2.unique_id + ", " + detail3.unique_id + ", " + detail4.unique_id); contactChanges.mContacts.add(modifiedContact); mItemCount--; } mPageCount++; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportBackWithDeletedDetails(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackWithDeletedDetails"); Integer pageNo = mProcessor.testGetPageFromReqId(reqId); int pageSize = mProcessor.getDownloadPageSize(); assertTrue(pageNo != null); assertEquals(Integer.valueOf(mPageCount), pageNo); ContactChanges contactChanges = new ContactChanges(); data.add(contactChanges); contactChanges.mCurrentServerVersion = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionBefore = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionAfter = CURRENT_SERVER_VERSION; contactChanges.mVersionAnchor = CURRENT_SERVER_VERSION; assertTrue(pageSize > 0); if (pageSize > 0) { contactChanges.mNumberOfPages = 1 + mPageCount + (mItemCount / pageSize); } int noOfContacts = Math.min(pageSize, mItemCount); for (int i = 0; i < noOfContacts; i++) { Contact curContact = new Contact(); curContact.contactID = FIRST_MODIFIED_CONTACT_ID + mItemCount - 1; contactChanges.mContacts.add(curContact); ContactDetail delDetail1 = new ContactDetail(); delDetail1.key = ContactDetail.DetailKeys.VCARD_NAME; delDetail1.deleted = true; ContactDetail delDetail2 = new ContactDetail(); delDetail2.key = ContactDetail.DetailKeys.VCARD_NICKNAME; delDetail2.deleted = true; ContactDetail delDetail3 = new ContactDetail(); delDetail3.key = ContactDetail.DetailKeys.VCARD_EMAIL; delDetail3.unique_id = NEW_EMAIL_DETAIL_ID + mItemCount - 1; delDetail3.deleted = true; curContact.details.add(delDetail1); curContact.details.add(delDetail2); curContact.details.add(delDetail3); mItemCount--; } mPageCount++; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private String generateModifiedString(String template, int index) { return template + "," + index; } private Long generateTestUserID(Long contactID) { if (contactID == null) { return null; } if ((contactID & 3) == 0) { return null; } return contactID + 5; } @Override public void onEngineException(Exception e) { mEng.onProcessorComplete(ServiceStatus.ERROR_UNKNOWN, "", e); } @SmallTest @Suppress // Breaks tests. public void testRunWithNoContactChanges() { final String fnName = "testRunWithNoContactChanges"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking database is empty"); Cursor cursor = mDb.openContactSummaryCursor(null, null); assertEquals(0, cursor.getCount()); startSubTest(fnName, "Running processor"); runProcessor(1, State.RUN_WITH_NO_CHANGES); assertEquals(State.IDLE, mState); cursor.close(); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests. public void testRunWithOneNewContact() { final String fnName = "testRunWithOneNewContact"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking database is empty"); Cursor cursor = mDb.openContactSummaryCursor(null, null); assertEquals(0, cursor.getCount()); startSubTest(fnName, "Running processor"); runProcessor(1, State.RUN_WITH_NEW_CONTACTS); startSubTest(fnName, "Checking database now has one contact"); cursor.requery(); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToNext()); ContactSummary summary = ContactSummaryTable.getQueryData(cursor); Contact contact = new Contact(); ServiceStatus status = mDb.fetchContact(summary.localContactID, contact); assertEquals(ServiceStatus.SUCCESS, status); Long userId = generateTestUserID(contact.contactID); assertTrue(contact.contactID != null); assertEquals(userId, contact.userID); assertTrue(mLastNewContact != null); assertTrue(TestModule.doContactsMatch(contact, mLastNewContact)); assertTrue(TestModule.doContactsFieldsMatch(contact, mLastNewContact)); assertEquals(State.IDLE, mState); cursor.close(); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests. public void testRunWithOneDeletedContact() { final String fnName = "testRunWithOneDeletedContact"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking database is empty"); Cursor cursor = mDb.openContactSummaryCursor(null, null); assertEquals(0, cursor.getCount()); Contact contact = mTestModule.createDummyContactData(); contact.contactID = FIRST_MODIFIED_CONTACT_ID; List<Contact> contactList = new ArrayList<Contact>(); contactList.add(contact); ServiceStatus status = mDb.syncAddContactList(contactList, false, false); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Running processor"); runProcessor(1, State.RUN_WITH_DELETED_CONTACTS); startSubTest(fnName, "Checking database now has no contacts"); cursor.requery(); assertEquals(0, cursor.getCount()); cursor.close(); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests. public void testRunWithOneModifiedContact() { final String fnName = "testRunWithOneModifiedContact"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking database is empty"); Cursor cursor = mDb.openContactSummaryCursor(null, null); assertEquals(0, cursor.getCount()); Contact orgContact = mTestModule.createDummyContactData(); orgContact.contactID = FIRST_MODIFIED_CONTACT_ID; for (int j = 0; j < orgContact.details.size(); j++) { ContactDetail detail = orgContact.details.get(j); switch (detail.key) { case VCARD_PHONE: case VCARD_EMAIL: detail.unique_id = ALT_PHONE_DETAIL_ID + j; break; } } ContactDetail detail1 = new ContactDetail(); detail1.key = ContactDetail.DetailKeys.VCARD_PHONE; detail1.unique_id = OLD_PHONE_DETAIL_ID; detail1.value = OLD_PHONE_DETAIL_VALUE; orgContact.details.add(detail1); List<Contact> contactList = new ArrayList<Contact>(); int originalNoOfDetails = orgContact.details.size(); contactList.add(orgContact); ServiceStatus status = mDb.syncAddContactList(contactList, false, false); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Running processor"); runProcessor(1, State.RUN_WITH_MODIFIED_CONTACTS); startSubTest(fnName, "Checking database still has one contact"); cursor.requery(); assertEquals(1, cursor.getCount()); cursor.close(); Contact modContact = new Contact(); status = mDb.fetchContactByServerId(FIRST_MODIFIED_CONTACT_ID, modContact); assertEquals(ServiceStatus.SUCCESS, status); assertEquals(originalNoOfDetails + 2, modContact.details.size()); for (ContactDetail detail : modContact.details) { switch (detail.key) { case VCARD_NICKNAME: assertEquals(generateModifiedString(MODIFIED_NICKNAME_STRING, 0), detail.value); break; case VCARD_PHONE: if (detail.unique_id != null && detail.unique_id.equals(OLD_PHONE_DETAIL_ID)) { assertEquals(generateModifiedString(MODIFIED_PHONE_STRING, 0), detail.value); assertEquals(MODIFIED_PHONE_TYPE, detail.keyType); assertEquals(MODIFIED_PHONE_ORDER, detail.order); } else if (detail.unique_id != null && detail.unique_id.equals(NEW_PHONE_DETAIL_ID)) { assertEquals(generateModifiedString(NEW_PHONE_STRING, 0), detail.value); assertEquals(NEW_PHONE_TYPE, detail.keyType); assertEquals(NEW_PHONE_ORDER, detail.order); } break; case VCARD_EMAIL: if (detail.unique_id != null && detail.unique_id.equals(NEW_EMAIL_DETAIL_ID)) { assertEquals(generateModifiedString(NEW_EMAIL_STRING, 0), detail.value); assertEquals(NEW_EMAIL_TYPE, detail.keyType); assertEquals(NEW_EMAIL_ORDER, detail.order); assertEquals(NEW_EMAIL_DETAIL_ID, detail.unique_id); break; } // Fall through default: boolean done = false; for (int j = 0; j < orgContact.details.size(); j++) { if (orgContact.details.get(j).localDetailID.equals(detail.localDetailID)) { assertTrue(DatabaseHelper.doDetailsMatch(orgContact.details.get(j), detail)); assertFalse(DatabaseHelper.hasDetailChanged(orgContact.details.get(j), detail)); done = true; break; } } assertTrue(done); } } assertEquals(State.IDLE, mState); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests. public void testRunWithOneDeletedDetail() { final String fnName = "testRunWithOneDeletedDetail"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking database is empty"); Cursor cursor = mDb.openContactSummaryCursor(null, null); assertEquals(0, cursor.getCount()); Contact orgContact = mTestModule.createDummyContactData(); orgContact.contactID = FIRST_MODIFIED_CONTACT_ID; ContactDetail detail1 = new ContactDetail(); detail1.key = ContactDetail.DetailKeys.VCARD_EMAIL; detail1.keyType = NEW_EMAIL_TYPE; detail1.value = NEW_EMAIL_STRING; detail1.unique_id = NEW_EMAIL_DETAIL_ID; orgContact.details.add(detail1); ContactDetail detail2 = new ContactDetail(); detail2.key = ContactDetail.DetailKeys.VCARD_EMAIL; detail2.keyType = NEW_EMAIL_TYPE; detail2.value = DEL_EMAIL_STRING2; detail2.unique_id = NEW_EMAIL_DETAIL_ID + 1; orgContact.details.add(detail2); int originalNoOfDetails = orgContact.details.size(); List<Contact> contactList = new ArrayList<Contact>(); contactList.add(orgContact); ServiceStatus status = mDb.syncAddContactList(contactList, false, false); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Running processor"); runProcessor(1, State.RUN_WITH_DELETED_DETAILS); startSubTest(fnName, "Checking database still has 1 contact"); cursor.requery(); assertEquals(1, cursor.getCount()); cursor.close(); Contact modContact = new Contact(); status = mDb.fetchContactByServerId(FIRST_MODIFIED_CONTACT_ID, modContact); assertEquals(ServiceStatus.SUCCESS, status); assertEquals(originalNoOfDetails - 3, modContact.details.size()); for (ContactDetail detail : modContact.details) { switch (detail.key) { case VCARD_NAME: case VCARD_NICKNAME: fail("Unexpected detail after deletion: " + detail.key); break; case VCARD_EMAIL: if (detail.unique_id != null && detail.unique_id.equals(NEW_EMAIL_DETAIL_ID)) { fail("Unexpected detail after deletion: " + detail.key); break; } // Fall through default: boolean done = false; for (int j = 0; j < orgContact.details.size(); j++) { if (orgContact.details.get(j).localDetailID.equals(detail.localDetailID)) { assertTrue(DatabaseHelper.doDetailsMatch(orgContact.details.get(j), detail)); assertFalse(DatabaseHelper.hasDetailChanged(orgContact.details.get(j), detail)); done = true; break; } } diff --git a/tests/src/com/vodafone360/people/tests/engine/contactsync/UploadServerContactsTest.java b/tests/src/com/vodafone360/people/tests/engine/contactsync/UploadServerContactsTest.java index 5b2bd6f..df5b3e8 100644 --- a/tests/src/com/vodafone360/people/tests/engine/contactsync/UploadServerContactsTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/contactsync/UploadServerContactsTest.java @@ -1,810 +1,809 @@ /* * 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.util.ArrayList; import java.util.List; import java.util.ListIterator; import android.app.Instrumentation; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; 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.ContactChangeLogTable; import com.vodafone360.people.database.tables.ContactDetailsTable; import com.vodafone360.people.database.tables.ContactSummaryTable; 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.ContactSummary; import com.vodafone360.people.datatypes.GroupItem; import com.vodafone360.people.datatypes.ItemList; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.contactsync.IContactSyncCallback; import com.vodafone360.people.engine.contactsync.UploadServerContacts; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.io.ResponseQueue; import com.vodafone360.people.tests.TestModule; import com.vodafone360.people.tests.engine.EngineTestFramework; import com.vodafone360.people.tests.engine.IEngineTestFrameworkObserver; public class UploadServerContactsTest extends InstrumentationTestCase implements IEngineTestFrameworkObserver { private static final String LOG_TAG = "UploadServerContactsTest"; private static final long MAX_PROCESSOR_TIME = 3000000; private static final long MAX_WAIT_FOR_REQ_ID = 5000; private static final int NO_OF_CONTACTS_TO_ADD = 55; private static final String NEW_DETAIL_VALUE = "0123456789"; private static final ContactDetail.DetailKeys NEW_DETAIL_KEY = ContactDetail.DetailKeys.VCARD_PHONE; private static final ContactDetail.DetailKeyTypes NEW_DETAIL_TYPE = ContactDetail.DetailKeyTypes.CELL; private static final String MOD_DETAIL_VALUE = ";Test;One"; private static final ContactDetail.DetailKeys MOD_DETAIL_KEY = ContactDetail.DetailKeys.VCARD_NAME; private static final ContactDetail.DetailKeyTypes MOD_DETAIL_TYPE = null; private static final long TEST_GROUP_1 = 860909; private static final long TEST_GROUP_2 = 860910; enum State { IDLE, ADD_CONTACT_LIST, MODIFY_CONTACT_LIST, DELETE_CONTACT_LIST, DELETE_CONTACT_DETAIL_LIST, ADD_NEW_GROUP_LIST, DELETE_GROUP_LIST } EngineTestFramework mEngineTester = null; MainApplication mApplication = null; DummyContactSyncEngine mEng = null; class UploadServerContactProcessorTest extends UploadServerContacts { public UploadServerContactProcessorTest(IContactSyncCallback callback, DatabaseHelper db) { super(callback, db); } public void testFetchContactChangeList(List<Contact> contactChangeList) { contactChangeList.clear(); contactChangeList.addAll(getContactChangeList()); } public void testFetchAddGroupLists(List<Long> contactIdList, List<GroupItem> groupList) { contactIdList.clear(); groupList.clear(); contactIdList.addAll(getContactIdList()); groupList.addAll(getGroupList()); } public void testFetchContactDeleteList(List<Long> contactIdList) { contactIdList.clear(); contactIdList.addAll(getContactIdList()); } public void testFetchContactDetailDeleteList(Contact deleteDetailContact) { android.os.Parcel _data = android.os.Parcel.obtain(); getDeleteDetailContact().writeToParcel(_data, 0); _data.setDataPosition(0); deleteDetailContact.readFromParcel(_data); } public Long testFetchDeleteGroupList(List<Long> contactIdList) { contactIdList.clear(); contactIdList.addAll(getContactIdList()); return getActiveGroupId(); } public int testGetPageSize() { return MAX_UP_PAGE_SIZE; } public void verifyNewContactsState() { assertEquals(InternalState.PROCESSING_NEW_CONTACTS, getInternalState()); } public void verifyModifyDetailsState() { assertEquals(InternalState.PROCESSING_MODIFIED_DETAILS, getInternalState()); } public void verifyDeleteContactsState() { assertEquals(InternalState.PROCESSING_DELETED_CONTACTS, getInternalState()); } public void verifyDeleteDetailsState() { assertEquals(InternalState.PROCESSING_DELETED_DETAILS, getInternalState()); } public void verifyGroupAddsState() { assertEquals(InternalState.PROCESSING_GROUP_ADDITIONS, getInternalState()); } public void verifyGroupDelsState() { assertEquals(InternalState.PROCESSING_GROUP_DELETIONS, getInternalState()); } }; UploadServerContactProcessorTest mProcessor; DatabaseHelper mDb = null; State mState = State.IDLE; Contact mReplyContact = null; int mInitialCount; int mInitialContactGroupCount; int mItemCount; boolean mBulkContactTest; TestModule mTestModule = new TestModule(); int mTestStep; @Override protected void setUp() throws Exception { super.setUp(); mApplication = (MainApplication)Instrumentation.newApplication(MainApplication.class, getInstrumentation().getTargetContext()); mApplication.onCreate(); mDb = mApplication.getDatabase(); mDb.removeUserData(); mEngineTester = new EngineTestFramework(this); mEng = new DummyContactSyncEngine(mEngineTester); mProcessor = new UploadServerContactProcessorTest(mEng, mApplication.getDatabase()); mEng.setProcessor(mProcessor); mEngineTester.setEngine(mEng); mState = State.IDLE; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); mBulkContactTest = false; } @Override protected void tearDown() throws Exception { // stop our dummy thread? mEngineTester.stopEventThread(); mEngineTester = null; mEng = null; SQLiteDatabase db = mDb.getReadableDatabase(); if (db.inTransaction()) { db.endTransaction(); } db.close(); super.tearDown(); } private void startSubTest(String function, String description) { Log.i(LOG_TAG, function + " - step " + mTestStep + ": " + description); mTestStep++; } private void runProcessor(int count, State state) { mInitialCount = count; nextState(state); mEng.mProcessorCompleteFlag = false; mProcessor.start(); ServiceStatus status = mEng.waitForProcessorComplete(MAX_PROCESSOR_TIME); assertEquals(ServiceStatus.SUCCESS, status); } private void nextState(State state) { mItemCount = mInitialCount; if (mItemCount == 0) { mState = State.IDLE; } else { mState = state; } } @Override public void reportBackToEngine(int reqId, EngineId engine) { Log.d(LOG_TAG, "reportBackToEngine"); ResponseQueue respQueue = ResponseQueue.getInstance(); List<BaseDataType> data = new ArrayList<BaseDataType>(); try { assertEquals(mEng.engineId(), engine); synchronized (mEng.mWaitForReqIdLock) { if (mEng.mActiveReqId == null || mEng.mActiveReqId.intValue() != reqId) { try { mEng.mWaitForReqIdLock.wait(MAX_WAIT_FOR_REQ_ID); } catch (InterruptedException e) { } assertEquals(Integer.valueOf(reqId), mEng.mActiveReqId); } } switch (mState) { case ADD_CONTACT_LIST: reportBackAddContactSuccess(reqId, data); break; case MODIFY_CONTACT_LIST: reportModifyContactSuccess(reqId, data); break; case DELETE_CONTACT_LIST: reportDeleteContactSuccess(reqId, data); break; case DELETE_CONTACT_DETAIL_LIST: reportDeleteContactDetailSuccess(reqId, data); break; case ADD_NEW_GROUP_LIST: reportBackAddGroupSuccess(reqId, data); break; case DELETE_GROUP_LIST: reportDeleteGroupListSuccess(reqId, data); break; default: fail("Unexpected request from processor"); } } catch (Throwable err) { - ServerError serverError = new ServerError(); - serverError.errorType = ServerError.ErrorTypes.INTERNALERROR.toString(); - serverError.errorValue = err + "\n"; + ServerError serverError = new ServerError(ServerError.ErrorType.INTERNALERROR); + serverError.errorDescription = err + "\n"; for (int i = 0; i < err.getStackTrace().length; i++) { StackTraceElement v = err.getStackTrace()[i]; - serverError.errorValue += "\t" + v + "\n"; + serverError.errorDescription += "\t" + v + "\n"; } - Log.e(LOG_TAG, "Exception:\n" + serverError.errorValue); + Log.e(LOG_TAG, "Exception:\n" + serverError.errorDescription); data.clear(); data.add(serverError); } respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); Log.d(LOG_TAG, "reportBackToEngine - message added to response queue"); } private void reportBackAddContactSuccess(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackAddContactSuccess"); mProcessor.verifyNewContactsState(); List<Contact> contactChangeList = new ArrayList<Contact>(); mProcessor.testFetchContactChangeList(contactChangeList); assertEquals(Math.min(mItemCount, mProcessor.testGetPageSize()), contactChangeList.size()); ContactChanges contactChanges = new ContactChanges(); contactChanges.mServerRevisionAfter = 1; contactChanges.mServerRevisionBefore = 0; data.add(contactChanges); for (int i = 0; i < contactChangeList.size(); i++) { Contact actualContact = contactChangeList.get(i); Contact expectedContact = new Contact(); ServiceStatus status = mDb.fetchContact(actualContact.localContactID, expectedContact); assertEquals(ServiceStatus.SUCCESS, status); assertEquals(expectedContact.details.size(), actualContact.details.size()); assertEquals(null, actualContact.aboutMe); assertEquals(null, actualContact.profilePath); assertEquals(null, actualContact.contactID); assertEquals(null, actualContact.deleted); assertEquals(null, actualContact.friendOfMine); assertEquals(null, actualContact.gender); assertEquals(null, actualContact.groupList); assertEquals(null, actualContact.sources); assertEquals(expectedContact.synctophone, actualContact.synctophone); assertEquals(null, actualContact.updated); assertEquals(null, actualContact.userID); final ListIterator<ContactDetail> itActDetails = actualContact.details.listIterator(); for (ContactDetail expDetail : expectedContact.details) { ContactDetail actDetail = itActDetails.next(); assertTrue(DatabaseHelper.doDetailsMatch(expDetail, actDetail)); assertFalse(DatabaseHelper.hasDetailChanged(expDetail, actDetail)); } generateReplyContact(expectedContact); contactChanges.mContacts.add(mReplyContact); } mItemCount -= contactChangeList.size(); assertTrue(mItemCount >= 0); if (mItemCount == 0) { mInitialCount = mInitialContactGroupCount; nextState(State.ADD_NEW_GROUP_LIST); } } private void reportBackAddGroupSuccess(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackAddGroupSuccess"); mProcessor.verifyGroupAddsState(); final List<Long> contactIdList = new ArrayList<Long>(); final List<GroupItem> groupList = new ArrayList<GroupItem>(); mProcessor.testFetchAddGroupLists(contactIdList, groupList); assertEquals(1, groupList.size()); Long activeGroupId = groupList.get(0).mId; assertTrue(activeGroupId != null); ItemList itemList = new ItemList(ItemList.Type.contact_group_relations); data.add(itemList); for (Long contactServerId : contactIdList) { Contact expectedContact = new Contact(); ServiceStatus status = mDb.fetchContactByServerId(contactServerId, expectedContact); assertEquals(ServiceStatus.SUCCESS, status); boolean found = false; for (Long groupId : expectedContact.groupList) { if (groupId.equals(activeGroupId)) { found = true; break; } } assertTrue("Contact " + contactServerId + " has been added to group " + activeGroupId + " which is not in the database", found); mItemCount--; } Log.i(LOG_TAG, "Groups/contacts remaining = " + mItemCount); assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportModifyContactSuccess(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportModifyContactSuccess"); mProcessor.verifyModifyDetailsState(); List<Contact> contactChangeList = new ArrayList<Contact>(); mProcessor.testFetchContactChangeList(contactChangeList); assertEquals(Math.min(mItemCount, mProcessor.testGetPageSize()), contactChangeList.size()); ContactChanges contactChanges = new ContactChanges(); contactChanges.mServerRevisionAfter = 1; contactChanges.mServerRevisionBefore = 0; data.add(contactChanges); for (int i = 0; i < contactChangeList.size(); i++) { Contact actualContact = contactChangeList.get(i); assertTrue(actualContact.contactID != null); assertEquals(null, actualContact.aboutMe); assertEquals(null, actualContact.profilePath); assertEquals(null, actualContact.deleted); assertEquals(null, actualContact.friendOfMine); assertEquals(null, actualContact.gender); assertEquals(null, actualContact.groupList); assertEquals(null, actualContact.sources); assertEquals(null, actualContact.synctophone); assertEquals(null, actualContact.updated); assertEquals(null, actualContact.userID); assertEquals(2, actualContact.details.size()); ContactDetail modDetail = actualContact.details.get(0); // Modified // detail // always // first ContactDetail newDetail = actualContact.details.get(1); assertEquals(NEW_DETAIL_VALUE, newDetail.value); assertEquals(NEW_DETAIL_KEY, newDetail.key); assertEquals(NEW_DETAIL_TYPE, newDetail.keyType); assertEquals(MOD_DETAIL_VALUE, modDetail.value); assertEquals(MOD_DETAIL_KEY, modDetail.key); assertEquals(MOD_DETAIL_TYPE, modDetail.keyType); mReplyContact = new Contact(); mReplyContact.contactID = actualContact.contactID; mReplyContact.userID = generateTestUserID(mReplyContact.contactID); ContactDetail replyDetail1 = new ContactDetail(); ContactDetail replyDetail2 = new ContactDetail(); replyDetail1.key = modDetail.key; replyDetail1.unique_id = modDetail.unique_id; replyDetail2.key = newDetail.key; replyDetail2.unique_id = newDetail.localDetailID + 2; mReplyContact.details.add(replyDetail1); mReplyContact.details.add(replyDetail2); contactChanges.mContacts.add(mReplyContact); } mItemCount -= contactChangeList.size(); assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportDeleteContactSuccess(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportDeleteContactSuccess"); mProcessor.verifyDeleteContactsState(); List<Long> contactIdList = new ArrayList<Long>(); mProcessor.testFetchContactDeleteList(contactIdList); assertEquals(Math.min(mItemCount, mProcessor.testGetPageSize()), contactIdList.size()); ContactListResponse contactListResponse = new ContactListResponse(); contactListResponse.mServerRevisionAfter = 1; contactListResponse.mServerRevisionBefore = 0; data.add(contactListResponse); contactListResponse.mContactIdList = new ArrayList<Integer>(); for (Long serverID : contactIdList) { assertTrue(serverID != null); contactListResponse.mContactIdList.add(Integer.valueOf(serverID.intValue())); } mItemCount -= contactIdList.size(); assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportDeleteContactDetailSuccess(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportDeleteContactDetailSuccess"); mProcessor.verifyDeleteDetailsState(); Contact contact = new Contact(); mProcessor.testFetchContactDetailDeleteList(contact); assertEquals(2, contact.details.size()); assertEquals(ContactDetail.DetailKeys.VCARD_NAME, contact.details.get(0).key); assertEquals(ContactDetail.DetailKeys.VCARD_PHONE, contact.details.get(1).key); ContactDetailDeletion contactDetailDeletion = new ContactDetailDeletion(); contactDetailDeletion.mServerVersionAfter = 1; contactDetailDeletion.mServerVersionBefore = 0; data.add(contactDetailDeletion); contactDetailDeletion.mContactId = contact.contactID.intValue(); contactDetailDeletion.mDetails = new ArrayList<ContactDetail>(); for (ContactDetail detail : contact.details) { ContactDetail tempDetail = new ContactDetail(); tempDetail.key = detail.key; tempDetail.unique_id = detail.unique_id; contactDetailDeletion.mDetails.add(tempDetail); } mItemCount--; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportDeleteGroupListSuccess(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportDeleteGroupListSuccess"); mProcessor.verifyGroupDelsState(); final List<Long> contactIdList = new ArrayList<Long>(); Long activeGroupId = mProcessor.testFetchDeleteGroupList(contactIdList); if (mItemCount == 1) { assertEquals(Long.valueOf(TEST_GROUP_2), activeGroupId); } else if (mItemCount == 2) { assertEquals(Long.valueOf(TEST_GROUP_1), activeGroupId); } else { fail("Unexpected number of groups in delete group list"); } StatusMsg statusMsg = new StatusMsg(); statusMsg.mStatus = true; data.add(statusMsg); mItemCount--; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private Long generateTestUserID(Long contactID) { if (contactID == null) { return null; } if ((contactID & 15) == 0) { return null; } return contactID + 5; } private void generateReplyContact(Contact expContact) { mReplyContact = new Contact(); mReplyContact.contactID = expContact.localContactID + 1; if ((expContact.localContactID & 15) != 0) { mReplyContact.userID = expContact.localContactID + 2; } for (ContactDetail detail : expContact.details) { ContactDetail newDetail = new ContactDetail(); generateReplyDetail(newDetail, detail); mReplyContact.details.add(newDetail); } } private void generateReplyDetail(ContactDetail replyDetail, ContactDetail expDetail) { replyDetail.key = expDetail.key; switch (replyDetail.key) { case VCARD_NAME: case VCARD_NICKNAME: case VCARD_DATE: case VCARD_TITLE: case PRESENCE_TEXT: case PHOTO: case LOCATION: break; default: replyDetail.unique_id = expDetail.localDetailID + 3; break; } } @Override public void onEngineException(Exception e) { mEng.onProcessorComplete(ServiceStatus.ERROR_UNKNOWN, "", e); } @SmallTest @Suppress // Breaks tests public void testRunWithNoContactChanges() { final String fnName = "testRunWithNoContactChanges"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking change list is empty"); long noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Running processor"); mProcessor.start(); ServiceStatus status = mEng.waitForProcessorComplete(MAX_PROCESSOR_TIME); assertEquals(ServiceStatus.SUCCESS, status); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests public void testRunWithNewContactChange() { final String fnName = "testRunWithNewContactChange"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking change list is empty"); long noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Adding test contact to database"); Contact contact = mTestModule.createDummyContactData(); ServiceStatus status = mDb.addContact(contact); assertEquals(ServiceStatus.SUCCESS, status); mInitialContactGroupCount = contact.groupList.size(); startSubTest(fnName, "Running processor"); runProcessor(1, State.ADD_CONTACT_LIST); startSubTest(fnName, "Fetching contact after sync"); Contact syncContact = mTestModule.createDummyContactData(); status = mDb.fetchContact(contact.localContactID, syncContact); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Check contact server ID is correct"); assertEquals(syncContact.contactID, mReplyContact.contactID); startSubTest(fnName, "Check detail server IDs are correct"); final ListIterator<ContactDetail> itReplyDetails = mReplyContact.details.listIterator(); for (ContactDetail syncDetail : syncContact.details) { ContactDetail replyDetail = itReplyDetails.next(); assertEquals(replyDetail.key, syncDetail.key); assertEquals(replyDetail.unique_id, syncDetail.unique_id); } noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); assertEquals(State.IDLE, mState); startSubTest(fnName, "Running processor with no contact changes"); runProcessor(0, State.IDLE); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests public void testRunWithDetailChanges() { final String fnName = "testRunWithDetailChanges"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking change list is empty"); long noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Adding test contact to database"); Contact contact = mTestModule.createDummyContactData(); contact.contactID = TestModule.generateRandomLong(); contact.userID = generateTestUserID(contact.contactID); List<Contact> contactList = new ArrayList<Contact>(); contactList.add(contact); ServiceStatus status = mDb.syncAddContactList(contactList, false, false); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Adding new detail to contact"); ContactDetail newDetail = new ContactDetail(); newDetail.value = NEW_DETAIL_VALUE; newDetail.key = NEW_DETAIL_KEY; newDetail.keyType = NEW_DETAIL_TYPE; newDetail.localContactID = contact.localContactID; status = mDb.addContactDetail(newDetail); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Modifying detail in contact"); ContactDetail modDetail = contact.details.get(0); modDetail.value = MOD_DETAIL_VALUE; modDetail.key = MOD_DETAIL_KEY; modDetail.keyType = MOD_DETAIL_TYPE; status = mDb.modifyContactDetail(modDetail); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Running processor"); runProcessor(1, State.MODIFY_CONTACT_LIST); startSubTest(fnName, "Fetching detail after sync"); Contact syncContact = new Contact(); status = mDb.fetchContact(contact.localContactID, syncContact); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Check contact server ID is correct"); boolean done = false; for (ContactDetail detail : syncContact.details) { if (detail.localDetailID.equals(newDetail.localDetailID)) { assertEquals(detail.unique_id, Long.valueOf(detail.localDetailID + 2)); done = true; break; } } assertTrue(done); assertEquals(syncContact.contactID, mReplyContact.contactID); assertEquals(syncContact.userID, mReplyContact.userID); assertEquals(State.IDLE, mState); noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Running processor with no contact changes"); runProcessor(0, State.IDLE); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests public void testRunWithContactDeletion() { final String fnName = "testRunWithContactDeletion"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking change list is empty"); long noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Adding test contact to database - no sync"); Contact contact = mTestModule.createDummyContactData(); contact.contactID = TestModule.generateRandomLong(); contact.userID = generateTestUserID(contact.contactID); List<Contact> contactList = new ArrayList<Contact>(); contactList.add(contact); ServiceStatus status = mDb.syncAddContactList(contactList, false, false); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Deleting contact"); status = mDb.deleteContact(contact.localContactID); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Running processor"); runProcessor(1, State.DELETE_CONTACT_LIST); assertEquals(State.IDLE, mState); startSubTest(fnName, "Checking change list is empty"); noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Running processor with no contact changes"); runProcessor(0, State.IDLE); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests public void testRunWithContactDetailDeletion() { final String fnName = "testRunWithContactDetailDeletion"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking change list is empty"); long noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Adding test contact to database - no sync"); Contact contact = mTestModule.createDummyContactData(); contact.contactID = TestModule.generateRandomLong(); contact.userID = generateTestUserID(contact.contactID); List<Contact> contactList = new ArrayList<Contact>(); contactList.add(contact); ServiceStatus status = mDb.syncAddContactList(contactList, false, false); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Adding test contact detail to database - no sync"); ContactDetail detail = new ContactDetail(); detail.value = NEW_DETAIL_VALUE; detail.key = ContactDetail.DetailKeys.VCARD_PHONE; detail.keyType = ContactDetail.DetailKeyTypes.CELL; detail.localContactID = contact.localContactID; diff --git a/tests/src/com/vodafone360/people/tests/service/PeopleServiceTest.java b/tests/src/com/vodafone360/people/tests/service/PeopleServiceTest.java index c1687c0..eeb688c 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.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.fetchAvailableIdentities(filter); + 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.fetchMyIdentities(filter); + 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(); - se1.errorValue = "Test error produced by test framework, ignore it"; - se1.errorType = "INTERNALERROR"; + ServerError se1 = new ServerError(ServerError.ErrorType.INTERNALERROR); + se1.errorDescription = "Test error produced by test framework, ignore it"; data.add(se1); respQueue.addToResponseQueue(reqId, data, engine); } } \ No newline at end of file diff --git a/tests/src/com/vodafone360/people/tests/service/utils/TimeOutWatcherTest.java b/tests/src/com/vodafone360/people/tests/service/utils/TimeOutWatcherTest.java index 06608c7..fcab75e 100644 --- a/tests/src/com/vodafone360/people/tests/service/utils/TimeOutWatcherTest.java +++ b/tests/src/com/vodafone360/people/tests/service/utils/TimeOutWatcherTest.java @@ -1,299 +1,299 @@ /* * 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.utils; import android.app.Instrumentation; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import com.vodafone360.people.MainApplication; import com.vodafone360.people.datatypes.BaseDataType; 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.Response; import com.vodafone360.people.service.utils.TimeOutWatcher; /** * JUnit tests for the TimeOutWatcher class. */ public class TimeOutWatcherTest extends InstrumentationTestCase { private final static long TIMEOUT_2000_MS = 2000; private final static long TIMEOUT_10000_MS = 10000; private TimeOutWatcher mWatcher = null; private MainApplication mApplication; protected void setUp() throws Exception { super.setUp(); mApplication = (MainApplication)Instrumentation.newApplication(MainApplication.class, getInstrumentation().getTargetContext()); mApplication.onCreate(); mWatcher = new TimeOutWatcher(); } protected void tearDown() throws Exception { mWatcher.kill(); super.tearDown(); } /** * Tests adding and removing requests with different cases: * -same expiry dates * -increasing dates * -decreasing dates */ public void testAddingAndRemovingRequests() { Log.i("testAddingAndRemovingRequests()", "-begin"); Request[] requests = new Request[10]; assertEquals(0, mWatcher.getRequestsCount()); // requests with same expiry date Log.i("testAddingAndRemovingRequests()", "-checking requests with same expiry date"); for(int i = 0; i < requests.length; i++) { requests[i] = createRequestWithTimeout(TIMEOUT_2000_MS); requests[i].calculateExpiryDate(); mWatcher.addRequest(requests[i]); } assertEquals(requests.length, mWatcher.getRequestsCount()); assertTrue(compareRequestArraysIdentical(requests, mWatcher.getRequestsArray())); for(int i = 0; i < requests.length; i++) { mWatcher.removeRequest(requests[i]); } assertEquals(0, mWatcher.getRequestsCount()); Log.i("testAddingAndRemovingRequests()", "-checking requests that don't wake up the thread each time they are added (but wake up the thread when removed with the same order)"); for(int i = 0; i < requests.length; i++) { requests[i] = createRequestWithTimeout(TIMEOUT_10000_MS * (i+1)); requests[i].calculateExpiryDate(); mWatcher.addRequest(requests[i]); } assertEquals(requests.length, mWatcher.getRequestsCount()); assertTrue(compareRequestArraysIdentical(requests, mWatcher.getRequestsArray())); for(int i = 0; i < requests.length; i++) { mWatcher.removeRequest(requests[i]); } assertEquals(0, mWatcher.getRequestsCount()); Log.i("testAddingAndRemovingRequests()", "-checking requests that wake up the thread each time they are added (but don't wake up the thread when removed with the same order"); for(int i = 0; i < requests.length; i++) { requests[i] = createRequestWithTimeout(TIMEOUT_10000_MS * (requests.length-i)); requests[i].calculateExpiryDate(); mWatcher.addRequest(requests[i]); } assertEquals(requests.length, mWatcher.getRequestsCount()); assertTrue(compareRequestArraysSameContent(requests, mWatcher.getRequestsArray())); for(int i = 0; i < requests.length; i++) { mWatcher.removeRequest(requests[i]); } assertEquals(0, mWatcher.getRequestsCount()); Log.i("testAddingAndRemovingRequests()", "-end"); } /** * Tests the invalidateAllRequests() method. */ @Suppress public void testTimingOutAllRequests() { Log.i("testTimingOutAllRequests()", "-begin"); Request[] requests = new Request[10]; assertEquals(0, QueueManager.getInstance().getRequestTimeoutWatcher().getRequestsCount()); for(int i = 0; i < requests.length; i++) { requests[i] = createRequestWithTimeout(TIMEOUT_2000_MS); QueueManager.getInstance().addRequest(requests[i]); } assertEquals(requests.length, QueueManager.getInstance().getRequestTimeoutWatcher().getRequestsCount()); assertTrue(compareRequestArraysIdentical(requests, QueueManager.getInstance().getRequestTimeoutWatcher().getRequestsArray())); QueueManager.getInstance().getRequestTimeoutWatcher().invalidateAllRequests(); assertEquals(0, QueueManager.getInstance().getRequestTimeoutWatcher().getRequestsCount()); Log.i("testTimingOutAllRequests()", "-end"); } /** * Tests that when requests are added, they are stored in an ascending ordered list. */ public void testRequestsAreSorted() { Log.i("testRequestsAreSorted()", "-begin"); assertEquals(0, mWatcher.getRequestsCount()); final int[] order = { 7, 10, 9, 6, 2, 8, 1, 5, 3, 4 }; // add the requests with following timeout order: 7, 10, 9, 6, 2, 8, 1, 5, 3, 4 for (int i = 0; i < order.length; i++) { final Request request = createRequestWithTimeout(TIMEOUT_10000_MS * order[i]); request.calculateExpiryDate(); mWatcher.addRequest(request); } final Request[] requests = mWatcher.getRequestsArray(); assertEquals(order.length, requests.length); // check that the requests are given back in the ascending order: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 for (int i = 0; i < requests.length; i++) { final Request request = requests[i]; assertEquals((i+1), request.getTimeout() / TIMEOUT_10000_MS); } Log.i("testRequestsAreSorted()", "-end"); } /** * Tests that a timeout error is thrown if the response of the request has not been received after the timeout period. */ @Suppress public void testThrowingTimeout() { Log.i("testThrowingTimeout()", "-begin"); final Request request = createRequestWithTimeout(TIMEOUT_2000_MS); // check that the response queue is empty for the engine with EngineId.UNDEFINED id (we use this one for the test) Response response = ResponseQueue.getInstance().getNextResponse(EngineId.UNDEFINED); assertNull(response); // adding the request to the queue should add it to the TimeOutWatcher final int reqId = QueueManager.getInstance().addRequest(request); // check that the response queue is still empty response = ResponseQueue.getInstance().getNextResponse(EngineId.UNDEFINED); assertNull(response); // let's give at least 2 times the timeout to the system before checking long stopTime = System.currentTimeMillis() + (TIMEOUT_2000_MS * 2); while (System.currentTimeMillis() < stopTime) { try { Thread.sleep(TIMEOUT_2000_MS); } catch(InterruptedException ie) { Log.i("testThrowingTimeout()", "Error while sleeping: "+ie); } } // check that the response is still empty response = ResponseQueue.getInstance().getNextResponse(EngineId.UNDEFINED); assertNotNull(response); // check response request id is the same as the request id assertEquals(reqId, response.mReqId.intValue()); // check the timeout error returned is as expected assertNotNull(response.mDataTypes); assertEquals(1, response.mDataTypes.size()); BaseDataType error = response.mDataTypes.get(0); assertTrue(error instanceof ServerError); ServerError srvError = (ServerError)error; - assertEquals(ServerError.ErrorTypes.REQUEST_TIMEOUT, srvError.getType()); + assertEquals(ServerError.ErrorType.REQUEST_TIMEOUT, srvError.getType()); Log.i("testThrowingTimeout()", "-end"); } //////////////////// // HELPER METHODS // //////////////////// /** * Creates a request for the "undefined" engine. * @param timeout the timeout for the request in milliseconds */ private Request createRequestWithTimeout(long timeout) { final Request request = new Request("", Type.PRESENCE_LIST, EngineId.UNDEFINED, false, timeout); request.setActive(true); return request; } /** * Checks if two arrays are exactly the same. * @param array1 the first array to compare * @param array2 the second array to compare * @return true if identical, false otherwise */ private boolean compareRequestArraysIdentical(Request[] array1, Request[] array2) { if (array1 == null || array2 == null) { throw new NullPointerException(); } if (array1.length != array2.length) { return false; } for (int i = 0; i < array1.length; i++) { if (array1[i] != array2[i]) { return false; } } return true; } /** * Checks if two arrays have the same content but not necessarily in the same order. * @param array1 the first array to compare * @param array2 the second array to compare * @return true if both arrays have the same content, false otherwise */ private boolean compareRequestArraysSameContent(Request[] array1, Request[] array2) { if (array1 == null || array2 == null) { throw new NullPointerException(); } if (array1.length != array2.length) { return false; } int count; for (int i = 0; i < array1.length; i++) { count = 0; for (int j = 0; j < array1.length; j++) { if (array1[i] == array2[j]) { count++; // more than one if (count > 1) return false; } } // none if (count == 0) return false; } // arrays contain the same requests return true; } }
360/360-Engine-for-Android
03d542b24b311dacc187ac5ec81f3fb2f4a1c055
added ui pushes for uncached identities. readded loading progress bar. caching of identities now works. committed fixes to keep client with old ui running.
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index a50990e..61f941e 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,713 +1,748 @@ /* * 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.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.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_CAPABILITY_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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; 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; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; + public static final String KEY_AVAILABLE_IDS = "availableids"; + 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(); } HttpConnectionThread.logE("getAvailableThirdPartyIdentities", mAvailableIdentityList.toString(), null); 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(); } HttpConnectionThread.logE("IE.getMyThirdPartyIdentities", mMyIdentityList.toString(), null); 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>(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < mMyIdentityList.size(); 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 iCapability = new IdentityCapability(); iCapability.mCapability = IdentityCapability.CapabilityID.chat; iCapability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(iCapability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = "mobile"; 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())); } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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: // changed the method called // startSetIdentityCapabilityStatus(data); 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_CAPABILITY_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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { 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: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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) { HttpConnectionThread.logE("IE.handleGetAvailableIdentitiesResponse", "", null); 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) { HttpConnectionThread.logE("handleGetMyIdentitiesResponse", "", null); 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); HttpConnectionThread.logE("Identity: ", ((Identity)item).toString(), null); } } } + 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 handleSetIdentityCapabilityStatus(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, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } }
360/360-Engine-for-Android
b84f56c2cbf2abe6be362e359bd8d6505c4406bc
- cached identities now working 90% - synchronization of getters of identities in IdentityEngine - fixed methods that would give wrong identity back - refactored Identity-class to use primitive data types instead of complex
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/datatypes/Identity.java b/src/com/vodafone360/people/datatypes/Identity.java index 46bc01e..9ab2aaf 100644 --- a/src/com/vodafone360/people/datatypes/Identity.java +++ b/src/com/vodafone360/people/datatypes/Identity.java @@ -1,614 +1,612 @@ /* * 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.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Vector; import android.os.Parcel; import android.os.Parcelable; import com.vodafone360.people.utils.LogUtils; /** * BaseDataType encapsulating an Identity issued to or retrieved from server */ public class Identity extends BaseDataType implements Parcelable { /** * Tags associated with Identity item. */ private enum Tags { IDENTITY_MAIN_TAG("availableidentity"), IDENTITY_CAPABILITY_LIST("identitycapabilitylist"), PLUGIN_ID("pluginid"), NETWORK_URL("networkurl"), AUTH_TYPE("authtype"), ICON_MIME("iconmime"), ICON2_MIME("icon2mime"), ORDER("order"), NAME("name"), ICON_URL("iconurl"), ICON2_URL("icon2url"), NETWORK("network"), // Properties below are only present after // GetMyIdentities. ACTIVE("active"), CREATED("created"), IDENTITY_ID("identityid"), UPDATED("updated"), IDENTITY_TYPE("identitytype"), USER_ID("userid"), USER_NAME("username"), DISPLAY_NAME("displayname"), COUNTRY_LIST("countrylist"); private final String tag; /** * Construct Tags item from supplied String * * @param s String value for Tags item. */ private Tags(String s) { tag = s; } /** * String value for 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 in Tags items. * @return Tags item for specified String, NULL otherwise. */ private static Tags findTag(String tag) { for (Tags tags : Tags.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } return null; } } - public String mPluginId = null; + public String mPluginId; - public String mNetwork = null; + public String mNetwork; - public URL mNetworkUrl = null; + public URL mNetworkUrl; - public URL mIconUrl = null; + public URL mIconUrl; - public URL mIcon2Url = null; + public URL mIcon2Url; public String mAuthType; - public String mIconMime = null; + public String mIconMime; - public Integer mOrder = null; + public int mOrder; - public String mName = null; + public String mName; - public List<IdentityCapability> mCapabilities = null; + public List<IdentityCapability> mCapabilities; /** Properties below are only present after GetMyIdentities. */ - public Boolean mActive = null; + public boolean mActive; - public Long mCreated = null; + public long mCreated; - public Long mUpdated = null; + public long mUpdated; - public String mIdentityId = null; + public String mIdentityId; - public Integer mUserId = null; + public int mUserId; - public String mUserName = null; + public String mUserName; - public String mDisplayName = null; + public String mDisplayName; - public List<String> mCountryList = null; + public List<String> mCountryList; - public String mIdentityType = null; + public String mIdentityType; private int mType; /** * Comparator class used to compare Identities retrieved from server to * remove duplicates from list passed to People client UI. */ public static class IdentityComparator implements Comparator<Identity> { @Override public int compare(Identity object1, Identity object2) { - return object1.mOrder.compareTo(object2.mOrder); + return new Integer(object1.mOrder).compareTo(new Integer(object2.mOrder)); } } /** * Test whether current Identity is identical to supplied Identity. * * @param id Identity to compare against. * @return true if Identities match, false otherwise. */ public boolean isSameAs(Identity id) { boolean isSame = true; if (!areStringValuesSame(mPluginId, id.mPluginId) || !areStringValuesSame(mNetwork, id.mNetwork) || !areStringValuesSame(mIdentityId, id.mIdentityId) || !areStringValuesSame(mDisplayName, id.mDisplayName)) { isSame = false; } if (mNetworkUrl != null && id.mNetworkUrl != null) { if (!mNetworkUrl.sameFile(id.mNetworkUrl)) { isSame = false; } } else if (mNetworkUrl == null && id.mNetworkUrl == null) { // Do nothing. } else { isSame = false; } if (mIconUrl != null && id.mIconUrl != null) { if (!mIconUrl.sameFile(id.mIconUrl)) { isSame = false; } } else if (mIconUrl == null && id.mIconUrl == null) { // Do nothing. } else { isSame = false; } return isSame; } /** * String values comparison * * @param s1 First String to test. * @param s2 Second String to test. * @return true if Strings match (or both are null), false otherwise. */ private boolean areStringValuesSame(String s1, String s2) { boolean isSame = true; if (s1 == null && s2 == null) { // Do nothing. } else if (s1 != null && s2 != null) { if (s1.compareTo(s2) != 0) { isSame = false; } } else { isSame = false; } return isSame; } /** * Default constructor. */ public Identity() { // Do nothing. } public Identity(int type) { mType = type; } /** * Create Identity from Parcel. * * @param in Parcel containing Identity. */ private Identity(Parcel in) { readFromParcel(in); } /** {@inheritDoc} */ - @Override + @Override public int getType() { - // TODO: Return appropriate type if its - // an available identity instead of my identity - return MY_IDENTITY_DATA_TYPE; + return mType; } /** * Populate Identity from supplied Hashtable. * * @param hash Hashtable containing identity details. * @return Identity instance. */ public Identity createFromHashtable(Hashtable<String, Object> hash) { Enumeration<String> e = hash.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); Object value = hash.get(key); Tags tag = Tags.findTag(key); if (tag != null) setValue(tag, value); } 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 val) { switch (tag) { case AUTH_TYPE: mAuthType = (String)val; break; case ICON_MIME: mIconMime = (String)val; break; case ICON2_MIME: // TODO: Remove TAG value? // mIcon2Mime = (String)val; break; case ICON_URL: try { mIconUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIconUrl = null; } break; case ICON2_URL: try { mIcon2Url = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIcon2Url = null; } break; case IDENTITY_CAPABILITY_LIST: /** Create id capability list. */ @SuppressWarnings("unchecked") Vector<Hashtable<String, Object>> v = (Vector<Hashtable<String, Object>>)val; if (mCapabilities == null) { mCapabilities = new ArrayList<IdentityCapability>(); } for (Hashtable<String, Object> obj : v) { IdentityCapability cap = new IdentityCapability(); cap.createFromHashtable(obj); mCapabilities.add(cap); } break; case IDENTITY_MAIN_TAG: // Not currently handled. break; case NAME: mName = (String)val; break; case NETWORK: mNetwork = (String)val; break; case NETWORK_URL: try { mNetworkUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong network url: '" + val + "'"); mNetworkUrl = null; } break; case ORDER: mOrder = (Integer)val; break; case PLUGIN_ID: mPluginId = (String)val; break; case ACTIVE: mActive = (Boolean)val; break; case CREATED: mCreated = (Long)val; break; case DISPLAY_NAME: mDisplayName = (String)val; break; case IDENTITY_ID: mIdentityId = (String)val; break; case IDENTITY_TYPE: mIdentityType = (String)val; break; case UPDATED: mUpdated = (Long)val; break; case USER_ID: mUserId = ((Long)val).intValue(); break; case USER_NAME: mUserName = (String)val; break; case COUNTRY_LIST: if (mCountryList == null) { mCountryList = new ArrayList<String>(); } break; default: // Do nothing. break; } } /** {@inheritDoc} */ @Override public String toString() { final StringBuffer sb = new StringBuffer("Name:"); sb.append(mName); sb.append("\nPluginID:"); sb.append(mPluginId); sb.append("\nNetwork:"); sb.append(mNetwork); sb.append("\nNetworkURL:"); sb.append(mNetworkUrl); sb.append("\nAuthType:"); sb.append(mAuthType); sb.append("\nIcon mime:"); sb.append(mIconMime); sb.append("\nIconURL:"); sb.append(mIconUrl); sb.append("\nOrder:"); sb.append(mOrder); sb.append("\nActive:"); sb.append(mActive); sb.append("\nCreated:"); sb.append(mCreated); sb.append("\nUpdated:"); sb.append(mUpdated); sb.append("\nIdentityId:"); sb.append(mIdentityId); sb.append("\nUserId:"); sb.append(mUserId); sb.append("\nUserName:"); sb.append(mUserName); sb.append("\nDisplayName:"); sb.append(mDisplayName); sb.append("\nIdentityType:"); sb.append(mIdentityType); if (mCountryList != null) { sb.append("\nCountry List: ("); sb.append(mCountryList.size()); sb.append(") = ["); for (int i = 0; i < mCountryList.size(); i++) { sb.append(mCountryList.get(i)); if (i < mCountryList.size() - 1) sb.append(", "); } sb.append("]"); } if (mCapabilities != null) { sb.append("\nCapabilities ("); sb.append(mCapabilities.size()); sb.append(")"); for (int i = 0; i < mCapabilities.size(); i++) { sb.append("\n" + mCapabilities.get(i).toString()); if (i < mCapabilities.size() - 1) { sb.append("\n\t---"); } } } return sb.toString(); } /** {@inheritDoc} */ @Override public int describeContents() { return 1; } /** * Enumeration containing items contained within Identity Parcel. */ private enum MemberData { PLUGIN_ID, NETWORK, NETWORK_URL, ICON_URL, AUTH_TYPE, ICON_MIME, ORDER, NAME; } /** * Read Identity item from Parcel. * * @param in Parcel containing Identity information. */ private void readFromParcel(Parcel in) { mPluginId = null; mNetwork = null; mNetworkUrl = null; mIconUrl = null; mAuthType = null; mIconMime = null; - mOrder = null; + mOrder = -1; mName = null; mCapabilities = null; boolean[] validDataList = new boolean[MemberData.values().length]; in.readBooleanArray(validDataList); if (validDataList[MemberData.PLUGIN_ID.ordinal()]) { mPluginId = in.readString(); } if (validDataList[MemberData.NETWORK.ordinal()]) { mNetwork = in.readString(); } if (validDataList[MemberData.NETWORK_URL.ordinal()]) { try { mNetworkUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.NETWORK_URL"); } } if (validDataList[MemberData.ICON_URL.ordinal()]) { try { mIconUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.ICON_URL"); } } if (validDataList[MemberData.AUTH_TYPE.ordinal()]) { mAuthType = in.readString(); } if (validDataList[MemberData.ICON_MIME.ordinal()]) { mIconMime = in.readString(); } if (validDataList[MemberData.ORDER.ordinal()]) { mOrder = in.readInt(); } if (validDataList[MemberData.NAME.ordinal()]) { mName = in.readString(); } int noOfCapabilities = in.readInt(); if (noOfCapabilities > 0) { mCapabilities = new ArrayList<IdentityCapability>(noOfCapabilities); for (int i = 0; i < noOfCapabilities; i++) { IdentityCapability cap = IdentityCapability.CREATOR.createFromParcel(in); mCapabilities.add(cap); } } } /** {@inheritDoc} */ @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 (mPluginId != null) { validDataList[MemberData.PLUGIN_ID.ordinal()] = true; dest.writeString(mPluginId); } if (mNetwork != null) { validDataList[MemberData.NETWORK.ordinal()] = true; dest.writeString(mNetwork); } if (mNetworkUrl != null) { validDataList[MemberData.NETWORK_URL.ordinal()] = true; dest.writeString(mNetworkUrl.toString()); } if (mIconUrl != null) { validDataList[MemberData.ICON_URL.ordinal()] = true; dest.writeString(mIconUrl.toString()); } if (mAuthType != null) { validDataList[MemberData.AUTH_TYPE.ordinal()] = true; dest.writeString(mAuthType); } if (mIconMime != null) { validDataList[MemberData.ICON_MIME.ordinal()] = true; dest.writeString(mIconMime); } - if (mOrder != null) { + if (mOrder != -1) { validDataList[MemberData.ORDER.ordinal()] = true; dest.writeInt(mOrder); } if (mName != null) { validDataList[MemberData.NAME.ordinal()] = true; dest.writeString(mName); } if (mCapabilities != null) { dest.writeInt(mCapabilities.size()); for (IdentityCapability cap : mCapabilities) { cap.writeToParcel(dest, 0); } } else { dest.writeInt(0); } int currentPos = dest.dataPosition(); dest.setDataPosition(validDataPos); dest.writeBooleanArray(validDataList); // Real array. dest.setDataPosition(currentPos); } /** Interface to allow Identity to be written and restored from a Parcel. */ public static final Parcelable.Creator<Identity> CREATOR = new Parcelable.Creator<Identity>() { public Identity createFromParcel(Parcel in) { return new Identity(in); } public Identity[] newArray(int size) { return new Identity[size]; } }; } diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 6c78677..a50990e 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,793 +1,713 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { - // private String mNetwork; - // private String mIdentityId; - // private Map<String, Object> mStatus = null; - // - // /** - // * Supply filter containing required capabilities. - // * @param filter Bundle containing capabilities filter. - // */ - // public void setCapabilityStatus(Bundle filter){ - // mStatus = prepareBoolFilter(filter); - // } - // } - /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; 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; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; /** * 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 ((mMyIdentityList.size() == 0) && ( + if ((mAvailableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } + HttpConnectionThread.logE("getAvailableThirdPartyIdentities", mAvailableIdentityList.toString(), null); + 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(); } + HttpConnectionThread.logE("IE.getMyThirdPartyIdentities", mMyIdentityList.toString(), null); + 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>(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < mMyIdentityList.size(); 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 iCapability = new IdentityCapability(); + iCapability.mCapability = IdentityCapability.CapabilityID.chat; + iCapability.mValue = new Boolean(true); + ArrayList<IdentityCapability> mobileCapabilities = + new ArrayList<IdentityCapability>(); + mobileCapabilities.add(iCapability); + + Identity mobileIdentity = new Identity(); + mobileIdentity.mNetwork = "mobile"; + 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())); } - - - /** - * Add request to fetch available identities. The request is added to the UI - * request and processed when the engine is ready. - * - */ -// private void addUiGetAvailableIdentities() { -// LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); -// emptyUiRequestQueue(); -// addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); -// } - - /** - * Add request to fetch the current user's identities. - * - */ -// private void addUiGetMyIdentities() { -// LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); -// emptyUiRequestQueue(); -// addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); -// } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: - executeGetAvailableIdentitiesRequest(data); - break; - case GET_MY_IDENTITIES: - executeGetMyIdentitiesRequest(data); - break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } - - /** - * Issue request to retrieve 'My' Identities. (Request is not issued if - * there is currently no connectivity). - * - * @param data Bundled request data. - */ - private void executeGetMyIdentitiesRequest(Object data) { - if (!isConnected()) { - return; - } - newState(State.GETTING_MY_IDENTITIES); - if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { - completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); - } - } /** * 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_CAPABILITY_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); } } - - /** - * Sends a getAvailableIdentities request to the backend. - * - * TODO: remove the parameter as soon as we have merged with the ui-refresh - * branch. - * - * @param data Bundled request data. - */ - private void executeGetAvailableIdentitiesRequest(Object data) { - if (!isConnected()) { - return; - } - newState(State.FETCHING_IDENTITIES); - mAvailableIdentityList.clear(); - if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { - 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { 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: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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) { + HttpConnectionThread.logE("IE.handleGetAvailableIdentitiesResponse", "", null); + 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); } } } 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) { + HttpConnectionThread.logE("handleGetMyIdentitiesResponse", "", null); + LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); - if (errorStatus == ServiceStatus.SUCCESS) { - // create mobile identity to support 360 chat - IdentityCapability iCapability = new IdentityCapability(); - iCapability.mCapability = IdentityCapability.CapabilityID.chat; - iCapability.mValue = new Boolean(true); - ArrayList<IdentityCapability> capabilities = - new ArrayList<IdentityCapability>(); - capabilities.add(iCapability); - - Identity mobileIdentity = new Identity(); - mobileIdentity.mNetwork = "mobile"; - mobileIdentity.mName = "Vodafone"; - mobileIdentity.mCapabilities = capabilities; - // end: create mobile identity to support 360 chat - - synchronized (mAvailableIdentityList) { + if (errorStatus == ServiceStatus.SUCCESS) { + synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); + HttpConnectionThread.logE("Identity: ", ((Identity)item).toString(), null); } - mMyIdentityList.add(mobileIdentity); } } 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 handleSetIdentityCapabilityStatus(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); } /** * 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); } - + /** - * Create cache of 'chat-able' identities. * - * @param list List array of retrieved Identities. + * Retrieves the filter for the getAvailableIdentities and getMyIdentities + * calls. + * + * @return The identities filter in form of a bundle. + * */ - private void makeChatableIdentitiesCache(List<Identity> list) { - if (mMyChatableIdentityList == null) { - mMyChatableIdentityList = new ArrayList<String>(); - } else { - mMyChatableIdentityList.clear(); - } - - for (Identity id : list) { - if (id.mActive && id.mCapabilities != null) { - for (IdentityCapability ic : id.mCapabilities) { - if (ic.mCapability == CapabilityID.chat && ic.mValue) { - mMyChatableIdentityList.add(id.mNetwork); - } - } - } - } - } - 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(); - addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); + 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, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } } diff --git a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java index 5ed76c7..c842743 100644 --- a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java +++ b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java @@ -1,498 +1,498 @@ /* * 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.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 data byte array containing Hessian encoded data * @param type Event type * @return List of BaseDataType items parsed from Hessian data * @throws IOException */ public List<BaseDataType> decodeHessianByteArray(byte[] data, Request.Type type, boolean isZipped) 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); } List<BaseDataType> mBaseDataTypeList = null; mMicroHessianInput.init(is); LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); try { mBaseDataTypeList = decodeResponse(is, type); } catch (IOException e) { LogUtils.logE("HessianDecoder.decodeHessianByteArray() " + "IOException during decodeResponse", e); } CloseUtils.close(bis); CloseUtils.close(is); return mBaseDataTypeList; } @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; } } /** * TODO: we cast every response to a Map, losing e.g. push event "c0" which * only contains a string - to fix * * @param is * @param type * @return * @throws IOException */ @SuppressWarnings("unchecked") private List<BaseDataType> decodeResponse(InputStream is, Request.Type type) throws IOException { boolean usesReplyTag = false; List<BaseDataType> mResultList = 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()); mResultList.add(zybErr); return mResultList; } // 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(mResultList, is, tag); return mResultList; } // 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); decodeResponseByRequestType(mResultList, hash, type); } else { // if we have a common request 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); mResultList.add(auth.createFromHashtable(authHash)); } else if (map.containsKey(KEY_CONTACT_LIST)) { // contact list getContacts(mResultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); } 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) { mResultList.add(UserProfile.createFromHashtable(obj)); } } else if (map.containsKey(KEY_USER_PROFILE)) { Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map .get(KEY_USER_PROFILE); mResultList.add(UserProfile.createFromHashtable(userProfileHash)); } else if ((map.containsKey(KEY_IDENTITY_LIST)) || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { int mType = 0; Vector<Hashtable<String, Object>> idcap = null; if (map.containsKey(KEY_IDENTITY_LIST)) { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); - mType = BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE; + mType = BaseDataType.MY_IDENTITY_DATA_TYPE; } else { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); - mType = BaseDataType.MY_IDENTITY_DATA_TYPE; + mType = BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE; } for (Hashtable<String, Object> obj : idcap) { Identity id = new Identity(mType); mResultList.add(id.createFromHashtable(obj)); } } 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) { mResultList.add(ActivityItem.createFromHashtable(obj)); } } } if (usesReplyTag) { is.read(); // read the last 'z' } return mResultList; } 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); } private void decodeResponseByRequestType(List<BaseDataType> clist, Hashtable<String, Object> hash, Request.Type type) { switch (type) { case CONTACT_CHANGES_OR_UPDATES: // create ContactChanges ContactChanges contChanges = new ContactChanges(); contChanges = contChanges.createFromHashtable(hash); clist.add(contChanges); break; case ADD_CONTACT: case SIGN_UP: clist.add(Contact.createFromHashtable(hash)); break; case RETRIEVE_PUBLIC_KEY: // AA define new object type clist.add(PublicKeyDetails.createFromHashtable(hash)); break; case FRIENDSHIP_REQUEST: 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); break; case CONTACT_DETAIL_DELETE: ContactDetailDeletion cdel = new ContactDetailDeletion(); clist.add(cdel.createFromHashtable(hash)); break; case USER_INVITATION: // Not currently supported. break; case CONTACT_GROUP_RELATION_LIST: ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); groupRelationList.populateFromHashtable(hash); clist.add(groupRelationList); break; case CONTACT_GROUP_RELATIONS: ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); groupRelationsList.populateFromHashtable(hash); clist.add(groupRelationsList); break; case GROUP_LIST: ItemList zyblist = new ItemList(ItemList.Type.group_privacy); zyblist.populateFromHashtable(hash); clist.add(zyblist); break; case ITEM_LIST_OF_LONGS: ItemList listOfLongs = new ItemList(ItemList.Type.long_value); listOfLongs.populateFromHashtable(hash); clist.add(listOfLongs); break; case STATUS_LIST: ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); zybstatlist.populateFromHashtable(hash); clist.add(zybstatlist); 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); } break; case EXPECTING_STATUS_ONLY: StatusMsg statMsg = new StatusMsg(); clist.add(statMsg.createFromHashtable(hash)); break; case STATUS: StatusMsg s = new StatusMsg(); s.mStatus = true; clist.add(s); break; case PRESENCE_LIST: PresenceList mPresenceList = new PresenceList(); mPresenceList.createFromHashtable(hash); clist.add(mPresenceList); break; case PUSH_MSG: // parse content of RPG Push msg parsePushMessage(clist, hash); break; case CREATE_CONVERSATION: Conversation mConversation = new Conversation(); mConversation.createFromHashtable(hash); clist.add(mConversation); break; default: LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" + type.name() + "]"); } } 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
2c857d28e2afe2d16f735140cb2b45dde1009dc0
modified wrong message name
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index fb67b72..6c78677 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,730 +1,730 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; 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; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; /** * 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 the user is currently signed up for. + * Gets all third party identities and adds the mobile identity + * from 360 to them. * - * @return A list of 3rd party identities the user is signed in to or an - * empty list if something went wrong retrieving the identities. + * @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> getMyThirdPartyIdentities() { + public ArrayList<Identity> getAvailableThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( - (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) + (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { - sendGetMyIdentitiesRequest(); + sendGetAvailableIdentitiesRequest(); } - return mMyIdentityList; - } + return mAvailableIdentityList; + } /** * - * Gets all third party identities and adds the mobile identity - * from 360 to them. + * Gets all third party identities the user is currently signed up for. * - * @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. + * @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> getMy360AndThirdPartyIdentities() { + public ArrayList<Identity> getMyThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( - (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) + (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { - sendGetAvailableIdentitiesRequest(); + sendGetMyIdentitiesRequest(); } - return mAvailableIdentityList; - } + 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>(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < mMyIdentityList.size(); 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; } } } return chatableIdentities; } private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ // private void addUiGetAvailableIdentities() { // LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to fetch the current user's identities. * */ // private void addUiGetMyIdentities() { // LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { 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: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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); } } } 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) { // create mobile identity to support 360 chat IdentityCapability iCapability = new IdentityCapability(); iCapability.mCapability = IdentityCapability.CapabilityID.chat; iCapability.mValue = new Boolean(true); ArrayList<IdentityCapability> capabilities = new ArrayList<IdentityCapability>(); capabilities.add(iCapability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = "mobile"; mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = capabilities; // end: create mobile identity to support 360 chat synchronized (mAvailableIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } mMyIdentityList.add(mobileIdentity); } } 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 handleSetIdentityCapabilityStatus(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); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } 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(); addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); } } /** * 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; diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index 2355a29..f7a1129 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,361 +1,361 @@ /* * 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 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.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 the user is currently signed up for. + * Gets all third party identities and adds the mobile identity + * from 360 to them. * - * @return A list of 3rd party identities the user is signed in to or an - * empty list if something went wrong retrieving the identities. + * @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> getMyThirdPartyIdentities(); + public ArrayList<Identity> getAvailableThirdPartyIdentities(); /** * - * Gets all third party identities and adds the mobile identity - * from 360 to them. + * Gets all third party identities the user is currently signed up for. * - * @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. + * @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> getMy360AndThirdPartyIdentities(); + 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 availability state for a single network. * @param presence Network-presence to set */ void setAvailability(NetworkPresence presence); /*** * 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 7e6a735..5ecea59 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,433 +1,433 @@ /* * 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> getMy360AndThirdPartyIdentities() { - return EngineManager.getInstance().getIdentityEngine().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); } /*** * @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
149ca26e80608d79e795ef9ce3b81d7ac63605da
now calling the correct method for identities I hope
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 3ddc840..de92fa2 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -272,531 +272,529 @@ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, if (canRun()) { 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) { final int type = mBaseDataType.getType(); switch(type) { case BaseDataType.PRESENCE_LIST_DATA_TYPE: handlePresenceList((PresenceList)mBaseDataType); break; case BaseDataType.PUSH_EVENT_DATA_TYPE: handlePushEvent(((PushEvent)mBaseDataType)); break; case BaseDataType.CONVERSATION_DATA_TYPE: // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); break; case BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE: handleSystemNotification((SystemNotification)mBaseDataType); break; case BaseDataType.SERVER_ERROR_DATA_TYPE: handleServerError((ServerError)mBaseDataType); break; default: 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.mMessageType); } } 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()) { 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 SET_MY_AVAILABILITY_FOR_COMMUNITY: Presence.setMyAvailabilityForCommunity(); 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()) { 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 presence list constructed from identities Hashtable<String, String> presences = getPresencesForStatus(status); if(presences == null) { LogUtils.logW("setMyAvailability() Ignoring setMyAvailability request because there are no identities!"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presences); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presences); } /** * 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); } } } public void onConnectionStateChanged(int state) { if (mLoggedIn && canRun()) { 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().getMy360AndThirdPartyIdentities(); + 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) { - if(!identity.mNetwork.equals(SocialNetwork.PC.toString())) { presences.put(identity.mNetwork, statusString); - } } return presences; } }
360/360-Engine-for-Android
fb6afa8492e4a93a867efcefc563529d5899ab4a
added changes to prepare the UI for the new getters
diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index 4181983..2355a29 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,333 +1,361 @@ /* * 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 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.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(); - /*** - * Begins the process of retrieving Third party Accounts that the user is - * already registered with from the Vodafone 360 back end. The response is - * sent to any currently registered Activity handlers. + /** + * + * 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(); + + /** + * + * 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> getMy360AndThirdPartyIdentities(); + + /** + * + * 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. * - * @param Bundle filter the kind of identities to return. */ - //void fetchMyIdentities(Bundle data); + 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 availability state for a single network. * @param presence Network-presence to set */ void setAvailability(NetworkPresence presence); /*** * 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 4813d76..7e6a735 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,427 +1,433 @@ /* * 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#fetchAvailableIdentities(Bundle) + /** + * @see com.vodafone360.people.service.interfaces.IPeopleService#getMyThirdPartyIdentities() */ -/* @Override - public void fetchAvailableIdentities(Bundle data) { - EngineManager.getInstance().getIdentityEngine().addUiGetAvailableIdentities(); - }*/ + public ArrayList<Identity> getMyThirdPartyIdentities() { + return EngineManager.getInstance().getIdentityEngine().getMyThirdPartyIdentities(); + } - /*** - * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchMyIdentities(Bundle) + /** + * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyIdentities() */ - /*@Override - public void fetchMyIdentities(Bundle data) { - EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(); - }*/ + public ArrayList<Identity> getMy360AndThirdPartyIdentities() { + return EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyIdentities(); + } + + /** + * @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); } /*** * @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
10119c397c644196c9b6d583e49b2c1aefde7cf4
Fixing the wrecked code from my failed merge
diff --git a/src/com/vodafone360/people/datatypes/AuthSessionHolder.java b/src/com/vodafone360/people/datatypes/AuthSessionHolder.java index 32a8246..c96bb65 100644 --- a/src/com/vodafone360/people/datatypes/AuthSessionHolder.java +++ b/src/com/vodafone360/people/datatypes/AuthSessionHolder.java @@ -1,163 +1,162 @@ /* * 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; } - /** {@inheritDoc} */ - @Override + public int getType() { return AUTH_SESSION_HOLDER_TYPE; } /** {@inheritDoc} */ public String toString() { final StringBuilder sb = 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); 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
d1695cf4a71f73b96f496f5fdba58b634288b875
Trying to correct the previous commit
diff --git a/src/com/vodafone360/people/datatypes/Identity.java b/src/com/vodafone360/people/datatypes/Identity.java index 8a0741d..46bc01e 100644 --- a/src/com/vodafone360/people/datatypes/Identity.java +++ b/src/com/vodafone360/people/datatypes/Identity.java @@ -1,619 +1,614 @@ /* * 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.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Vector; import android.os.Parcel; import android.os.Parcelable; import com.vodafone360.people.utils.LogUtils; /** * BaseDataType encapsulating an Identity issued to or retrieved from server */ public class Identity extends BaseDataType implements Parcelable { /** * Tags associated with Identity item. */ private enum Tags { IDENTITY_MAIN_TAG("availableidentity"), IDENTITY_CAPABILITY_LIST("identitycapabilitylist"), PLUGIN_ID("pluginid"), NETWORK_URL("networkurl"), AUTH_TYPE("authtype"), ICON_MIME("iconmime"), ICON2_MIME("icon2mime"), ORDER("order"), NAME("name"), ICON_URL("iconurl"), ICON2_URL("icon2url"), NETWORK("network"), // Properties below are only present after // GetMyIdentities. ACTIVE("active"), CREATED("created"), IDENTITY_ID("identityid"), UPDATED("updated"), IDENTITY_TYPE("identitytype"), USER_ID("userid"), USER_NAME("username"), DISPLAY_NAME("displayname"), COUNTRY_LIST("countrylist"); private final String tag; /** * Construct Tags item from supplied String * * @param s String value for Tags item. */ private Tags(String s) { tag = s; } /** * String value for 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 in Tags items. * @return Tags item for specified String, NULL otherwise. */ private static Tags findTag(String tag) { for (Tags tags : Tags.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } return null; } } public String mPluginId = null; public String mNetwork = null; public URL mNetworkUrl = null; public URL mIconUrl = null; public URL mIcon2Url = null; public String mAuthType; public String mIconMime = null; public Integer mOrder = null; public String mName = null; public List<IdentityCapability> mCapabilities = null; /** Properties below are only present after GetMyIdentities. */ public Boolean mActive = null; public Long mCreated = null; public Long mUpdated = null; public String mIdentityId = null; public Integer mUserId = null; public String mUserName = null; public String mDisplayName = null; public List<String> mCountryList = null; public String mIdentityType = null; private int mType; /** * Comparator class used to compare Identities retrieved from server to * remove duplicates from list passed to People client UI. */ public static class IdentityComparator implements Comparator<Identity> { @Override public int compare(Identity object1, Identity object2) { return object1.mOrder.compareTo(object2.mOrder); } } /** * Test whether current Identity is identical to supplied Identity. * * @param id Identity to compare against. * @return true if Identities match, false otherwise. */ public boolean isSameAs(Identity id) { boolean isSame = true; if (!areStringValuesSame(mPluginId, id.mPluginId) || !areStringValuesSame(mNetwork, id.mNetwork) || !areStringValuesSame(mIdentityId, id.mIdentityId) || !areStringValuesSame(mDisplayName, id.mDisplayName)) { isSame = false; } if (mNetworkUrl != null && id.mNetworkUrl != null) { if (!mNetworkUrl.sameFile(id.mNetworkUrl)) { isSame = false; } } else if (mNetworkUrl == null && id.mNetworkUrl == null) { // Do nothing. } else { isSame = false; } if (mIconUrl != null && id.mIconUrl != null) { if (!mIconUrl.sameFile(id.mIconUrl)) { isSame = false; } } else if (mIconUrl == null && id.mIconUrl == null) { // Do nothing. } else { isSame = false; } return isSame; } /** * String values comparison * * @param s1 First String to test. * @param s2 Second String to test. * @return true if Strings match (or both are null), false otherwise. */ private boolean areStringValuesSame(String s1, String s2) { boolean isSame = true; if (s1 == null && s2 == null) { // Do nothing. } else if (s1 != null && s2 != null) { if (s1.compareTo(s2) != 0) { isSame = false; } } else { isSame = false; } return isSame; } /** * Default constructor. */ public Identity() { // Do nothing. } public Identity(int type) { mType = type; } /** * Create Identity from Parcel. * * @param in Parcel containing Identity. */ private Identity(Parcel in) { readFromParcel(in); } /** {@inheritDoc} */ - @Override -<<<<<<< HEAD - public int type() { - return mType; -======= + @Override public int getType() { // TODO: Return appropriate type if its // an available identity instead of my identity - return MY_IDENTITY_DATA_TYPE; ->>>>>>> Correction to my previous type() modification and cleaned up a lot of toString() methods + return MY_IDENTITY_DATA_TYPE; } /** * Populate Identity from supplied Hashtable. * * @param hash Hashtable containing identity details. * @return Identity instance. */ public Identity createFromHashtable(Hashtable<String, Object> hash) { Enumeration<String> e = hash.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); Object value = hash.get(key); Tags tag = Tags.findTag(key); if (tag != null) setValue(tag, value); } 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 val) { switch (tag) { case AUTH_TYPE: mAuthType = (String)val; break; case ICON_MIME: mIconMime = (String)val; break; case ICON2_MIME: // TODO: Remove TAG value? // mIcon2Mime = (String)val; break; case ICON_URL: try { mIconUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIconUrl = null; } break; case ICON2_URL: try { mIcon2Url = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIcon2Url = null; } break; case IDENTITY_CAPABILITY_LIST: /** Create id capability list. */ @SuppressWarnings("unchecked") Vector<Hashtable<String, Object>> v = (Vector<Hashtable<String, Object>>)val; if (mCapabilities == null) { mCapabilities = new ArrayList<IdentityCapability>(); } for (Hashtable<String, Object> obj : v) { IdentityCapability cap = new IdentityCapability(); cap.createFromHashtable(obj); mCapabilities.add(cap); } break; case IDENTITY_MAIN_TAG: // Not currently handled. break; case NAME: mName = (String)val; break; case NETWORK: mNetwork = (String)val; break; case NETWORK_URL: try { mNetworkUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong network url: '" + val + "'"); mNetworkUrl = null; } break; case ORDER: mOrder = (Integer)val; break; case PLUGIN_ID: mPluginId = (String)val; break; case ACTIVE: mActive = (Boolean)val; break; case CREATED: mCreated = (Long)val; break; case DISPLAY_NAME: mDisplayName = (String)val; break; case IDENTITY_ID: mIdentityId = (String)val; break; case IDENTITY_TYPE: mIdentityType = (String)val; break; case UPDATED: mUpdated = (Long)val; break; case USER_ID: mUserId = ((Long)val).intValue(); break; case USER_NAME: mUserName = (String)val; break; case COUNTRY_LIST: if (mCountryList == null) { mCountryList = new ArrayList<String>(); } break; default: // Do nothing. break; } } /** {@inheritDoc} */ @Override public String toString() { final StringBuffer sb = new StringBuffer("Name:"); sb.append(mName); sb.append("\nPluginID:"); sb.append(mPluginId); sb.append("\nNetwork:"); sb.append(mNetwork); sb.append("\nNetworkURL:"); sb.append(mNetworkUrl); sb.append("\nAuthType:"); sb.append(mAuthType); sb.append("\nIcon mime:"); sb.append(mIconMime); sb.append("\nIconURL:"); sb.append(mIconUrl); sb.append("\nOrder:"); sb.append(mOrder); sb.append("\nActive:"); sb.append(mActive); sb.append("\nCreated:"); sb.append(mCreated); sb.append("\nUpdated:"); sb.append(mUpdated); sb.append("\nIdentityId:"); sb.append(mIdentityId); sb.append("\nUserId:"); sb.append(mUserId); sb.append("\nUserName:"); sb.append(mUserName); sb.append("\nDisplayName:"); sb.append(mDisplayName); sb.append("\nIdentityType:"); sb.append(mIdentityType); if (mCountryList != null) { sb.append("\nCountry List: ("); sb.append(mCountryList.size()); sb.append(") = ["); for (int i = 0; i < mCountryList.size(); i++) { sb.append(mCountryList.get(i)); if (i < mCountryList.size() - 1) sb.append(", "); } sb.append("]"); } if (mCapabilities != null) { sb.append("\nCapabilities ("); sb.append(mCapabilities.size()); sb.append(")"); for (int i = 0; i < mCapabilities.size(); i++) { sb.append("\n" + mCapabilities.get(i).toString()); if (i < mCapabilities.size() - 1) { sb.append("\n\t---"); } } } return sb.toString(); } /** {@inheritDoc} */ @Override public int describeContents() { return 1; } /** * Enumeration containing items contained within Identity Parcel. */ private enum MemberData { PLUGIN_ID, NETWORK, NETWORK_URL, ICON_URL, AUTH_TYPE, ICON_MIME, ORDER, NAME; } /** * Read Identity item from Parcel. * * @param in Parcel containing Identity information. */ private void readFromParcel(Parcel in) { mPluginId = null; mNetwork = null; mNetworkUrl = null; mIconUrl = null; mAuthType = null; mIconMime = null; mOrder = null; mName = null; mCapabilities = null; boolean[] validDataList = new boolean[MemberData.values().length]; in.readBooleanArray(validDataList); if (validDataList[MemberData.PLUGIN_ID.ordinal()]) { mPluginId = in.readString(); } if (validDataList[MemberData.NETWORK.ordinal()]) { mNetwork = in.readString(); } if (validDataList[MemberData.NETWORK_URL.ordinal()]) { try { mNetworkUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.NETWORK_URL"); } } if (validDataList[MemberData.ICON_URL.ordinal()]) { try { mIconUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.ICON_URL"); } } if (validDataList[MemberData.AUTH_TYPE.ordinal()]) { mAuthType = in.readString(); } if (validDataList[MemberData.ICON_MIME.ordinal()]) { mIconMime = in.readString(); } if (validDataList[MemberData.ORDER.ordinal()]) { mOrder = in.readInt(); } if (validDataList[MemberData.NAME.ordinal()]) { mName = in.readString(); } int noOfCapabilities = in.readInt(); if (noOfCapabilities > 0) { mCapabilities = new ArrayList<IdentityCapability>(noOfCapabilities); for (int i = 0; i < noOfCapabilities; i++) { IdentityCapability cap = IdentityCapability.CREATOR.createFromParcel(in); mCapabilities.add(cap); } } } /** {@inheritDoc} */ @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 (mPluginId != null) { validDataList[MemberData.PLUGIN_ID.ordinal()] = true; dest.writeString(mPluginId); } if (mNetwork != null) { validDataList[MemberData.NETWORK.ordinal()] = true; dest.writeString(mNetwork); } if (mNetworkUrl != null) { validDataList[MemberData.NETWORK_URL.ordinal()] = true; dest.writeString(mNetworkUrl.toString()); } if (mIconUrl != null) { validDataList[MemberData.ICON_URL.ordinal()] = true; dest.writeString(mIconUrl.toString()); } if (mAuthType != null) { validDataList[MemberData.AUTH_TYPE.ordinal()] = true; dest.writeString(mAuthType); } if (mIconMime != null) { validDataList[MemberData.ICON_MIME.ordinal()] = true; dest.writeString(mIconMime); } if (mOrder != null) { validDataList[MemberData.ORDER.ordinal()] = true; dest.writeInt(mOrder); } if (mName != null) { validDataList[MemberData.NAME.ordinal()] = true; dest.writeString(mName); } if (mCapabilities != null) { dest.writeInt(mCapabilities.size()); for (IdentityCapability cap : mCapabilities) { cap.writeToParcel(dest, 0); } } else { dest.writeInt(0); } int currentPos = dest.dataPosition(); dest.setDataPosition(validDataPos); dest.writeBooleanArray(validDataList); // Real array. dest.setDataPosition(currentPos); } /** Interface to allow Identity to be written and restored from a Parcel. */ public static final Parcelable.Creator<Identity> CREATOR = new Parcelable.Creator<Identity>() { public Identity createFromParcel(Parcel in) { return new Identity(in); } public Identity[] newArray(int size) { return new Identity[size]; } }; } diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 3e6ff8a..fb67b72 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,793 +1,793 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; 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; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; /** * 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 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; } /** * * 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> getMy360AndThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } /** * * 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>(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < mMyIdentityList.size(); 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; } } } return chatableIdentities; } private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ // private void addUiGetAvailableIdentities() { // LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to fetch the current user's identities. * */ // private void addUiGetMyIdentities() { // LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { - switch (resp.mDataTypes.get(0).type()) { + 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: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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); } } } 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) { // create mobile identity to support 360 chat IdentityCapability iCapability = new IdentityCapability(); iCapability.mCapability = IdentityCapability.CapabilityID.chat; iCapability.mValue = new Boolean(true); ArrayList<IdentityCapability> capabilities = new ArrayList<IdentityCapability>(); capabilities.add(iCapability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = "mobile"; mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = capabilities; // end: create mobile identity to support 360 chat synchronized (mAvailableIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } mMyIdentityList.add(mobileIdentity); } } 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 handleSetIdentityCapabilityStatus(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); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } 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(); addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); } } /** * 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, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } }
360/360-Engine-for-Android
cc2bc76a327e18061f83d569caeb437a03801c7b
- changed ui accessors in IdentityEngine - added different types to Identity to be able to distinguish between GetAvailableIdentities and GetMyIdentities - HessianDecoder now distinguishes between GetAvailableIdentities and GetMyIdentities, too
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index fb243b7..2c05885 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,718 +1,718 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; 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; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; /** * 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 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; } /** * * 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 identities pc and mobile. + * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } /** * * 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>(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < mMyIdentityList.size(); 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; } } } return chatableIdentities; } private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ // private void addUiGetAvailableIdentities() { // LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to fetch the current user's identities. * */ // private void addUiGetMyIdentities() { // LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { switch (resp.mDataTypes.get(0).type()) { 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: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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); } } } 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) { // create mobile identity to support 360 chat IdentityCapability iCapability = new IdentityCapability(); iCapability.mCapability = IdentityCapability.CapabilityID.chat; iCapability.mValue = new Boolean(true); ArrayList<IdentityCapability> capabilities = new ArrayList<IdentityCapability>(); capabilities.add(iCapability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = "mobile"; mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = capabilities; // end: create mobile identity to support 360 chat synchronized (mAvailableIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } mMyIdentityList.add(mobileIdentity); } } 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.type() == 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 handleSetIdentityCapabilityStatus(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.type() == 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); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } 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(); addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); } } /**
360/360-Engine-for-Android
3645c28f886a4e898f9ab89554a67c7203a57457
added new requests to IdentityEngine to replace the traditional ui requests
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 2144a41..fb243b7 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,718 +1,718 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ - private final ArrayList<Identity> mAvailableIdentityList = new ArrayList<Identity>(); + private ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ - private final ArrayList<Identity> mMyIdentityList = new ArrayList<Identity>(); + private ArrayList<Identity> mMyIdentityList; /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; /** * 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 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; } /** * * 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 + * the 360 identities pc and mobile. * be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } /** * * 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>(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < mMyIdentityList.size(); 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; } } } return chatableIdentities; } private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ // private void addUiGetAvailableIdentities() { // LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to fetch the current user's identities. * */ // private void addUiGetMyIdentities() { // LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { switch (resp.mDataTypes.get(0).type()) { 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: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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); } } } 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) { // create mobile identity to support 360 chat IdentityCapability iCapability = new IdentityCapability(); iCapability.mCapability = IdentityCapability.CapabilityID.chat; iCapability.mValue = new Boolean(true); ArrayList<IdentityCapability> capabilities = new ArrayList<IdentityCapability>(); capabilities.add(iCapability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = "mobile"; mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = capabilities; // end: create mobile identity to support 360 chat synchronized (mAvailableIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } mMyIdentityList.add(mobileIdentity); } } 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.type() == 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 handleSetIdentityCapabilityStatus(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.type() == 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); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } 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(); addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); } } /**
360/360-Engine-for-Android
84aa22ea75fd3cc8c3947e562aa464d29af7d89b
Changed the horrid String name() for Data type to a plain int type(). This should help with the refactoring not mention GC and speed. Over to you Rudy...
diff --git a/src/com/vodafone360/people/engine/login/LoginEngine.java b/src/com/vodafone360/people/engine/login/LoginEngine.java index 95527e4..4e411c3 100644 --- a/src/com/vodafone360/people/engine/login/LoginEngine.java +++ b/src/com/vodafone360/people/engine/login/LoginEngine.java @@ -1,625 +1,623 @@ /* * 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; /** * 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, 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;
360/360-Engine-for-Android
4d0187e849aba9a7c55abd9e4cd9555908ccca27
now using the method stubbed method that Rudy added.
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 4f4ff7a..dce7419 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -131,667 +131,670 @@ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, 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 * * @return true if everything is ready */ private boolean canRun() { 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; } /** * 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()) { 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); } @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()) { 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) { final int type = mBaseDataType.type(); switch(type) { case BaseDataType.PRESENCE_LIST_DATA_TYPE: handlePresenceList((PresenceList)mBaseDataType); break; case BaseDataType.PUSH_EVENT_DATA_TYPE: handlePushEvent(((PushEvent)mBaseDataType)); break; case BaseDataType.CONVERSATION_DATA_TYPE: // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); break; case BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE: handleSystemNotification((SystemNotification)mBaseDataType); break; case BaseDataType.SERVER_ERROR_DATA_TYPE: handleServerError((ServerError)mBaseDataType); break; default: 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.mMessageType); } } 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()) { 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 SET_MY_AVAILABILITY_FOR_COMMUNITY: Presence.setMyAvailabilityForCommunity(); 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()) { 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); + // Get presence list constructed from identities + Hashtable<String, String> presences = getPresencesForStatus(status); + if(presences == null) { + LogUtils.logW("setMyAvailability() Ignoring setMyAvailability request because there are no identities!"); + return; + } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), - presenceList); + presences); // 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, presences); } /** * 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); } } } public void onConnectionStateChanged(int state) { if (mLoggedIn && canRun()) { 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().getMy360AndThirdPartyIdentities(); 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; } }
360/360-Engine-for-Android
709d3a836e7bdcaca261e8660057e2359a097f98
breaky breaky, identity refaky
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 2c05885..2144a41 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,669 +1,669 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ - private ArrayList<Identity> mAvailableIdentityList; + private final ArrayList<Identity> mAvailableIdentityList = new ArrayList<Identity>(); /** List array of Identities retrieved from Server. */ - private ArrayList<Identity> mMyIdentityList; + private final ArrayList<Identity> mMyIdentityList = new ArrayList<Identity>(); /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; /** * 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 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; } /** * * 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> getMy360AndThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } /** * * 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>(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < mMyIdentityList.size(); 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; } } } return chatableIdentities; } private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ // private void addUiGetAvailableIdentities() { // LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to fetch the current user's identities. * */ // private void addUiGetMyIdentities() { // LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { switch (resp.mDataTypes.get(0).type()) { 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: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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); } } } 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) { // create mobile identity to support 360 chat IdentityCapability iCapability = new IdentityCapability(); iCapability.mCapability = IdentityCapability.CapabilityID.chat; iCapability.mValue = new Boolean(true); ArrayList<IdentityCapability> capabilities = new ArrayList<IdentityCapability>(); capabilities.add(iCapability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = "mobile"; mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = capabilities; // end: create mobile identity to support 360 chat synchronized (mAvailableIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } mMyIdentityList.add(mobileIdentity); } } 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.type() == 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 handleSetIdentityCapabilityStatus(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.type() == 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); } /** * Get Connectivity status from the connection manager. *
360/360-Engine-for-Android
6c62e21cbc05101c63b524385cd955a79439a82f
Simplified code a little, now just has old behaviour with minor cleanup.
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 83a5666..4f4ff7a 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,792 +1,797 @@ /* * 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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; - } - if (!canRun()) { - LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"); - return -1; + mNextRuntime = -1; + LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" + + mNextRuntime); + return mNextRuntime; } /** * 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()) { 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); } @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()) { 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) { final int type = mBaseDataType.type(); switch(type) { case BaseDataType.PRESENCE_LIST_DATA_TYPE: handlePresenceList((PresenceList)mBaseDataType); break; case BaseDataType.PUSH_EVENT_DATA_TYPE: handlePushEvent(((PushEvent)mBaseDataType)); break; case BaseDataType.CONVERSATION_DATA_TYPE: // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); break; case BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE: handleSystemNotification((SystemNotification)mBaseDataType); break; case BaseDataType.SERVER_ERROR_DATA_TYPE: handleServerError((ServerError)mBaseDataType); break; default: 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.mMessageType); } } 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()) { + 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: - if (data != null) { - Presence.setMyAvailability(((OnlineStatus)data).toString()); - completeUiRequest(ServiceStatus.SUCCESS, null); - setNextRuntime(); - } + Presence.setMyAvailability((Hashtable<String, String>)data); break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: - if (data != null) { - Presence.setMyAvailabilityForCommunity(); - completeUiRequest(ServiceStatus.SUCCESS, null); - setNextRuntime(); - } + Presence.setMyAvailabilityForCommunity(); + 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) { + if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && + ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) + || !canRun()) { 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 = new Hashtable<String, String>(); - // 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); } } } public void onConnectionStateChanged(int state) { if (mLoggedIn && canRun()) { 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().getMy360AndThirdPartyIdentities(); 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/io/api/Presence.java b/src/com/vodafone360/people/service/io/api/Presence.java index 38ccb1a..012f9fc 100644 --- a/src/com/vodafone360/people/service/io/api/Presence.java +++ b/src/com/vodafone360/people/service/io/api/Presence.java @@ -1,126 +1,139 @@ /* * 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.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; + } + 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(); } /** * 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(); } public static void setMyAvailabilityForCommunity() { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.setMyAvailabilityForCommunity() No session, so return"); return; } } } diff --git a/src/com/vodafone360/people/utils/HardcodedUtils.java b/src/com/vodafone360/people/utils/HardcodedUtils.java index 4f3fe72..c76e198 100644 --- a/src/com/vodafone360/people/utils/HardcodedUtils.java +++ b/src/com/vodafone360/people/utils/HardcodedUtils.java @@ -1,65 +1,65 @@ /* * 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.Hashtable; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.NetworkPresence; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; /** * @author timschwerdtner * Collection of hardcoded and duplicated code as a first step for refactoring. */ public class HardcodedUtils { -// /** -// * To be used with IPeopleService.setAvailability until identity handling -// * has been refactored. -// * @param Desired availability state -// * @return A hashtable for the set availability call -// */ -// public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) { -// Hashtable<String, String> availability = new Hashtable<String, String>(); -// -// LogUtils.logD("Setting Availability to: " + onlineStatus.toString()); -// // TODO: REMOVE HARDCODE setting everything possible to currentStatus -// availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString()); -// -// return availability; -// } + /** + * To be used with IPeopleService.setAvailability until identity handling + * has been refactored. + * @param Desired availability state + * @return A hashtable for the set availability call + */ + public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) { + Hashtable<String, String> availability = new Hashtable<String, String>(); + + LogUtils.logD("Setting Availability to: " + onlineStatus.toString()); + // TODO: REMOVE HARDCODE setting everything possible to currentStatus + availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString()); + + return availability; + } /** * The static list of supported TPC accounts. */ public static final int[] THIRD_PARTY_CHAT_ACCOUNTS = new int[]{SocialNetwork.FACEBOOK_COM.ordinal(), SocialNetwork.GOOGLE.ordinal(), SocialNetwork.HYVES_NL.ordinal(), SocialNetwork.MICROSOFT.ordinal()}; }
360/360-Engine-for-Android
577640aec0ae9a50b1503e867967aab4bd7d567d
New availability method now used NetworkPresence as the argument
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index a4c6645..83a5666 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -107,660 +107,686 @@ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, /** 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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!canRun()) { 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()) { 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); } @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()) { 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) { final int type = mBaseDataType.type(); switch(type) { case BaseDataType.PRESENCE_LIST_DATA_TYPE: handlePresenceList((PresenceList)mBaseDataType); break; case BaseDataType.PUSH_EVENT_DATA_TYPE: handlePushEvent(((PushEvent)mBaseDataType)); break; case BaseDataType.CONVERSATION_DATA_TYPE: // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); break; case BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE: handleSystemNotification((SystemNotification)mBaseDataType); break; case BaseDataType.SERVER_ERROR_DATA_TYPE: handleServerError((ServerError)mBaseDataType); break; default: 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.mMessageType); } } 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) { LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { Presence.setMyAvailability(((OnlineStatus)data).toString()); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: if (data != null) { Presence.setMyAvailabilityForCommunity(); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } 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) { 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 state of the engine. Also displays the login notification if - * necessary. + * Changes the user's availability and therefore the state of the engine. + * Also displays the login notification if necessary. * - * @param accounts + * @param status Availability to set for all identities we have. */ - public void setMyAvailability(OnlineStatus onlinestatus) { - if (onlinestatus == null) { + 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:"+onlinestatus.toString()); + 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> userPresence = new Hashtable<String, String>(); + Hashtable<String, String> presenceList = new Hashtable<String, String>(); // TODO: Fill up hashtable with identities and online statuses - User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), - userPresence); - Hashtable<String, String> availability = new Hashtable<String, String>(); - for (NetworkPresence presence : myself.getPayload()) { - availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), - OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); - } + User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), + presenceList); + // set the DB values for myself - myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); - updateMyPresenceInDatabase(myself); + me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); + updateMyPresenceInDatabase(me); // set the engine to run now - addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, userPresence); + addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } - public void setMyAvailability(String network, String availability) { - + /** + * 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); } } } public void onConnectionStateChanged(int state) { if (mLoggedIn && canRun()) { 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().getMy360AndThirdPartyIdentities(); 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/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index ee64ee0..4181983 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,344 +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.interfaces; import android.os.Bundle; import android.os.Handler; 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.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(); /*** * Begins the process of retrieving Third party Accounts that the user is * already registered with 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 fetchMyIdentities(Bundle data); /*** * 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); - -// /*** -// * Alter the current Social Network availability state and send it to the -// * server. -// * -// * @param myself is the wrapper for the own presence state, can be retrieved -// * from PresenceTable.getUserByLocalContactId(long -// * meProfileLocalContactId). -// */ -// void setAvailability(Hashtable<String, String> myself); /** * Change current global (all identities) availability state. - * @param onlinestatus Availability to set for all identities we have. + * @param status Availability to set for all identities we have. */ - void setAvailability(OnlineStatus onlinestatus); + void setAvailability(OnlineStatus status); /** * Change current availability state for a single network. - * @param network - * @param availability + * @param presence Network-presence to set */ - void setAvailability(String network, String availability); + void setAvailability(NetworkPresence presence); /*** * 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); }
360/360-Engine-for-Android
9b13e35b1437095fdbb4194ce67934ffd2c23e16
Minor changes that I missed.
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 7d510b4..a4c6645 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -23,756 +23,744 @@ * 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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!canRun()) { 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()) { 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); } @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()) { 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) { final int type = mBaseDataType.type(); switch(type) { case BaseDataType.PRESENCE_LIST_DATA_TYPE: handlePresenceList((PresenceList)mBaseDataType); break; case BaseDataType.PUSH_EVENT_DATA_TYPE: handlePushEvent(((PushEvent)mBaseDataType)); break; case BaseDataType.CONVERSATION_DATA_TYPE: // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); break; case BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE: handleSystemNotification((SystemNotification)mBaseDataType); break; case BaseDataType.SERVER_ERROR_DATA_TYPE: handleServerError((ServerError)mBaseDataType); break; default: 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.mMessageType); } } 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) { LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { - Presence.setMyAvailability((String)data); + Presence.setMyAvailability(((OnlineStatus)data).toString()); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: if (data != null) { Presence.setMyAvailabilityForCommunity(); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } 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) { 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 state of the engine. Also displays the login notification if -// * necessary. -// * -// * @param accounts -// */ -// public void setMyAvailability(Hashtable<String, String> myselfPresence) { -// if (myselfPresence == null) { -// LogUtils.logE("PresenceEngine setMyAvailability:" -// + " Can't send the setAvailability request due to DB reading errors"); -// return; -// } -// -// LogUtils.logV("PresenceEngine setMyAvailability() called with:" + myselfPresence); -// if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { -// LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); -// return; -// } -// -// User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), -// myselfPresence); -// -// Hashtable<String, String> availability = new Hashtable<String, String>(); -// for (NetworkPresence presence : myself.getPayload()) { -// availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), -// OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); -// } -// // set the DB values for myself -// myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); -// updateMyPresenceInDatabase(myself); -// -// // set the engine to run now -// -// addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); -// } - /** + * Changes the state of the engine. Also displays the login notification if + * necessary. * - * @param availability + * @param accounts */ - public void setMyAvailability(String availability) { - if (TextUtils.isEmpty(availability)) { + public void setMyAvailability(OnlineStatus onlinestatus) { + if (onlinestatus == null) { LogUtils.logE("PresenceEngine setMyAvailability:" - + " Can't my availability using empty availability"); + + " Can't send the setAvailability request due to DB reading errors"); + return; + } + + LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+onlinestatus.toString()); + if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { + LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } - LogUtils.logV("PresenceEngine setMyAvailability() called with:" + availability); + // Get presences + Hashtable<String, String> userPresence = new Hashtable<String, String>(); - addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); + // TODO: Fill up hashtable with identities and online statuses + User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), + userPresence); + + Hashtable<String, String> availability = new Hashtable<String, String>(); + for (NetworkPresence presence : myself.getPayload()) { + availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), + OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); + } + // set the DB values for myself + myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); + updateMyPresenceInDatabase(myself); + + // set the engine to run now + + addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, userPresence); } - + public void setMyAvailability(String network, String availability) { } 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); } } } public void onConnectionStateChanged(int state) { if (mLoggedIn && canRun()) { 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().getMy360AndThirdPartyIdentities(); 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/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index 9c25e9e..ee64ee0 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,344 +1,344 @@ /* * 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 android.os.Bundle; import android.os.Handler; 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.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(); /*** * Begins the process of retrieving Third party Accounts that the user is * already registered with 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 fetchMyIdentities(Bundle data); /*** * 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); // /*** // * Alter the current Social Network availability state and send it to the // * server. // * // * @param myself is the wrapper for the own presence state, can be retrieved // * from PresenceTable.getUserByLocalContactId(long // * meProfileLocalContactId). // */ // void setAvailability(Hashtable<String, String> myself); /** * Change current global (all identities) availability state. - * @param availability Availability to set for all identities we have. + * @param onlinestatus Availability to set for all identities we have. */ - void setAvailability(String availability); + void setAvailability(OnlineStatus onlinestatus); /** * Change current availability state for a single network. * @param network * @param availability */ void setAvailability(String network, String availability); /*** * 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/io/api/Presence.java b/src/com/vodafone360/people/service/io/api/Presence.java index 0e5e93e..38ccb1a 100644 --- a/src/com/vodafone360/people/service/io/api/Presence.java +++ b/src/com/vodafone360/people/service/io/api/Presence.java @@ -1,125 +1,126 @@ /* * 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.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(); } /** * API to set my availability * * @param engineId ID of presence engine. - * @param availability Availability to set + * @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 apropriate 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(); } /** * 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(); } public static void setMyAvailabilityForCommunity() { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.setMyAvailabilityForCommunity() No session, so return"); return; } } }
360/360-Engine-for-Android
0c70523e6bcecbf885fe3403045b802a83449f7f
Removed . from README
diff --git a/README b/README index 0c39d43..9defdfe 100644 --- a/README +++ b/README @@ -1 +1 @@ -For detailed documentation please visit http://360.github.com/360-Engine-for-Android. +For detailed documentation please visit http://360.github.com/360-Engine-for-Android
360/360-Engine-for-Android
f234ada769a85553996d3e5deda9ffc0817eb4ec
Added . to README
diff --git a/README b/README index 9defdfe..0c39d43 100644 --- a/README +++ b/README @@ -1 +1 @@ -For detailed documentation please visit http://360.github.com/360-Engine-for-Android +For detailed documentation please visit http://360.github.com/360-Engine-for-Android.
360/360-Engine-for-Android
1337dd323f7bedc12880ed18346e14e109503e58
- changed ui accessors in IdentityEngine - added different types to Identity to be able to distinguish between GetAvailableIdentities and GetMyIdentities - HessianDecoder now distinguishes between GetAvailableIdentities and GetMyIdentities, too
diff --git a/src/com/vodafone360/people/datatypes/Identity.java b/src/com/vodafone360/people/datatypes/Identity.java index 8d288b2..28d8446 100644 --- a/src/com/vodafone360/people/datatypes/Identity.java +++ b/src/com/vodafone360/people/datatypes/Identity.java @@ -1,605 +1,609 @@ /* * 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.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Vector; import android.os.Parcel; import android.os.Parcelable; import com.vodafone360.people.utils.LogUtils; /** * BaseDataType encapsulating an Identity issued to or retrieved from server */ public class Identity extends BaseDataType implements Parcelable { /** * Tags associated with Identity item. */ private enum Tags { IDENTITY_MAIN_TAG("availableidentity"), IDENTITY_CAPABILITY_LIST("identitycapabilitylist"), PLUGIN_ID("pluginid"), NETWORK_URL("networkurl"), AUTH_TYPE("authtype"), ICON_MIME("iconmime"), ICON2_MIME("icon2mime"), ORDER("order"), NAME("name"), ICON_URL("iconurl"), ICON2_URL("icon2url"), NETWORK("network"), // Properties below are only present after // GetMyIdentities. ACTIVE("active"), CREATED("created"), IDENTITY_ID("identityid"), UPDATED("updated"), IDENTITY_TYPE("identitytype"), USER_ID("userid"), USER_NAME("username"), DISPLAY_NAME("displayname"), COUNTRY_LIST("countrylist"); private final String tag; /** * Construct Tags item from supplied String * * @param s String value for Tags item. */ private Tags(String s) { tag = s; } /** * String value for 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 in Tags items. * @return Tags item for specified String, NULL otherwise. */ private static Tags findTag(String tag) { for (Tags tags : Tags.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } return null; } } public String mPluginId = null; public String mNetwork = null; public URL mNetworkUrl = null; public URL mIconUrl = null; public URL mIcon2Url = null; public String mAuthType; public String mIconMime = null; public Integer mOrder = null; public String mName = null; public List<IdentityCapability> mCapabilities = null; /** Properties below are only present after GetMyIdentities. */ public Boolean mActive = null; public Long mCreated = null; public Long mUpdated = null; public String mIdentityId = null; public Integer mUserId = null; public String mUserName = null; public String mDisplayName = null; public List<String> mCountryList = null; public String mIdentityType = null; + + private int mType; /** * Comparator class used to compare Identities retrieved from server to * remove duplicates from list passed to People client UI. */ public static class IdentityComparator implements Comparator<Identity> { @Override public int compare(Identity object1, Identity object2) { return object1.mOrder.compareTo(object2.mOrder); } } /** * Test whether current Identity is identical to supplied Identity. * * @param id Identity to compare against. * @return true if Identities match, false otherwise. */ public boolean isSameAs(Identity id) { boolean isSame = true; if (!areStringValuesSame(mPluginId, id.mPluginId) || !areStringValuesSame(mNetwork, id.mNetwork) || !areStringValuesSame(mIdentityId, id.mIdentityId) || !areStringValuesSame(mDisplayName, id.mDisplayName)) { isSame = false; } if (mNetworkUrl != null && id.mNetworkUrl != null) { if (!mNetworkUrl.sameFile(id.mNetworkUrl)) { isSame = false; } } else if (mNetworkUrl == null && id.mNetworkUrl == null) { // Do nothing. } else { isSame = false; } if (mIconUrl != null && id.mIconUrl != null) { if (!mIconUrl.sameFile(id.mIconUrl)) { isSame = false; } } else if (mIconUrl == null && id.mIconUrl == null) { // Do nothing. } else { isSame = false; } return isSame; } /** * String values comparison * * @param s1 First String to test. * @param s2 Second String to test. * @return true if Strings match (or both are null), false otherwise. */ private boolean areStringValuesSame(String s1, String s2) { boolean isSame = true; if (s1 == null && s2 == null) { // Do nothing. } else if (s1 != null && s2 != null) { if (s1.compareTo(s2) != 0) { isSame = false; } } else { isSame = false; } return isSame; } /** * Default constructor. */ public Identity() { // Do nothing. } + + public Identity(int type) { + mType = type; + } /** * Create Identity from Parcel. * * @param in Parcel containing Identity. */ private Identity(Parcel in) { readFromParcel(in); } /** {@inheritDoc} */ @Override public int type() { - // TODO: Return appropriate type if its - // an available identity instead of my identity - return MY_IDENTITY_DATA_TYPE; + return mType; } /** * Populate Identity from supplied Hashtable. * * @param hash Hashtable containing identity details. * @return Identity instance. */ public Identity createFromHashtable(Hashtable<String, Object> hash) { Enumeration<String> e = hash.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); Object value = hash.get(key); Tags tag = Tags.findTag(key); if (tag != null) setValue(tag, value); } 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 val) { switch (tag) { case AUTH_TYPE: mAuthType = (String)val; break; case ICON_MIME: mIconMime = (String)val; break; case ICON2_MIME: // TODO: Remove TAG value? // mIcon2Mime = (String)val; break; case ICON_URL: try { mIconUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIconUrl = null; } break; case ICON2_URL: try { mIcon2Url = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIcon2Url = null; } break; case IDENTITY_CAPABILITY_LIST: /** Create id capability list. */ @SuppressWarnings("unchecked") Vector<Hashtable<String, Object>> v = (Vector<Hashtable<String, Object>>)val; if (mCapabilities == null) { mCapabilities = new ArrayList<IdentityCapability>(); } for (Hashtable<String, Object> obj : v) { IdentityCapability cap = new IdentityCapability(); cap.createFromHashtable(obj); mCapabilities.add(cap); } break; case IDENTITY_MAIN_TAG: // Not currently handled. break; case NAME: mName = (String)val; break; case NETWORK: mNetwork = (String)val; break; case NETWORK_URL: try { mNetworkUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong network url: '" + val + "'"); mNetworkUrl = null; } break; case ORDER: mOrder = (Integer)val; break; case PLUGIN_ID: mPluginId = (String)val; break; case ACTIVE: mActive = (Boolean)val; break; case CREATED: mCreated = (Long)val; break; case DISPLAY_NAME: mDisplayName = (String)val; break; case IDENTITY_ID: mIdentityId = (String)val; break; case IDENTITY_TYPE: mIdentityType = (String)val; break; case UPDATED: mUpdated = (Long)val; break; case USER_ID: mUserId = ((Long)val).intValue(); break; case USER_NAME: mUserName = (String)val; break; case COUNTRY_LIST: if (mCountryList == null) { mCountryList = new ArrayList<String>(); } break; default: // Do nothing. break; } } /** {@inheritDoc} */ @Override public String toString() { StringBuffer ret = new StringBuffer(); ret.append("Name: " + mName); ret.append("\nPluginID: " + mPluginId); ret.append("\nNetwork: " + mNetwork); ret.append("\nNetworkURL: " + mNetworkUrl); ret.append("\nAuthType: " + mAuthType); ret.append("\nIcon mime: " + mIconMime); ret.append("\nIconURL: " + mIconUrl); ret.append("\nOrder: " + mOrder); ret.append("\nActive: " + mActive); ret.append("\nCreated: " + mCreated); ret.append("\nUpdated: " + mUpdated); ret.append("\nIdentityId: " + mIdentityId); ret.append("\nUserId: " + mUserId); ret.append("\nUserName: " + mUserName); ret.append("\nDisplayName: " + mDisplayName); ret.append("\nIdentityType: " + mIdentityType); if (mCountryList != null) { ret.append("\nCountry List: (" + mCountryList.size() + ") = ["); for (int i = 0; i < mCountryList.size(); i++) { ret.append(mCountryList.get(i)); if (i < mCountryList.size() - 1) ret.append(", "); } ret.append("]"); } if (mCapabilities != null) { ret.append("\nCapabilities (" + mCapabilities.size() + ")"); for (int i = 0; i < mCapabilities.size(); i++) { ret.append("\n" + mCapabilities.get(i).toString()); if (i < mCapabilities.size() - 1) { ret.append("\n\t---"); } } } return ret.toString(); } /** {@inheritDoc} */ @Override public int describeContents() { return 1; } /** * Enumeration containing items contained within Identity Parcel. */ private enum MemberData { PLUGIN_ID, NETWORK, NETWORK_URL, ICON_URL, AUTH_TYPE, ICON_MIME, ORDER, NAME; } /** * Read Identity item from Parcel. * * @param in Parcel containing Identity information. */ private void readFromParcel(Parcel in) { mPluginId = null; mNetwork = null; mNetworkUrl = null; mIconUrl = null; mAuthType = null; mIconMime = null; mOrder = null; mName = null; mCapabilities = null; boolean[] validDataList = new boolean[MemberData.values().length]; in.readBooleanArray(validDataList); if (validDataList[MemberData.PLUGIN_ID.ordinal()]) { mPluginId = in.readString(); } if (validDataList[MemberData.NETWORK.ordinal()]) { mNetwork = in.readString(); } if (validDataList[MemberData.NETWORK_URL.ordinal()]) { try { mNetworkUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.NETWORK_URL"); } } if (validDataList[MemberData.ICON_URL.ordinal()]) { try { mIconUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.ICON_URL"); } } if (validDataList[MemberData.AUTH_TYPE.ordinal()]) { mAuthType = in.readString(); } if (validDataList[MemberData.ICON_MIME.ordinal()]) { mIconMime = in.readString(); } if (validDataList[MemberData.ORDER.ordinal()]) { mOrder = in.readInt(); } if (validDataList[MemberData.NAME.ordinal()]) { mName = in.readString(); } int noOfCapabilities = in.readInt(); if (noOfCapabilities > 0) { mCapabilities = new ArrayList<IdentityCapability>(noOfCapabilities); for (int i = 0; i < noOfCapabilities; i++) { IdentityCapability cap = IdentityCapability.CREATOR.createFromParcel(in); mCapabilities.add(cap); } } } /** {@inheritDoc} */ @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 (mPluginId != null) { validDataList[MemberData.PLUGIN_ID.ordinal()] = true; dest.writeString(mPluginId); } if (mNetwork != null) { validDataList[MemberData.NETWORK.ordinal()] = true; dest.writeString(mNetwork); } if (mNetworkUrl != null) { validDataList[MemberData.NETWORK_URL.ordinal()] = true; dest.writeString(mNetworkUrl.toString()); } if (mIconUrl != null) { validDataList[MemberData.ICON_URL.ordinal()] = true; dest.writeString(mIconUrl.toString()); } if (mAuthType != null) { validDataList[MemberData.AUTH_TYPE.ordinal()] = true; dest.writeString(mAuthType); } if (mIconMime != null) { validDataList[MemberData.ICON_MIME.ordinal()] = true; dest.writeString(mIconMime); } if (mOrder != null) { validDataList[MemberData.ORDER.ordinal()] = true; dest.writeInt(mOrder); } if (mName != null) { validDataList[MemberData.NAME.ordinal()] = true; dest.writeString(mName); } if (mCapabilities != null) { dest.writeInt(mCapabilities.size()); for (IdentityCapability cap : mCapabilities) { cap.writeToParcel(dest, 0); } } else { dest.writeInt(0); } int currentPos = dest.dataPosition(); dest.setDataPosition(validDataPos); dest.writeBooleanArray(validDataList); // Real array. dest.setDataPosition(currentPos); } /** Interface to allow Identity to be written and restored from a Parcel. */ public static final Parcelable.Creator<Identity> CREATOR = new Parcelable.Creator<Identity>() { public Identity createFromParcel(Parcel in) { return new Identity(in); } public Identity[] newArray(int size) { return new Identity[size]; } }; } diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 4e604fa..2c05885 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,724 +1,793 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; 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; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; - private static final String KEY_DATA_CHATABLE_IDENTITIES = "chatable_data"; - /** * 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 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; } /** * - * Gets all third party identities and adds the mobile and pc identities + * 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 identities pc and mobile. If the retrieval failed the list will + * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } + /** + * + * 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>(); + + // checking each identity for its chat capability and adding it to the + // list if it does + for (int i = 0; i < mMyIdentityList.size(); 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; + } + } + } + + return chatableIdentities; + } + private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ // private void addUiGetAvailableIdentities() { // LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to fetch the current user's identities. * */ // private void addUiGetMyIdentities() { // LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { - switch (mState) { - case IDLE: - LogUtils.logW("IDLE should never happend"); - break; - case FETCHING_IDENTITIES: - case GETTING_MY_IDENTITIES: - case GETTING_MY_CHATABLE_IDENTITIES: - handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); - break; - case SETTING_IDENTITY_CAPABILITY_STATUS: - handleSetIdentityCapabilityStatus(resp.mDataTypes); - break; - case VALIDATING_IDENTITY_CREDENTIALS: - handleValidateIdentityCredentials(resp.mDataTypes); - break; + switch (resp.mDataTypes.get(0).type()) { + 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: + handleSetIdentityCapabilityStatus(resp.mDataTypes); + break; + case BaseDataType.STATUS_MSG_DATA_TYPE: + handleValidateIdentityCredentials(resp.mDataTypes); + break; default: - LogUtils.logW("default should never happend"); + LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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: - addUiGetAvailableIdentities(); + sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: - // TODO padma + 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 handleServerGetAvailableIdentitiesResponse(List<BaseDataType> data) { - Bundle bu = null; + private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); + if (errorStatus == ServiceStatus.SUCCESS) { - mAvailableIdentityList.clear(); - for (BaseDataType item : data) { - if (item.type() == BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE) { - mAvailableIdentityList.add((Identity)item); - } else { - completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); - return; - } - } - bu = new Bundle(); - if (mState == State.GETTING_MY_IDENTITIES - || (mState == State.GETTING_MY_CHATABLE_IDENTITIES)) { - // store local copy of my identities - makeChatableIdentitiesCache(mAvailableIdentityList); - bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); - } - bu.putParcelableArrayList(KEY_DATA, mAvailableIdentityList); + synchronized (mAvailableIdentityList) { + mAvailableIdentityList.clear(); + + for (BaseDataType item : data) { + mAvailableIdentityList.add((Identity)item); + } + } } - LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse completw UI req"); - completeUiRequest(errorStatus, bu); - newState(State.IDLE); + + 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) { + // create mobile identity to support 360 chat + IdentityCapability iCapability = new IdentityCapability(); + iCapability.mCapability = IdentityCapability.CapabilityID.chat; + iCapability.mValue = new Boolean(true); + ArrayList<IdentityCapability> capabilities = + new ArrayList<IdentityCapability>(); + capabilities.add(iCapability); + + Identity mobileIdentity = new Identity(); + mobileIdentity.mNetwork = "mobile"; + mobileIdentity.mName = "Vodafone"; + mobileIdentity.mCapabilities = capabilities; + // end: create mobile identity to support 360 chat + + synchronized (mAvailableIdentityList) { + mMyIdentityList.clear(); + + for (BaseDataType item : data) { + mMyIdentityList.add((Identity)item); + } + mMyIdentityList.add(mobileIdentity); + } + } + + 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.type() == 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 handleSetIdentityCapabilityStatus(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.type() == 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); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } 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(); addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); } } /** * 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, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } } diff --git a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java index 9e1d42a..7d58677 100644 --- a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java +++ b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java @@ -1,495 +1,498 @@ /* * 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.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 data byte array containing Hessian encoded data * @param type Event type * @return List of BaseDataType items parsed from Hessian data * @throws IOException */ public List<BaseDataType> decodeHessianByteArray(byte[] data, Request.Type type, boolean isZipped) 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); } List<BaseDataType> mBaseDataTypeList = null; mMicroHessianInput.init(is); LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); try { mBaseDataTypeList = decodeResponse(is, type); } catch (IOException e) { LogUtils.logE("HessianDecoder.decodeHessianByteArray() " + "IOException during decodeResponse", e); } CloseUtils.close(bis); CloseUtils.close(is); return mBaseDataTypeList; } @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; } } /** * TODO: we cast every response to a Map, losing e.g. push event "c0" which * only contains a string - to fix * * @param is * @param type * @return * @throws IOException */ @SuppressWarnings("unchecked") private List<BaseDataType> decodeResponse(InputStream is, Request.Type type) throws IOException { boolean usesReplyTag = false; List<BaseDataType> mResultList = 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(); zybErr.errorType = mMicroHessianInput.readFault().errString(); mResultList.add(zybErr); return mResultList; } // 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(mResultList, is, tag); return mResultList; } // 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); decodeResponseByRequestType(mResultList, hash, type); } else { // if we have a common request 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); mResultList.add(auth.createFromHashtable(authHash)); } else if (map.containsKey(KEY_CONTACT_LIST)) { // contact list getContacts(mResultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); } 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) { mResultList.add(UserProfile.createFromHashtable(obj)); } } else if (map.containsKey(KEY_USER_PROFILE)) { Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map .get(KEY_USER_PROFILE); mResultList.add(UserProfile.createFromHashtable(userProfileHash)); } else if ((map.containsKey(KEY_IDENTITY_LIST)) || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { + int mType = 0; Vector<Hashtable<String, Object>> idcap = null; if (map.containsKey(KEY_IDENTITY_LIST)) { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); + mType = BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE; } else { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); + mType = BaseDataType.MY_IDENTITY_DATA_TYPE; } for (Hashtable<String, Object> obj : idcap) { - Identity id = new Identity(); + Identity id = new Identity(mType); mResultList.add(id.createFromHashtable(obj)); } } 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) { mResultList.add(ActivityItem.createFromHashtable(obj)); } } } if (usesReplyTag) { is.read(); // read the last 'z' } return mResultList; } 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); } private void decodeResponseByRequestType(List<BaseDataType> clist, Hashtable<String, Object> hash, Request.Type type) { switch (type) { case CONTACT_CHANGES_OR_UPDATES: // create ContactChanges ContactChanges contChanges = new ContactChanges(); contChanges = contChanges.createFromHashtable(hash); clist.add(contChanges); break; case ADD_CONTACT: case SIGN_UP: clist.add(Contact.createFromHashtable(hash)); break; case RETRIEVE_PUBLIC_KEY: // AA define new object type clist.add(PublicKeyDetails.createFromHashtable(hash)); break; case FRIENDSHIP_REQUEST: 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); break; case CONTACT_DETAIL_DELETE: ContactDetailDeletion cdel = new ContactDetailDeletion(); clist.add(cdel.createFromHashtable(hash)); break; case USER_INVITATION: // Not currently supported. break; case CONTACT_GROUP_RELATION_LIST: ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); groupRelationList.populateFromHashtable(hash); clist.add(groupRelationList); break; case CONTACT_GROUP_RELATIONS: ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); groupRelationsList.populateFromHashtable(hash); clist.add(groupRelationsList); break; case GROUP_LIST: ItemList zyblist = new ItemList(ItemList.Type.group_privacy); zyblist.populateFromHashtable(hash); clist.add(zyblist); break; case ITEM_LIST_OF_LONGS: ItemList listOfLongs = new ItemList(ItemList.Type.long_value); listOfLongs.populateFromHashtable(hash); clist.add(listOfLongs); break; case STATUS_LIST: ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); zybstatlist.populateFromHashtable(hash); clist.add(zybstatlist); 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); } break; case EXPECTING_STATUS_ONLY: StatusMsg statMsg = new StatusMsg(); clist.add(statMsg.createFromHashtable(hash)); break; case STATUS: StatusMsg s = new StatusMsg(); s.mStatus = true; clist.add(s); break; case PRESENCE_LIST: PresenceList mPresenceList = new PresenceList(); mPresenceList.createFromHashtable(hash); clist.add(mPresenceList); break; case PUSH_MSG: // parse content of RPG Push msg parsePushMessage(clist, hash); break; case CREATE_CONVERSATION: Conversation mConversation = new Conversation(); mConversation.createFromHashtable(hash); clist.add(mConversation); break; default: LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" + type.name() + "]"); } } 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
d88adabc79b4366dbddb4829a0779ee5a1e93e71
added new requests to IdentityEngine to replace the traditional ui requests
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 619633b..4e604fa 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,692 +1,724 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; + private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ - private final ArrayList<Identity> mAvailableIdentityList = new ArrayList<Identity>(); + private ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ - private final ArrayList<Identity> mMyIdentityList = new ArrayList<Identity>(); + private ArrayList<Identity> mMyIdentityList; /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; private static final String KEY_DATA_CHATABLE_IDENTITIES = "chatable_data"; /** * 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 the user is currently signed up for. * - * @return A list of 3rd party identities the user is signed in to or null - * if there was something wrong retrieving the identities. + * @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; - } + } /** * * Gets all third party identities and adds the mobile and pc identities * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus - * the 360 identities pc and mobile. + * the 360 identities pc and mobile. If the retrieval failed the list will + * be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyIdentities() { + if ((mMyIdentityList.size() == 0) && ( + (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) + > MIN_REQUEST_INTERVAL)) { + sendGetAvailableIdentitiesRequest(); + } + return mAvailableIdentityList; } + private void sendGetMyIdentitiesRequest() { + Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); + } + + private void sendGetAvailableIdentitiesRequest() { + Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); + } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ - public void addUiGetAvailableIdentities() { - LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); - emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); - } +// private void addUiGetAvailableIdentities() { +// LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); +// emptyUiRequestQueue(); +// addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); +// } /** * Add request to fetch the current user's identities. * */ - public void addUiGetMyIdentities() { - LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); - emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); - } +// private void addUiGetMyIdentities() { +// LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); +// emptyUiRequestQueue(); +// addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); +// } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { switch (mState) { case IDLE: LogUtils.logW("IDLE should never happend"); break; case FETCHING_IDENTITIES: case GETTING_MY_IDENTITIES: case GETTING_MY_CHATABLE_IDENTITIES: handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); break; case SETTING_IDENTITY_CAPABILITY_STATUS: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case VALIDATING_IDENTITY_CREDENTIALS: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("default should never happend"); break; } } } /** * 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: addUiGetAvailableIdentities(); break; case IDENTITY_CHANGE: // TODO padma 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 handleServerGetAvailableIdentitiesResponse(List<BaseDataType> data) { Bundle bu = null; LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { if (item.type() == BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE) { mAvailableIdentityList.add((Identity)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mState == State.GETTING_MY_IDENTITIES || (mState == State.GETTING_MY_CHATABLE_IDENTITIES)) { // store local copy of my identities makeChatableIdentitiesCache(mAvailableIdentityList); bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); } bu.putParcelableArrayList(KEY_DATA, mAvailableIdentityList); } LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse completw UI req"); completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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.type() == 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 handleSetIdentityCapabilityStatus(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.type() == 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); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } 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(); addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); } } /** * 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, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } }
360/360-Engine-for-Android
048076b357dac5d8d8f64770fbd2ec6dd236a0ef
now using the method stubbed method that Rudy added.
diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index bcbd744..06d73b8 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,317 +1,314 @@ /* * 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.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 - // TODO: Need to construct "status" from identities and utility method - Hashtable<String, String> status = new Hashtable<String, String>(); - status.put("google", "online"); - status.put("microsoft", "online"); - status.put("mobile", "online"); - status.put("facebook.com", "online"); - status.put("hyves.nl", "online"); + // 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); } } 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 34937ac..178d294 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,752 +1,781 @@ /* * 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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!canRun()) { 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()) { 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); } @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()) { 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) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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) { LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: Presence.setMyAvailability((Hashtable<String, String>)data); break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: Presence.setMyAvailabilityForCommunity(); 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) { 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); + // Get presence list constructed from identities + Hashtable<String, String> presences = getPresencesForStatus(status); + if(presences == null) { + LogUtils.logW("setMyAvailability() Ignoring setMyAvailability request because there are no identities!"); + return; + } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), - presenceList); + presences); // 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, presences); } /** * 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); } } } public void onConnectionStateChanged(int state) { if (mLoggedIn && canRun()) { 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().getMy360AndThirdPartyIdentities(); + + 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; + } }
360/360-Engine-for-Android
35368e4d67e02e13a2baadd9ae0ed0a40f9aa55f
breaky breaky, identity refaky
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 305499a..a004388 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,715 +1,702 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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 { +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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ - private final ArrayList<Identity> mIdentityList = new ArrayList<Identity>(); + private final ArrayList<Identity> mAvailableIdentityList = new ArrayList<Identity>(); + + /** List array of Identities retrieved from Server. */ + private final ArrayList<Identity> mMyIdentityList = new ArrayList<Identity>(); /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** Definitions for expected data-types returned from Server. */ private static final String TYPE_IDENTITY = "Identity"; private static final String TYPE_STATUS_MSG = "StatusMsg"; public static final String KEY_DATA = "data"; private static final String KEY_DATA_CHATABLE_IDENTITIES = "chatable_data"; private static final String LOG_STATUS_MSG = TYPE_STATUS_MSG + ": "; - /** - * Generate Map containing boolean capability filters for supplied Bundle. - * - * @param filter Bundle containing filter. - * @return Map containing set of capabilities. - */ - private static Map<String, Object> prepareBoolFilter(Bundle filter) { - Map<String, Object> objectFilter = null; - if (filter != null && (filter.keySet().size() > 0)) { - objectFilter = new Hashtable<String, Object>(); - 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; - } - /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; } - + + /** - * 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() { - } - - /** - * Process a response received from Server. The response is handled - * according to the current IdentityEngine state. + * Gets all third party identities the user is currently signed up for. * - * @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) { - PushEvent evt = (PushEvent)resp.mDataTypes.get(0); - handlePushRequest(evt.mMessageType); - } else { - switch (mState) { - case IDLE: - LogUtils.logW("IDLE should never happend"); - break; - case FETCHING_IDENTITIES: - case GETTING_MY_IDENTITIES: - case GETTING_MY_CHATABLE_IDENTITIES: - handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); - break; - case SETTING_IDENTITY_CAPABILITY_STATUS: - handleSetIdentityCapabilityStatus(resp.mDataTypes); - break; - case VALIDATING_IDENTITY_CREDENTIALS: - handleValidateIdentityCredentials(resp.mDataTypes); - break; - default: - LogUtils.logW("default should never happend"); - break; - } - } - } - - /** - * Handle Status or Timeline Activity change Push message + * @return A list of 3rd party identities the user is signed in to or null + * if there was something wrong retrieving the identities. * - * @param evt Push message type (Status change or Timeline change). */ - private void handlePushRequest(PushMessageTypes evt) { - LogUtils.logD("IdentityEngine handlePushRequest"); - switch (evt) { - case IDENTITY_NETWORK_CHANGE: - addUiFetchIdentities(); - break; - case IDENTITY_CHANGE: - EngineManager.getInstance().getPresenceEngine().setMyAvailability(); - addUiGetMyIdentities(); - mEventCallback.kickWorkerThread(); - break; - default: - // do nothing - } + public ArrayList<Identity> getMyThirdPartyIdentities() { + return mMyIdentityList; } /** - * Issue any outstanding UI request. * - * @param requestType Request to be issued. - * @param dara Data associated with the request. + * Gets all third party identities and adds the mobile and pc identities + * from 360 to them. + * + * @return A list of all 3rd party identities the user is signed in to plus + * the 360 identities pc and mobile. + * */ - @Override - protected void processUiRequest(ServiceUiRequest requestType, Object data) { - LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); - switch (requestType) { - case FETCH_IDENTITIES: - startGetAvailableIdentities(data); - break; - case GET_MY_IDENTITIES: - startGetMyIdentities(data); - break; - case GET_MY_CHATABLE_IDENTITIES: - startGetMyChatableIdentities(); - break; - case VALIDATE_IDENTITY_CREDENTIALS: - startValidateIdentityCredentials(data); - break; - case SET_IDENTITY_CAPABILITY_STATUS: - // changed the method called - // startSetIdentityCapabilityStatus(data); - startSetIdentityStatus(data); - break; - default: - completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); - break; - } + public ArrayList<Identity> getMy360AndThirdPartyIdentities() { + } - - /** - * 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(); - } - } - + + + + /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ - public void addUiFetchIdentities() { - LogUtils.logD("IdentityEngine.addUiFetchIdentities()"); + public void addUiGetAvailableIdentities() { + LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.FETCH_IDENTITIES, getIdentitiesFilter()); + addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); + } + + /** + * Add request to fetch the current user's identities. + * + */ + public void addUiGetMyIdentities() { + LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); + emptyUiRequestQueue(); + addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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); } /** - * Add request to fetch the current user's identities. - * - */ - public void addUiGetMyIdentities() { - LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); - emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); - } - - /** - * Change current IdentityEngine state. + * Issue any outstanding UI request. * - * @param newState new state. + * @param requestType Request to be issued. + * @param dara Data associated with the request. */ - private void newState(State newState) { - State oldState = mState; - synchronized (mMutex) { - if (newState == mState) { - return; - } - mState = newState; + @Override + protected void processUiRequest(ServiceUiRequest requestType, Object data) { + LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); + switch (requestType) { + case GET_AVAILABLE_IDENTITIES: + executeGetAvailableIdentitiesRequest(data); + break; + case GET_MY_IDENTITIES: + executeGetMyIdentitiesRequest(data); + break; + case VALIDATE_IDENTITY_CREDENTIALS: + executeValidateIdentityCredentialsRequest(data); + break; + case SET_IDENTITY_CAPABILITY_STATUS: + // changed the method called + // startSetIdentityCapabilityStatus(data); + executeSetIdentityStatusRequest(data); + break; + default: + completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); + break; } - LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } - + /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * - * TODO: remove parameter as soon as branch ui-refresh is merged. - * * @param data Bundled request data. - * */ - private void startGetMyIdentities(Object data) { + private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } - /** - * Issue request to retrieve 'My chat-able' Identities. The request is - * filtered to retrieve only identities with the chat capability enabled. - * (Request is not issued if there is currently no connectivity). - */ - private void startGetMyChatableIdentities() { - if (!isConnected()) { - return; - } - Bundle filter = new Bundle(); - ArrayList<String> l = new ArrayList<String>(); - l.add(IdentityCapability.CapabilityID.chat.name()); - filter.putStringArrayList("capability", l); - - newState(State.GETTING_MY_CHATABLE_IDENTITIES); - if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter(filter)))) { - completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); - } - } - - /** * 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 startSetIdentityStatus(Object data) { + private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_CAPABILITY_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 startValidateIdentityCredentials(Object 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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ - private void startGetAvailableIdentities(Object data) { + private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); - mIdentityList.clear(); + mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { + PushEvent evt = (PushEvent)resp.mDataTypes.get(0); + handlePushResponse(evt.mMessageType); + } else { + switch (mState) { + case IDLE: + LogUtils.logW("IDLE should never happend"); + break; + case FETCHING_IDENTITIES: + case GETTING_MY_IDENTITIES: + case GETTING_MY_CHATABLE_IDENTITIES: + handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); + break; + case SETTING_IDENTITY_CAPABILITY_STATUS: + handleSetIdentityCapabilityStatus(resp.mDataTypes); + break; + case VALIDATING_IDENTITY_CREDENTIALS: + handleValidateIdentityCredentials(resp.mDataTypes); + break; + default: + LogUtils.logW("default should never happend"); + break; + } + } + } + + /** + * 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: + addUiGetAvailableIdentities(); + break; + case IDENTITY_CHANGE: + // TODO padma + 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 handleServerGetAvailableIdentitiesResponse(List<BaseDataType> data) { Bundle bu = null; LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(TYPE_IDENTITY, data); if (errorStatus == ServiceStatus.SUCCESS) { - mIdentityList.clear(); + mAvailableIdentityList.clear(); for (BaseDataType item : data) { if (TYPE_IDENTITY.equals(item.name())) { - mIdentityList.add((Identity)item); + mAvailableIdentityList.add((Identity)item); LogUtils.logD("Identity: " + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mState == State.GETTING_MY_IDENTITIES || (mState == State.GETTING_MY_CHATABLE_IDENTITIES)) { // store local copy of my identities - makeChatableIdentitiesCache(mIdentityList); + makeChatableIdentitiesCache(mAvailableIdentityList); bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); } - bu.putParcelableArrayList(KEY_DATA, mIdentityList); + bu.putParcelableArrayList(KEY_DATA, mAvailableIdentityList); } LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse completw UI req"); completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } 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 handleSetIdentityCapabilityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } + + 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(); + addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); + } + } + /** - * Add request to fetch the current user's 'chat-able' identities. This will - * automatically apply set of filters applied to GetMyIdentities API call to - * get Identities with chat capability. - * - * Note: Only called from tests. + * 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. */ - public void getMyChatableIdentities() { - LogUtils.logD("IdentityEngine.getMyChatableIdentities()"); - if (mMyChatableIdentityList != null) { - Bundle bu = new Bundle(); - bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); - completeUiRequest(ServiceStatus.SUCCESS, bu); - return; + @Override + public long getNextRunTime() { + if (isUiRequestOutstanding()) { + return 0; + } + if (isCommsResponseOutstanding()) { + return 0; } + return getCurrentTimeout(); + } - addUiRequestToQueue(ServiceUiRequest.GET_MY_CHATABLE_IDENTITIES, null); + /** {@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. * - * Retrieves the filter for the getAvailableIdentities and getMyIdentities - * calls. - * - * @return The identities filter in form of a bundle. + * @param filter Bundle containing filter. + * @return Map containing set of capabilities. + */ + private static Map<String, Object> prepareBoolFilter(Bundle filter) { + Map<String, Object> objectFilter = null; + if (filter != null && (filter.keySet().size() > 0)) { + objectFilter = new Hashtable<String, Object>(); + 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 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; + 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; } + } diff --git a/src/com/vodafone360/people/service/ServiceUiRequest.java b/src/com/vodafone360/people/service/ServiceUiRequest.java index 529d203..caf24d7 100644 --- a/src/com/vodafone360/people/service/ServiceUiRequest.java +++ b/src/com/vodafone360/people/service/ServiceUiRequest.java @@ -1,267 +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 */ - FETCH_IDENTITIES, + 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, /** * Request to set the presence availability status for a single community */ SET_MY_AVAILABILITY_FOR_COMMUNITY, /** 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, /* * 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 0dbc95b..4181983 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,333 +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.interfaces; import android.os.Bundle; import android.os.Handler; 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.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(); /*** * Begins the process of retrieving Third party Accounts that the user is * already registered with 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 fetchMyIdentities(Bundle data); + //void fetchMyIdentities(Bundle data); /*** * 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); + //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 availability state for a single network. * @param presence Network-presence to set */ void setAvailability(NetworkPresence presence); /*** * 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 c80638b..4da73ae 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,427 +1,427 @@ /* * 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.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#fetchAvailableIdentities(Bundle) */ - @Override +/* @Override public void fetchAvailableIdentities(Bundle data) { - EngineManager.getInstance().getIdentityEngine().addUiFetchIdentities(); - } + EngineManager.getInstance().getIdentityEngine().addUiGetAvailableIdentities(); + }*/ /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchMyIdentities(Bundle) */ - @Override + /*@Override public void fetchMyIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(); - } + }*/ /*** * @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); } /*** * @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
3cbe912cd3c1540d0d3242097bf2f84b92c88e1a
Simplified code a little, now just has old behaviour with minor cleanup.
diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index c4f60ae..bcbd744 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,326 +1,317 @@ /* * 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.ContactSummary.OnlineStatus; 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 - // TODO: this hard code needs change, must filter the identities - // info by VCARD.IMADRESS + // TODO: Need to construct "status" from identities and utility method Hashtable<String, String> status = new Hashtable<String, String>(); status.put("google", "online"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("facebook.com", "online"); status.put("hyves.nl", "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); } } 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); } } - - /** - * @param input - * @return - */ - public static boolean notNullOrBlank(String input) { - return (input != null) && input.length() > 0; - } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 566d9a4..34937ac 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,769 +1,752 @@ /* * 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.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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { - if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!canRun()) { 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()) { 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); } @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()) { 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) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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) { LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: - if (data != null) { - Presence.setMyAvailability(((OnlineStatus)data).toString()); - completeUiRequest(ServiceStatus.SUCCESS, null); - setTimeout(CHECK_FREQUENCY); - } + Presence.setMyAvailability((Hashtable<String, String>)data); break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: - if (data != null) { - Presence.setMyAvailabilityForCommunity(); - completeUiRequest(ServiceStatus.SUCCESS, null); - setNextRuntime(); - } + Presence.setMyAvailabilityForCommunity(); + break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); - completeUiRequest(ServiceStatus.SUCCESS, null); - setTimeout(CHECK_FREQUENCY); break; - case CREATE_CONVERSATION: - if (data != null) { - List<String> tos = ((ChatMessage)data).getTos(); - LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " - + tos); - Chat.startChat(tos); - // Request to update the UI - completeUiRequest(ServiceStatus.SUCCESS, null); - // Request to update the UI - setTimeout(CHECK_FREQUENCY); - } + List<String> tos = ((ChatMessage)data).getTos(); + LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + + tos); + Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: - if (data != null) { - 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); - // Request to update the UI - completeUiRequest(ServiceStatus.SUCCESS, null); - // Request to update the UI - setTimeout(CHECK_FREQUENCY); - } + 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); } - - private void initSetMyAvailabilityRequest(User myself) { - if (myself == 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 ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && - ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED)) { + if (me.isOnline() == OnlineStatus.ONLINE.ordinal() && + ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); - for (NetworkPresence presence : myself.getPayload()) { + for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values - myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); + me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); - updateMyPresenceInDatabase(myself); + 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 = new Hashtable<String, String>(); - // 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()) { 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()); } } diff --git a/src/com/vodafone360/people/service/io/api/Presence.java b/src/com/vodafone360/people/service/io/api/Presence.java index 7f3bccc..d9a71ac 100644 --- a/src/com/vodafone360/people/service/io/api/Presence.java +++ b/src/com/vodafone360/people/service/io/api/Presence.java @@ -1,102 +1,115 @@ /* * 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.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; + } + 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(); } public static void setMyAvailabilityForCommunity() { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.setMyAvailabilityForCommunity() No session, so return"); return; } } } diff --git a/src/com/vodafone360/people/utils/HardcodedUtils.java b/src/com/vodafone360/people/utils/HardcodedUtils.java index 4f3fe72..c76e198 100644 --- a/src/com/vodafone360/people/utils/HardcodedUtils.java +++ b/src/com/vodafone360/people/utils/HardcodedUtils.java @@ -1,65 +1,65 @@ /* * 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.Hashtable; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.NetworkPresence; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; /** * @author timschwerdtner * Collection of hardcoded and duplicated code as a first step for refactoring. */ public class HardcodedUtils { -// /** -// * To be used with IPeopleService.setAvailability until identity handling -// * has been refactored. -// * @param Desired availability state -// * @return A hashtable for the set availability call -// */ -// public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) { -// Hashtable<String, String> availability = new Hashtable<String, String>(); -// -// LogUtils.logD("Setting Availability to: " + onlineStatus.toString()); -// // TODO: REMOVE HARDCODE setting everything possible to currentStatus -// availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString()); -// -// return availability; -// } + /** + * To be used with IPeopleService.setAvailability until identity handling + * has been refactored. + * @param Desired availability state + * @return A hashtable for the set availability call + */ + public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) { + Hashtable<String, String> availability = new Hashtable<String, String>(); + + LogUtils.logD("Setting Availability to: " + onlineStatus.toString()); + // TODO: REMOVE HARDCODE setting everything possible to currentStatus + availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString()); + + return availability; + } /** * The static list of supported TPC accounts. */ public static final int[] THIRD_PARTY_CHAT_ACCOUNTS = new int[]{SocialNetwork.FACEBOOK_COM.ordinal(), SocialNetwork.GOOGLE.ordinal(), SocialNetwork.HYVES_NL.ordinal(), SocialNetwork.MICROSOFT.ordinal()}; }
360/360-Engine-for-Android
c3ec6be22344cc6ff629be0d63395360faddfee6
New availability method now used NetworkPresence as the argument
diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index 9a93021..c4f60ae 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,326 +1,326 @@ /* * 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.ContactSummary.OnlineStatus; 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 // TODO: this hard code needs change, must filter the identities // info by VCARD.IMADRESS Hashtable<String, String> status = new Hashtable<String, String>(); status.put("google", "online"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("facebook.com", "online"); status.put("hyves.nl", "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); } } return !ignoredNetworks.isEmpty(); } protected static boolean updateMyPresence(User user, DatabaseHelper dbHelper) { boolean contactsChanged = false; - SQLiteDatabase writableDb = dbHelper.getWritableDatabase(); - if (PresenceTable.updateUser(user, null, writableDb) != PresenceTable.USER_NOTADDED) { + 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); } } /** * @param input * @return */ public static boolean notNullOrBlank(String input) { return (input != null) && input.length() > 0; } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 4f4b9fc..566d9a4 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,744 +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.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.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.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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!canRun()) { 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()) { 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); } @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()) { 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 + "]"); - UiAgent uiAgent = mEventCallback.getUiAgent(); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { - uiAgent.updatePresence(myself.getLocalContactId()); + 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) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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) { LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { Presence.setMyAvailability(((OnlineStatus)data).toString()); completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: if (data != null) { Presence.setMyAvailabilityForCommunity(); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); break; case CREATE_CONVERSATION: if (data != null) { List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setTimeout(CHECK_FREQUENCY); } break; case SEND_CHAT_MESSAGE: if (data != null) { 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); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setTimeout(CHECK_FREQUENCY); } break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); } } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } private void initSetMyAvailabilityRequest(User myself) { if (myself == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED)) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** - * Changes the state of the engine. Also displays the login notification if - * necessary. + * Changes the user's availability and therefore the state of the engine. + * Also displays the login notification if necessary. * - * @param accounts + * @param status Availability to set for all identities we have. */ - public void setMyAvailability(OnlineStatus onlinestatus) { - if (onlinestatus == null) { + 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:"+onlinestatus.toString()); + 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> userPresence = new Hashtable<String, String>(); + Hashtable<String, String> presenceList = new Hashtable<String, String>(); // TODO: Fill up hashtable with identities and online statuses - User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), - userPresence); - Hashtable<String, String> availability = new Hashtable<String, String>(); - for (NetworkPresence presence : myself.getPayload()) { - availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), - OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); - } + User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), + presenceList); + // set the DB values for myself - myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); - updateMyPresenceInDatabase(myself); + me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); + updateMyPresenceInDatabase(me); // set the engine to run now - addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, userPresence); + addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } - public void setMyAvailability(String network, String availability) { - + /** + * 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()) { 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()); } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index 67a4a99..0dbc95b 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,345 +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.interfaces; -import java.util.Hashtable; - import android.os.Bundle; import android.os.Handler; 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.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(); /*** * Begins the process of retrieving Third party Accounts that the user is * already registered with 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 fetchMyIdentities(Bundle data); /*** * 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); - -// /*** -// * Alter the current Social Network availability state and send it to the -// * server. -// * -// * @param myself is the wrapper for the own presence state, can be retrieved -// * from PresenceTable.getUserByLocalContactId(long -// * meProfileLocalContactId). -// */ -// void setAvailability(Hashtable<String, String> myself); /** * Change current global (all identities) availability state. - * @param onlinestatus Availability to set for all identities we have. + * @param status Availability to set for all identities we have. */ - void setAvailability(OnlineStatus onlinestatus); + void setAvailability(OnlineStatus status); /** * Change current availability state for a single network. - * @param network - * @param availability + * @param presence Network-presence to set */ - void setAvailability(String network, String availability); + void setAvailability(NetworkPresence presence); /*** * 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 3674f0e..c80638b 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,425 +1,427 @@ /* * 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.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#fetchAvailableIdentities(Bundle) */ @Override public void fetchAvailableIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiFetchIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchMyIdentities(Bundle) */ @Override public void fetchMyIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(); } /*** * @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(String) + * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(OnlineStatus) */ @Override - public void setAvailability(OnlineStatus onlinestatus) { - EngineManager.getInstance().getPresenceEngine().setMyAvailability(onlinestatus); + public void setAvailability(OnlineStatus status) { + EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** - * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(String, String) + * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(NetworkPresence) */ @Override - public void setAvailability(String network, String availability) { - EngineManager.getInstance().getPresenceEngine().setMyAvailability(network, availability); + public void setAvailability(NetworkPresence presence) { + EngineManager.getInstance().getPresenceEngine().setMyAvailability(presence); } /*** * @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
b4f4c6581f0e4d07f9dab0376c2e37504225a3d3
Minor changes that I missed.
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index c4d50f6..4f4b9fc 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -17,740 +17,728 @@ * 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.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.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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!canRun()) { 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()) { 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); } @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()) { 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 + "]"); UiAgent uiAgent = mEventCallback.getUiAgent(); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { uiAgent.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) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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) { LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { - Presence.setMyAvailability((String)data); + Presence.setMyAvailability(((OnlineStatus)data).toString()); completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); } break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: if (data != null) { Presence.setMyAvailabilityForCommunity(); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); completeUiRequest(ServiceStatus.SUCCESS, null); setTimeout(CHECK_FREQUENCY); break; case CREATE_CONVERSATION: if (data != null) { List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setTimeout(CHECK_FREQUENCY); } break; case SEND_CHAT_MESSAGE: if (data != null) { 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); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setTimeout(CHECK_FREQUENCY); } break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); } } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } private void initSetMyAvailabilityRequest(User myself) { if (myself == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED)) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } -// /** -// * Changes the state of the engine. Also displays the login notification if -// * necessary. -// * -// * @param accounts -// */ -// public void setMyAvailability(Hashtable<String, String> myselfPresence) { -// if (myselfPresence == null) { -// LogUtils.logE("PresenceEngine setMyAvailability:" -// + " Can't send the setAvailability request due to DB reading errors"); -// return; -// } -// -// LogUtils.logV("PresenceEngine setMyAvailability() called with:" + myselfPresence); -// if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { -// LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); -// return; -// } -// -// User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), -// myselfPresence); -// -// Hashtable<String, String> availability = new Hashtable<String, String>(); -// for (NetworkPresence presence : myself.getPayload()) { -// availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), -// OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); -// } -// // set the DB values for myself -// myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); -// updateMyPresenceInDatabase(myself); -// -// // set the engine to run now -// -// addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); -// } - /** + * Changes the state of the engine. Also displays the login notification if + * necessary. * - * @param availability + * @param accounts */ - public void setMyAvailability(String availability) { - if (TextUtils.isEmpty(availability)) { + public void setMyAvailability(OnlineStatus onlinestatus) { + if (onlinestatus == null) { LogUtils.logE("PresenceEngine setMyAvailability:" - + " Can't my availability using empty availability"); + + " Can't send the setAvailability request due to DB reading errors"); return; } - LogUtils.logV("PresenceEngine setMyAvailability() called with:" + availability); + LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+onlinestatus.toString()); + if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { + LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); + return; + } + + // Get presences + Hashtable<String, String> userPresence = new Hashtable<String, String>(); + + // TODO: Fill up hashtable with identities and online statuses + User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), + userPresence); + + Hashtable<String, String> availability = new Hashtable<String, String>(); + for (NetworkPresence presence : myself.getPayload()) { + availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), + OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); + } + // set the DB values for myself + myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); + updateMyPresenceInDatabase(myself); + + // set the engine to run now - addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); + addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, userPresence); } - + public void setMyAvailability(String network, String availability) { } 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()) { 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()); } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index 6fd9379..67a4a99 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,344 +1,345 @@ /* * 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.Hashtable; import android.os.Bundle; import android.os.Handler; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; +import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; 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(); /*** * Begins the process of retrieving Third party Accounts that the user is * already registered with 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 fetchMyIdentities(Bundle data); /*** * 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); // /*** // * Alter the current Social Network availability state and send it to the // * server. // * // * @param myself is the wrapper for the own presence state, can be retrieved // * from PresenceTable.getUserByLocalContactId(long // * meProfileLocalContactId). // */ // void setAvailability(Hashtable<String, String> myself); /** * Change current global (all identities) availability state. - * @param availability Availability to set for all identities we have. + * @param onlinestatus Availability to set for all identities we have. */ - void setAvailability(String availability); + void setAvailability(OnlineStatus onlinestatus); /** * Change current availability state for a single network. * @param network * @param availability */ void setAvailability(String network, String availability); /*** * 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 f3e4033..3674f0e 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,424 +1,425 @@ /* * 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.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.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#fetchAvailableIdentities(Bundle) */ @Override public void fetchAvailableIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiFetchIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchMyIdentities(Bundle) */ @Override public void fetchMyIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(); } /*** * @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(String) */ @Override - public void setAvailability(String availability) { - EngineManager.getInstance().getPresenceEngine().setMyAvailability(availability); + public void setAvailability(OnlineStatus onlinestatus) { + EngineManager.getInstance().getPresenceEngine().setMyAvailability(onlinestatus); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(String, String) */ @Override public void setAvailability(String network, String availability) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(network, availability); } /*** * @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 diff --git a/src/com/vodafone360/people/service/io/api/Presence.java b/src/com/vodafone360/people/service/io/api/Presence.java index 6d7fc80..7f3bccc 100644 --- a/src/com/vodafone360/people/service/io/api/Presence.java +++ b/src/com/vodafone360/people/service/io/api/Presence.java @@ -1,100 +1,102 @@ /* * 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.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(); } /** * API to set my availability * * @param engineId ID of presence engine. - * @param availability Availability to set + * @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 apropriate 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(); } public static void setMyAvailabilityForCommunity() { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.setMyAvailabilityForCommunity() No session, so return"); return; } } }
360/360-Engine-for-Android
f71bf78182adeb7706213f453bb4edef91ec7990
Removed . from README
diff --git a/README b/README index 0c39d43..9defdfe 100644 --- a/README +++ b/README @@ -1 +1 @@ -For detailed documentation please visit http://360.github.com/360-Engine-for-Android. +For detailed documentation please visit http://360.github.com/360-Engine-for-Android
360/360-Engine-for-Android
4934b99a0bb806168e2396f7d6e55d7453a7726b
Added . to README
diff --git a/README b/README index 9defdfe..0c39d43 100644 --- a/README +++ b/README @@ -1 +1 @@ -For detailed documentation please visit http://360.github.com/360-Engine-for-Android +For detailed documentation please visit http://360.github.com/360-Engine-for-Android.
360/360-Engine-for-Android
67ee645c05be823948f5424f686f7b2719140f8e
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 a757bb1..7000fbe 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,793 +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()) { + 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)); } }
360/360-Engine-for-Android
66c9fd7ba1712266ea0b180c9221427896949105
JUnit fix
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java index 81b55e9..3ba9bb4 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java @@ -1,741 +1,747 @@ /* * 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>(); - for (Account account : mNativeContactsApi - .getAccountsByType(NativeContactsApi.GOOGLE_ACCOUNT_TYPE)) { - accountList.add(account); + + Account googleAccounts[]=mNativeContactsApi.getAccountsByType(NativeContactsApi.GOOGLE_ACCOUNT_TYPE); + if (googleAccounts!=null && googleAccounts.length>0){ + for (Account account : mNativeContactsApi + .getAccountsByType(NativeContactsApi.GOOGLE_ACCOUNT_TYPE)) { + accountList.add(account); + } } - for (Account account : mNativeContactsApi - .getAccountsByType(NativeContactsApi.PHONE_ACCOUNT_TYPE)) { - accountList.add(account); + Account phoneAccounts[]=mNativeContactsApi.getAccountsByType(NativeContactsApi.PHONE_ACCOUNT_TYPE); + if (phoneAccounts!=null && phoneAccounts.length>0){ + 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) { // 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++; }
360/360-Engine-for-Android
d0640166a8f9ef2f5c8fd4a2d5c5934cafba4cfb
ContacList SpeedUp
diff --git a/res/layout/contact_list.xml b/res/layout/contact_list.xml index 51b563a..f725127 100644 --- a/res/layout/contact_list.xml +++ b/res/layout/contact_list.xml @@ -1,95 +1,98 @@ <?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:id="@+id/GroupFilter" android:background="@drawable/group_filter_background" android:textAppearance="@style/PeopleTextAppearance.GroupFilter" android:layout_marginTop="@dimen/group_filter_margin_top" android:layout_marginBottom="@dimen/group_filter_margin_bottom" android:layout_width="fill_parent" android:layout_height="@dimen/group_filter_height" android:clickable="true" android:focusable="true" > <include layout="@layout/filter_list_item"/> </LinearLayout> <FrameLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"> <ListView android:id="@+id/group_list" android:layout_height="fill_parent" android:layout_width="fill_parent"> </ListView> <!-- Include the progress bar layout --> <include layout="@layout/progress_layout"/> <!-- Layout to include the main list and the empty view --> <LinearLayout android:id="@+id/contact_list_and_empty_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <ListView android:id="@id/android:list" android:layout_width="fill_parent" - android:layout_height="fill_parent"> + android:layout_height="fill_parent" + android:cacheColorHint="#ffffff" + > + </ListView> <!-- this is needed because when the list above is set to wrap_content the divider normally displayed at the bottom of the list is not visible --> <ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/list_divider_horizontal" android:scaleType="fitXY"/> <ScrollView android:id="@id/android:empty" android:layout_width="fill_parent" android:layout_height="wrap_content" android:fillViewport="true" android:layout_weight="1"> <TextView android:id="@+id/emptyText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/ContactListActivity_TextView_noContacts" android:textSize="20sp" android:textColor="?android:attr/textColorSecondary" android:paddingLeft="10dip" android:paddingRight="10dip" android:paddingTop="10dip" android:lineSpacingMultiplier="0.92"/> </ScrollView> </LinearLayout> </FrameLayout> </LinearLayout> \ No newline at end of file diff --git a/src/com/vodafone360/people/database/tables/ContactSummaryTable.java b/src/com/vodafone360/people/database/tables/ContactSummaryTable.java index 5eaadee..aa82743 100644 --- a/src/com/vodafone360/people/database/tables/ContactSummaryTable.java +++ b/src/com/vodafone360/people/database/tables/ContactSummaryTable.java @@ -1,750 +1,750 @@ /* * 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.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Map.Entry; import android.content.ContentValues; 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 com.vodafone360.people.Settings; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ContactsTable.ContactIdInfo; import com.vodafone360.people.datatypes.Contact; 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.datatypes.ContactSummary.AltFieldType; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.User; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.CloseUtils; import com.vodafone360.people.utils.LogUtils; /** * The ContactSummaryTable contains a summary of important contact details for * each contact such as name, status and Avatar availability. This data is * duplicated here to improve the performance of the main contact list in the UI * (otherwise the a costly inner join between the contact and contact details * table would be needed). This class is never instantiated hence all methods * must be static. * * @version %I%, %G% */ public abstract class ContactSummaryTable { /** * The name of the table as it appears in the database. */ public static final String TABLE_NAME = "ContactSummary"; public static final String TABLE_INDEX_NAME = "ContactSummaryIndex"; /** * This holds the presence information for each contact in the ContactSummaryTable */ private static HashMap<Long, Integer> sPresenceMap = new HashMap<Long, Integer>(); /** * An enumeration of all the field names in the database. */ public static enum Field { SUMMARYID("_id"), LOCALCONTACTID("LocalContactId"), DISPLAYNAME("DisplayName"), STATUSTEXT("StatusText"), ALTFIELDTYPE("AltFieldType"), ALTDETAILTYPE("AltDetailType"), ONLINESTATUS("OnlineStatus"), NATIVEID("NativeId"), FRIENDOFMINE("FriendOfMine"), PICTURELOADED("PictureLoaded"), SNS("Sns"), SYNCTOPHONE("Synctophone"); /** * The 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(String field) { mField = field; } /** * @return the name of the field as it appears in the database. */ public String toString() { return mField; } } /** * Creates ContactSummary Table. * * @param writeableDb A writable SQLite database * @throws SQLException If an SQL compilation error occurs */ public static void create(SQLiteDatabase writeableDb) throws SQLException { DatabaseHelper.trace(true, "ContactSummaryTable.create()"); //TODO: As of now kept the onlinestatus field in table. Would remove it later on writeableDb.execSQL("CREATE TABLE " + TABLE_NAME + " (" + Field.SUMMARYID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.LOCALCONTACTID + " LONG, " + Field.DISPLAYNAME + " TEXT, " + Field.STATUSTEXT + " TEXT, " + Field.ALTFIELDTYPE + " INTEGER, " + Field.ALTDETAILTYPE + " INTEGER, " + Field.ONLINESTATUS + " INTEGER, " + Field.NATIVEID + " INTEGER, " + Field.FRIENDOFMINE + " BOOLEAN, " + Field.PICTURELOADED + " BOOLEAN, " + Field.SNS + " STRING, " + Field.SYNCTOPHONE + " BOOLEAN);"); writeableDb.execSQL("CREATE INDEX " + TABLE_INDEX_NAME + " ON " + TABLE_NAME + " ( " + Field.LOCALCONTACTID + ", " + Field.DISPLAYNAME + " )"); clearPresenceMap(); } /** * Fetches the list of table fields that can be injected into an SQL query * statement. The {@link #getQueryData(Cursor)} method can be used to obtain * the data from the query. * * @return The query string * @see #getQueryData(Cursor). */ private static String getFullQueryList() { return Field.SUMMARYID + ", " + TABLE_NAME + "." + Field.LOCALCONTACTID + ", " + Field.DISPLAYNAME + ", " + Field.STATUSTEXT + ", " + Field.ONLINESTATUS + ", " + Field.NATIVEID + ", " + Field.FRIENDOFMINE + ", " + Field.PICTURELOADED + ", " + Field.SNS + ", " + Field.SYNCTOPHONE + ", " + Field.ALTFIELDTYPE + ", " + Field.ALTDETAILTYPE; } /** * Returns a full SQL query statement to fetch the contact summary * information. The {@link #getQueryData(Cursor)} method can be used to * obtain the data from the query. * * @return The query string * @see #getQueryData(Cursor). */ private static String getOrderedQueryStringSql() { return "SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " ORDER BY LOWER(" + Field.DISPLAYNAME + ")"; } /** * Returns a full SQL query statement to fetch the contact summary * information. The {@link #getQueryData(Cursor)} method can be used to * obtain the data from the query. * * @param whereClause An SQL where clause (without the "WHERE"). Cannot be * null. * @return The query string * @see #getQueryData(Cursor). */ private static String getQueryStringSql(String whereClause) { return "SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE " + whereClause; } /** * Returns a full SQL query statement to fetch the contact summary * information in alphabetical order of contact name. The * {@link #getQueryData(Cursor)} method can be used to obtain the data from * the query. * * @param whereClause An SQL where clause (without the "WHERE"). Cannot be * null. * @return The query string * @see #getQueryData(Cursor). */ private static String getOrderedQueryStringSql(String whereClause) { return "SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE " + whereClause + " ORDER BY LOWER(" + Field.DISPLAYNAME + ")"; } /** * UPDATE ContactSummary SET * NativeId = ? * WHERE LocalContactId = ? */ private static final String UPDATE_NATIVE_ID_BY_LOCAL_CONTACT_ID = "UPDATE " + TABLE_NAME + " SET " + Field.NATIVEID + "=? WHERE " + Field.LOCALCONTACTID + "=?"; /** * Column indices which match the query string returned by * {@link #getFullQueryList()}. */ - private static final int SUMMARY_ID = 0; + public static final int SUMMARY_ID = 0; - private static final int LOCALCONTACT_ID = 1; + public static final int LOCALCONTACT_ID = 1; - private static final int FORMATTED_NAME = 2; + public static final int FORMATTED_NAME = 2; - private static final int STATUS_TEXT = 3; + public static final int STATUS_TEXT = 3; @SuppressWarnings("unused") @Deprecated - private static final int ONLINE_STATUS = 4; + public static final int ONLINE_STATUS = 4; - private static final int NATIVE_CONTACTID = 5; + public static final int NATIVE_CONTACTID = 5; - private static final int FRIEND_MINE = 6; + public static final int FRIEND_MINE = 6; - private static final int PICTURE_LOADED = 7; + public static final int PICTURE_LOADED = 7; - private static final int SNS = 8; + public static final int SNS = 8; - private static final int SYNCTOPHONE = 9; + public static final int SYNCTOPHONE = 9; - private static final int ALTFIELD_TYPE = 10; + public static final int ALTFIELD_TYPE = 10; - private static final int ALTDETAIL_TYPE = 11; + public static final int ALTDETAIL_TYPE = 11; /** * Fetches the contact summary data from the current record of the given * cursor. * * @param c Cursor returned by one of the {@link #getFullQueryList()} based * query methods. * @return Filled in ContactSummary object */ public static ContactSummary getQueryData(Cursor c) { ContactSummary contactSummary = new ContactSummary(); if (!c.isNull(SUMMARY_ID)) { contactSummary.summaryID = c.getLong(SUMMARY_ID); } if (!c.isNull(LOCALCONTACT_ID)) { contactSummary.localContactID = c.getLong(LOCALCONTACT_ID); } contactSummary.formattedName = c.getString(FORMATTED_NAME); contactSummary.statusText = c.getString(STATUS_TEXT); contactSummary.onlineStatus = getPresence(contactSummary.localContactID); if (!c.isNull(NATIVE_CONTACTID)) { contactSummary.nativeContactId = c.getInt(NATIVE_CONTACTID); } if (!c.isNull(FRIEND_MINE)) { contactSummary.friendOfMine = (c.getInt(FRIEND_MINE) == 0 ? false : true); } if (!c.isNull(PICTURE_LOADED)) { contactSummary.pictureLoaded = (c.getInt(PICTURE_LOADED) == 0 ? false : true); } if (!c.isNull(SNS)) { contactSummary.sns = c.getString(SNS); } if (!c.isNull(SYNCTOPHONE)) { contactSummary.synctophone = (c.getInt(SYNCTOPHONE) == 0 ? false : true); } if (!c.isNull(ALTFIELD_TYPE)) { int val = c.getInt(ALTFIELD_TYPE); if (val < AltFieldType.values().length) { contactSummary.altFieldType = AltFieldType.values()[val]; } } if (!c.isNull(ALTDETAIL_TYPE)) { int val = c.getInt(ALTDETAIL_TYPE); if (val < ContactDetail.DetailKeys.values().length) { contactSummary.altDetailType = ContactDetail.DetailKeyTypes.values()[val]; } } return contactSummary; } /** * Fetches the contact summary for a particular contact * * @param localContactID The primary key ID of the contact to find * @param summary A new ContactSummary object to be filled in * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus fetchSummaryItem(long localContactId, ContactSummary summary, SQLiteDatabase readableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(false, "ContactSummeryTable.fetchSummaryItem() localContactId[" + localContactId + "]"); } Cursor c1 = null; try { c1 = readableDb.rawQuery( getQueryStringSql(Field.LOCALCONTACTID + "=" + localContactId), null); if (!c1.moveToFirst()) { LogUtils.logW("ContactSummeryTable.fetchSummaryItem() localContactId[" + localContactId + "] not found in ContactSummeryTable."); return ServiceStatus.ERROR_NOT_FOUND; } summary.copy(getQueryData(c1)); return ServiceStatus.SUCCESS; } catch (SQLiteException e) { LogUtils .logE( "ContactSummeryTable.fetchSummaryItem() Exception - Unable to fetch contact summary", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(c1); c1 = null; } } /** * Processes a ContentValues object to handle a missing name or missing * status. * <ol> * <li>If the name is missing it will be replaced using the alternative * detail.</li> * <li>If the name is present, but status is missing the status will be * replaced using the alternative detail</li> * <li>Otherwise, the althernative detail is not used</li> * </ol> * In any case the {@link Field#ALTFIELDTYPE} value will be updated to * reflect how the alternative detail is being used. * * @param values The ContentValues object to be updated * @param altDetail The must suitable alternative detail (see * {@link #fetchNewAltDetail(long, ContactDetail, SQLiteDatabase)} */ private static void updateAltValues(ContentValues values, ContactDetail altDetail) { if (!values.containsKey(Field.DISPLAYNAME.toString())) { values.put(Field.DISPLAYNAME.toString(), altDetail.getValue()); values.put(Field.ALTFIELDTYPE.toString(), ContactSummary.AltFieldType.NAME.ordinal()); } else if (!values.containsKey(Field.STATUSTEXT.toString())) { values.put(Field.STATUSTEXT.toString(), altDetail.getValue()); values.put(Field.ALTFIELDTYPE.toString(), ContactSummary.AltFieldType.STATUS.ordinal()); } else { values.put(Field.ALTFIELDTYPE.toString(), ContactSummary.AltFieldType.UNUSED.ordinal()); } if (altDetail.keyType != null) { values.put(Field.ALTDETAILTYPE.toString(), altDetail.keyType.ordinal()); } } /** * Processes a ContentValues object to handle a missing name or missing * status. * <ol> * <li>If type is NAME, the name will be set to the alternative detail.</li> * <li>If type is STATUS, the status will be set to the alternative detail</li> * <li>Otherwise, the alternative detail is not used</li> * </ol> * In any case the {@link Field#ALTFIELDTYPE} value will be updated to * reflect how the alternative detail is being used. * * @param values The ContentValues object to be updated * @param altDetail The must suitable alternative detail (see * {@link #fetchNewAltDetail(long, ContactDetail, SQLiteDatabase)} * @param type Specifies how the alternative detail should be used */ /* * private static void updateAltValues(ContentValues values, ContactDetail * altDetail, ContactSummary.AltFieldType type) { switch (type) { case NAME: * values.put(Field.DISPLAYNAME.toString(), altDetail.getValue()); * values.put(Field.ALTFIELDTYPE.toString(), * ContactSummary.AltFieldType.NAME .ordinal()); break; case STATUS: * values.put(Field.STATUSTEXT.toString(), altDetail.getValue()); * values.put(Field.ALTFIELDTYPE.toString(), * ContactSummary.AltFieldType.STATUS .ordinal()); break; default: * values.put(Field.ALTFIELDTYPE.toString(), * ContactSummary.AltFieldType.UNUSED .ordinal()); } if (altDetail.keyType * != null) { values.put(Field.ALTDETAILTYPE.toString(), * altDetail.keyType.ordinal()); } } */ /** * Adds contact summary information to the table for a new contact. If the * contact has no name or no status, an alternative detail will be used such * as telephone number or email address. * * @param contact The new contact * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus addContact(Contact contact, SQLiteDatabase writableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(true, "ContactSummeryTable.addContact() contactID[" + contact.contactID + "]"); } if (contact.localContactID == null) { LogUtils.logE("ContactSummeryTable.addContact() Invalid parameters"); return ServiceStatus.ERROR_NOT_FOUND; } try { final ContentValues values = new ContentValues(); values.put(Field.LOCALCONTACTID.toString(), contact.localContactID); values.put(Field.NATIVEID.toString(), contact.nativeContactId); values.put(Field.FRIENDOFMINE.toString(), contact.friendOfMine); values.put(Field.SYNCTOPHONE.toString(), contact.synctophone); ContactDetail altDetail = findAlternativeNameContactDetail(values, contact.details); updateAltValues(values, altDetail); addToPresenceMap(contact.localContactID); if (writableDb.insertOrThrow(TABLE_NAME, null, values) < 0) { LogUtils.logE("ContactSummeryTable.addContact() " + "Unable to insert new contact summary"); return ServiceStatus.ERROR_NOT_FOUND; } return ServiceStatus.SUCCESS; } catch (SQLException e) { LogUtils.logE("ContactSummeryTable.addContact() SQLException - " + "Unable to insert new contact summary", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } /** * This method returns the most preferred contact detail to be displayed * instead of the contact name when vcard.name is missing. * * @param values - ContentValues to be stored in the DB for the added * contact * @param details - the list of all contact details for the contact being * added * @return the contact detail most suitable to replace the missing * vcard.name. "Value" field may be empty if no suitable contact * detail was found. */ private static ContactDetail findAlternativeNameContactDetail(ContentValues values, List<ContactDetail> details) { ContactDetail altDetail = new ContactDetail(); for (ContactDetail detail : details) { getContactValuesFromDetail(values, detail); if (isPreferredAltDetail(detail, altDetail)) { altDetail.copy(detail); } } return altDetail; } /** * Deletes a contact summary record * * @param localContactID The primary key ID of the contact to delete * @param writableDb Writeable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteContact(Long localContactId, SQLiteDatabase writableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(true, "ContactSummeryTable.deleteContact() localContactId[" + localContactId + "]"); } if (localContactId == null) { LogUtils.logE("ContactSummeryTable.deleteContact() Invalid parameters"); return ServiceStatus.ERROR_NOT_FOUND; } try { if (writableDb.delete(TABLE_NAME, Field.LOCALCONTACTID + "=" + localContactId, null) <= 0) { LogUtils.logE("ContactSummeryTable.deleteContact() " + "Unable to delete contact summary"); return ServiceStatus.ERROR_NOT_FOUND; } deleteFromPresenceMap(localContactId); return ServiceStatus.SUCCESS; } catch (SQLException e) { LogUtils.logE("ContactSummeryTable.deleteContact() SQLException - " + "Unable to delete contact summary", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } /** * Modifies contact parameters. Called when fields in the Contacts table * have been changed. * * @param contact The modified contact * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus modifyContact(Contact contact, SQLiteDatabase writableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(true, "ContactSummeryTable.modifyContact() contactID[" + contact.contactID + "]"); } if (contact.localContactID == null) { LogUtils.logE("ContactSummeryTable.modifyContact() Invalid parameters"); return ServiceStatus.ERROR_NOT_FOUND; } try { final ContentValues values = new ContentValues(); values.put(Field.LOCALCONTACTID.toString(), contact.localContactID); values.put(Field.NATIVEID.toString(), contact.nativeContactId); values.put(Field.FRIENDOFMINE.toString(), contact.friendOfMine); values.put(Field.SYNCTOPHONE.toString(), contact.synctophone); String[] args = { String.format("%d", contact.localContactID) }; if (writableDb.update(TABLE_NAME, values, Field.LOCALCONTACTID + "=?", args) < 0) { LogUtils.logE("ContactSummeryTable.modifyContact() " + "Unable to update contact summary"); return ServiceStatus.ERROR_NOT_FOUND; } return ServiceStatus.SUCCESS; } catch (SQLException e) { LogUtils.logE("ContactSummeryTable.modifyContact() " + "SQLException - Unable to update contact summary", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } /** * Adds suitable entries to a ContentValues objects for inserting or * updating the contact summary table, from a contact detail. * * @param contactValues The content values object to update * @param newDetail The new or modified detail * @return true if the summary table has been updated, false otherwise */ private static boolean getContactValuesFromDetail(ContentValues contactValues, ContactDetail newDetail) { switch (newDetail.key) { case VCARD_NAME: if (newDetail.value != null) { VCardHelper.Name name = newDetail.getName(); if (name != null) { String nameStr = name.toString(); // this is what we do to display names of contacts // coming from server if (nameStr.length() > 0) { contactValues.put(Field.DISPLAYNAME.toString(), name.toString()); } } } return true; case PRESENCE_TEXT: if (newDetail.value != null && newDetail.value.length() > 0) { contactValues.put(Field.STATUSTEXT.toString(), newDetail.value); contactValues.put(Field.SNS.toString(), newDetail.alt); } return true; case PHOTO: if (newDetail.value == null) { contactValues.put(Field.PICTURELOADED.toString(), (Boolean)null); } else { contactValues.put(Field.PICTURELOADED.toString(), false); } return true; default: // Do Nothing. } return false; } /** * Determines if a contact detail should be used in preference to the * current alternative detail (the alternative detail is one that is shown * when a contact has no name or no status). * * @param newDetail The new detail * @param currentDetail The current alternative detail * @return true if the new detail should be used, false otherwise */ private static boolean isPreferredAltDetail(ContactDetail newDetail, ContactDetail currentDetail) { // this means we'll update the detail if (currentDetail.key == null || (currentDetail.key == DetailKeys.UNKNOWN)) { return true; } switch (newDetail.key) { case VCARD_PHONE: // AA:EMAIL,IMADDRESS,ORG will not be updated, PHONE will // consider "preferred" detail check switch (currentDetail.key) { case VCARD_EMAIL: case VCARD_IMADDRESS: case VCARD_ORG: case VCARD_ADDRESS: case VCARD_BUSINESS: case VCARD_TITLE: case VCARD_ROLE: return false; case VCARD_PHONE: break; default: return true; } break; case VCARD_IMADDRESS: // AA:will be updating everything, except for EMAIL and ORG, and // IMADDRESS, when preferred details needs to be considered // first switch (currentDetail.key) { case VCARD_IMADDRESS: break; case VCARD_EMAIL: case VCARD_ORG: case VCARD_ROLE: case VCARD_TITLE: return false; default: return true; } break; case VCARD_ADDRESS: case VCARD_BUSINESS: // AA:will be updating everything, except for EMAIL and ORG, // when preferred details needs to be considered first switch (currentDetail.key) { case VCARD_EMAIL: case VCARD_ORG: case VCARD_ROLE: case VCARD_TITLE: return false; case VCARD_ADDRESS: case VCARD_BUSINESS: break; default: return true; } break; case VCARD_ROLE: case VCARD_TITLE: // AA:will be updating everything, except for EMAIL and ORG, // when preferred details needs to be considered first switch (currentDetail.key) { case VCARD_EMAIL: case VCARD_ORG: 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() " @@ -768,619 +768,619 @@ public abstract class ContactSummaryTable { 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 updateNameAndStatus(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.DetailKeys prefferredStatusDetails[] = { ContactDetail.DetailKeys.PRESENCE_TEXT, ContactDetail.DetailKeys.VCARD_PHONE, ContactDetail.DetailKeys.VCARD_EMAIL }; ContactDetail name = null; ContactDetail status = 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; } } // Query the details for status field for (ContactDetail.DetailKeys key : prefferredStatusDetails) { if ((status = contact.getContactDetail(key)) != null) { // Some contacts have only email but the name detail!=null // (gmail for example) if (key == ContactDetail.DetailKeys.VCARD_NAME && status.getName() == null) continue; if (key != ContactDetail.DetailKeys.VCARD_NAME && isEmpty(status.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(); // Build the status String statusString = status != null ? status.getValue() : null; if (statusString == null) statusString = ""; if (status != null && status.key == ContactDetail.DetailKeys.VCARD_NAME) statusString = status.getName().toString(); int altFieldType = AltFieldType.STATUS.ordinal(); int altDetailType = (status != null && status.keyType != null) ? status.keyType.ordinal() : ContactDetail.DetailKeyTypes.UNKNOWN.ordinal(); // This has to be done in order to set presence text. altFieldType and // altDetailType have to be 0, SNS has to be set String sns = ""; if (status != null && status.key == ContactDetail.DetailKeys.PRESENCE_TEXT) { altFieldType = AltFieldType.UNUSED.ordinal(); altDetailType = 0; sns = status.alt; } // If no status is present, display nothing if (isEmpty(statusString)) { altFieldType = AltFieldType.UNUSED.ordinal(); altDetailType = 0; } // Start updating the table SQLiteStatement statement = null; try { statement = writableDb.compileStatement("UPDATE " + TABLE_NAME + " SET " + Field.DISPLAYNAME + "=?," + Field.STATUSTEXT + "=?," + Field.ALTDETAILTYPE + "=?," + Field.ALTFIELDTYPE + "=?," + Field.SNS + "=? WHERE " + Field.LOCALCONTACTID + "=?"); writableDb.beginTransaction(); statement.bindString(1, nameString); statement.bindString(2, statusString); statement.bindLong(3, altDetailType); statement.bindLong(4, altFieldType); statement.bindString(5, sns); statement.bindLong(6, 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 */ - private synchronized static OnlineStatus getPresence(Long localContactID) { + 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
5bed6021c774f0588f34135eb7ec618c4b5e8d8d
Migrate engine changes from the old SVN project to the new project set-up. Engine changes work on both old UI and UI refresh projects.
diff --git a/src/com/vodafone360/people/engine/login/LoginEngine.java b/src/com/vodafone360/people/engine/login/LoginEngine.java index 97fbc40..7ebb18b 100644 --- a/src/com/vodafone360/people/engine/login/LoginEngine.java +++ b/src/com/vodafone360/people/engine/login/LoginEngine.java @@ -1,1375 +1,1423 @@ /* * 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; /** * 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(); /** * Used to verify datatype of server response to request activation code and * activation account. */ private static final String STATUS_MSG = "StatusMsg"; /** * Used to verify datatype of server response for * {@link Auth#getSessionByCredentials} request. */ private static final String AUTH_SESSION_HOLDER = "AuthSessionHolder"; /** * 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.startSignUp()"); + LogUtils.logD("LoginEngine.startFetchTermsOfService()"); if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - completeUiRequest(ServiceStatus.ERROR_COMMS, null); + updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } newState(State.FETCHING_TERMS_OF_SERVICE); if (!setReqId(Auth.getTermsAndConditions(this))) { - completeUiRequest(ServiceStatus.ERROR_COMMS, null); + 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) { - completeUiRequest(ServiceStatus.ERROR_COMMS, null); + updateTermsState(ServiceStatus.ERROR_COMMS, null); return; } newState(State.FETCHING_PRIVACY_STATEMENT); if (!setReqId(Auth.getPrivacyStatement(this))) { - completeUiRequest(ServiceStatus.ERROR_COMMS, null); + 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("Contact", 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("PublicKeyDetails", 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(AUTH_SESSION_HOLDER, 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(AUTH_SESSION_HOLDER, 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(STATUS_MSG, 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(STATUS_MSG, 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("SimpleText", 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("SimpleText", 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); } /** * 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
5fc4096a9b847dc72ea974173a54557956e6f5c3
Fixing up the broken code caused by previous failed merge
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index fe1b6a4..a757bb1 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -28,769 +28,766 @@ 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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { return -1; } if (!canRun()) { 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()) { 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); } @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()) { 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()) { 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(((OnlineStatus)data).toString()); + Presence.setMyAvailability((Hashtable<String,String>)data); break; - case SET_MY_AVAILABILITY_FOR_COMMUNITY: - Presence.setMyAvailabilityForCommunity(); - 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()) { 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()) { 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/ServiceUiRequest.java b/src/com/vodafone360/people/service/ServiceUiRequest.java index caf24d7..3221220 100644 --- a/src/com/vodafone360/people/service/ServiceUiRequest.java +++ b/src/com/vodafone360/people/service/ServiceUiRequest.java @@ -1,267 +1,263 @@ /* * 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, - /** - * Request to set the presence availability status for a single community - */ - SET_MY_AVAILABILITY_FOR_COMMUNITY, /** 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, /* * 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/io/api/Presence.java b/src/com/vodafone360/people/service/io/api/Presence.java index d9a71ac..9c4a1f4 100644 --- a/src/com/vodafone360/people/service/io/api/Presence.java +++ b/src/com/vodafone360/people/service/io/api/Presence.java @@ -1,115 +1,86 @@ /* * 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; } 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(); - } - - public static void setMyAvailabilityForCommunity() { - if (LoginEngine.getSession() == null) { - LogUtils.logE("Presence.setMyAvailabilityForCommunity() No session, so return"); - return; - } - } }
360/360-Engine-for-Android
d67812d47f7186b49441d581c9027805d31c5b8d
ContentEngine crash fixed
diff --git a/src/com/vodafone360/people/engine/content/ContentEngine.java b/src/com/vodafone360/people/engine/content/ContentEngine.java index 8ba6193..fa12db9 100644 --- a/src/com/vodafone360/people/engine/content/ContentEngine.java +++ b/src/com/vodafone360/people/engine/content/ContentEngine.java @@ -1,250 +1,250 @@ /* * 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.util.Hashtable; import java.util.List; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.ExternalResponseObject; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.SystemNotification; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.io.QueueManager; import com.vodafone360.people.service.io.Request; import com.vodafone360.people.service.io.ResponseQueue.Response; /** * Content engine for downloading and uploading all kind of content (pictures, * videos, files) */ public class ContentEngine extends BaseEngine { /** * Constructor for the ContentEngine. * * @param eventCallback IEngineEventCallback for calling the constructor of * the super class * @param dbHelper Instance of DatabaseHelper */ public ContentEngine(final IEngineEventCallback eventCallback, final DatabaseHelper dbHelper) { super(eventCallback); this.mDbHelper = dbHelper; mEngineId = EngineId.CONTENT_ENGINE; } /** * Queue with unprocessed ContentObjects. */ private FiFoQueue mUnprocessedQueue = new FiFoQueue(); /** * Queue with ContentObjects for downloads. */ private FiFoQueue mDownloadQueue = new FiFoQueue(); /** * Queue with ContentObjects for uploads. */ private FiFoQueue mUploadQueue = new FiFoQueue(); /** * Instance of DatabaseHelper. */ private DatabaseHelper mDbHelper; /** * Hashtable to match requests to ContentObjects. */ private Hashtable<Integer, ContentObject> requestContentObjectMatchTable = new Hashtable<Integer, ContentObject>(); /** * Getter for the local instance of DatabaseHelper. * * @return local instance of DatabaseHelper */ public final DatabaseHelper getDatabaseHelper() { return mDbHelper; } /** * Processes one ContentObject. * * @param co ContentObject to be processed */ public final void processContentObject(final ContentObject co) { mUnprocessedQueue.add(co); } /** * Iterates over the ContentObject list and processes every element. * * @param list List with ContentObjects which are to be processed */ public final void processContentObjects(final List<ContentObject> list) { for (ContentObject co : list) { processContentObject(co); } } /** * Processes the main queue and splits it into the download and upload * queues. */ private void processQueue() { ContentObject co; // picking unprocessed ContentObjects while ((co = mUnprocessedQueue.poll()) != null) { // putting them to downloadqueue ... if (co.getDirection() == ContentObject.TransferDirection.DOWNLOAD) { mDownloadQueue.add(co); } else { // ... or the uploadqueue mUploadQueue.add(co); } } } /** * Determines the next RunTime of this Engine It first processes the * in-queue and then look. * * @return time in milliseconds from now when the engine should be run */ @Override public final long getNextRunTime() { processQueue(); // if there are CommsResponses outstanding, run now if (isCommsResponseOutstanding()) { return 0; } return (mDownloadQueue.size() + mUploadQueue.size() > 0) ? 0 : -1; } /** * Empty implementation without function at the moment. */ @Override public void onCreate() { } /** * Empty implementation without function at the moment. */ @Override public void onDestroy() { } /** * Empty implementation without function at the moment. */ @Override protected void onRequestComplete() { } /** * Empty implementation without function at the moment. */ @Override protected void onTimeoutEvent() { } /** * Processes the response Finds the matching contentobject for the repsonse * using the id of the response and sets its status to done. At last the * TransferComplete method of the ContentObject is called. * * @param resp Response object that has been processed */ @Override protected final void processCommsResponse(final Response resp) { ContentObject co = requestContentObjectMatchTable.remove(resp.mReqId); if (co == null) { // check if we have an invalid response return; } List<BaseDataType> mDataTypes = resp.mDataTypes; - // Sometimes it is empty - if (mDataTypes == null) { + // Sometimes it is null or empty + if (mDataTypes == null || mDataTypes.size()==0) { co.setTransferStatus(ContentObject.TransferStatus.ERROR); RuntimeException exc = new RuntimeException("Empty response returned"); co.getTransferListener().transferError(co, exc); return; } Object data = mDataTypes.get(0); if (mDataTypes.get(0).name().equals(ServerError.class.getSimpleName()) || mDataTypes.get(0).name().equals(SystemNotification.class.getSimpleName())) { co.setTransferStatus(ContentObject.TransferStatus.ERROR); RuntimeException exc = new RuntimeException(data.toString()); co.getTransferListener().transferError(co, exc); } else { co.setTransferStatus(ContentObject.TransferStatus.DONE); co.setExtResponse((ExternalResponseObject) data); co.getTransferListener().transferComplete(co); } } /** * Empty implementation of abstract method from BaseEngine. */ @Override protected void processUiRequest(final ServiceUiRequest requestId, final Object data) { } /** * run method of this engine iterates over the downloadqueue, makes requests * out of ContentObjects and puts them into QueueManager queue. */ @Override public final void run() { if (isCommsResponseOutstanding() && processCommsInQueue()) { return; } ContentObject co; boolean queueChanged = false; while ((co = mDownloadQueue.poll()) != null) { queueChanged = true; // set the status of this contentobject to transferring co.setTransferStatus(ContentObject.TransferStatus.TRANSFERRING); Request request = new Request(co.getUrl().toString(), co.getUrlParams(), engineId()); QueueManager.getInstance().addRequest(request); // important: later we will match done requests back to the // contentobject using this map requestContentObjectMatchTable.put(request.getRequestId(), co); } if (queueChanged) { QueueManager.getInstance().fireQueueStateChanged(); } } }
360/360-Engine-for-Android
7644565040f762dff40565e7e9ac72d0b0ed25ee
fixed broken unit tests
diff --git a/tests/src/com/vodafone360/people/tests/datatypes/NowPlusDatatypesTests.java b/tests/src/com/vodafone360/people/tests/datatypes/NowPlusDatatypesTests.java index 511470c..d9c78b1 100644 --- a/tests/src/com/vodafone360/people/tests/datatypes/NowPlusDatatypesTests.java +++ b/tests/src/com/vodafone360/people/tests/datatypes/NowPlusDatatypesTests.java @@ -1,425 +1,426 @@ /* * 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.datatypes; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Vector; import com.vodafone360.people.datatypes.ActivityContact; +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.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.ItemList; import com.vodafone360.people.datatypes.PublicKeyDetails; import com.vodafone360.people.datatypes.PushEvent; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.datatypes.UserProfile; import com.vodafone360.people.datatypes.IdentityCapability.CapabilityID; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.io.rpg.PushMessageTypes; import com.vodafone360.people.service.io.rpg.RpgPushMessage; import android.test.AndroidTestCase; public class NowPlusDatatypesTests extends AndroidTestCase { public void testActivityContact() { ActivityContact input = new ActivityContact(); input.mAddress = "foo"; input.mAvatarUrl = "foo"; input.mContactId = 1L; input.mName = "bar"; input.mNetwork = "mob"; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("address", input.mAddress); hash.put("avatarurl", input.mAvatarUrl); hash.put("contactid", input.mContactId); hash.put("name", input.mName); hash.put("network", input.mNetwork); ActivityContact output = ActivityContact.createFromHashTable(hash); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mAddress, output.mAddress); assertEquals(input.mAvatarUrl, output.mAvatarUrl); assertEquals(input.mContactId, output.mContactId); assertEquals(input.mName, output.mName); assertEquals(input.mNetwork, output.mNetwork); } public void testContactChanges() { List<Contact> contacts = new ArrayList<Contact>(); long currentServerVersion = 1; long versionAnchor = 2; int numberOfPages = 3; long serverRevisionBefore = 4; long serverRevisionAfter = 5; Hashtable<String, Object> hashUserProfile = new Hashtable<String, Object>(); ContactChanges input = new ContactChanges(); input.mContacts = contacts; input.mCurrentServerVersion = ((Long) currentServerVersion).intValue(); input.mVersionAnchor = ((Long) versionAnchor).intValue(); input.mNumberOfPages = numberOfPages; input.mServerRevisionBefore = ((Long) serverRevisionBefore).intValue(); input.mServerRevisionAfter = ((Long) serverRevisionAfter).intValue(); input.mUserProfile = UserProfile.createFromHashtable(hashUserProfile); Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("contact", contacts); hash.put("currentserverrevision", currentServerVersion); hash.put("serverrevisionanchor", versionAnchor); hash.put("numpages", numberOfPages); hash.put("serverrevisionbefore", serverRevisionBefore); hash.put("serverrevisionafter", serverRevisionAfter); hash.put("userprofile", hashUserProfile); ContactChanges helper = new ContactChanges(); ContactChanges output = helper.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mContacts, output.mContacts); assertEquals(input.mCurrentServerVersion, output.mCurrentServerVersion); assertEquals(input.mNumberOfPages, output.mNumberOfPages); assertEquals(input.mServerRevisionBefore, output.mServerRevisionBefore); assertEquals(input.mServerRevisionAfter, output.mServerRevisionAfter); } public void testContactDetailDeletion() { long serverVersionBefore = 1; long serverVersionAfter = 2; long contactId = 3; ContactDetailDeletion input = new ContactDetailDeletion(); input.mServerVersionBefore = ((Long) serverVersionBefore).intValue(); input.mServerVersionAfter = ((Long) serverVersionAfter).intValue(); input.mContactId = ((Long) contactId).intValue(); Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("serverrevisionbefore", serverVersionBefore); hash.put("serverrevisionafter", serverVersionAfter); hash.put("contactid", contactId); ContactDetailDeletion helper = new ContactDetailDeletion(); ContactDetailDeletion output = helper.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mServerVersionBefore, output.mServerVersionBefore); assertEquals(input.mServerVersionAfter, output.mServerVersionAfter); assertEquals(input.mContactId, output.mContactId); } public void testContactListResponse() { long serverRevisionBefore = 1; long serverRevisionAfter = 2; List<Integer> contactIdList = new ArrayList<Integer>(); Integer contactId = 3; ContactListResponse input = new ContactListResponse(); input.mServerRevisionBefore = ((Long) serverRevisionBefore).intValue(); input.mServerRevisionAfter = ((Long) serverRevisionAfter).intValue(); input.mContactIdList = contactIdList; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("serverrevisionbefore", serverRevisionBefore); hash.put("serverrevisionafter", serverRevisionAfter); hash.put("contactidlist", contactIdList); hash.put("contactid", contactId); ContactListResponse helper = new ContactListResponse(); ContactListResponse output = helper.createFromHashTable(hash); // createFromHashTable should be static input.mContactIdList.add(contactId); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mServerRevisionBefore, output.mServerRevisionBefore); assertEquals(input.mServerRevisionAfter, output.mServerRevisionAfter); assertEquals(input.mContactIdList, output.mContactIdList); } public void testGroupItem() { int groupType = 1; boolean isReadOnly = true; boolean requiresLocalisation = true; boolean isSystemGroup = true; boolean isSmartGroup = true; long id = 3; long userId = 4; String name = "foo"; GroupItem input = new GroupItem(); input.mGroupType = (Integer) groupType; input.mIsReadOnly = (Boolean) isReadOnly; input.mRequiresLocalisation = (Boolean) requiresLocalisation; input.mIsSystemGroup = (Boolean) isSystemGroup; input.mIsSmartGroup = (Boolean) isSmartGroup; input.mId = (Long) id; input.mUserId = (Long) userId; input.mName = name; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("grouptype", groupType); hash.put("isreadonly", isReadOnly); hash.put("requireslocalisation", requiresLocalisation); hash.put("issystemgroup", isSystemGroup); hash.put("issmartgroup", isSmartGroup); hash.put("id", id); hash.put("userid", userId); hash.put("name", name); GroupItem helper = new GroupItem(); GroupItem output = helper.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mGroupType, output.mGroupType); assertEquals(input.mIsReadOnly, output.mIsReadOnly); assertEquals(input.mRequiresLocalisation, output.mRequiresLocalisation); assertEquals(input.mIsSystemGroup, output.mIsSystemGroup); assertEquals(input.mIsSmartGroup, output.mIsSmartGroup); assertEquals(input.mId, output.mId); assertEquals(input.mUserId, output.mUserId); assertEquals(input.mName, output.mName); } public void testIdentityCapability() { IdentityCapability input = new IdentityCapability(); input.mCapability = CapabilityID.share_media; input.mDescription = "des"; input.mName = "name"; input.mValue = true; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("capabilityid", input.mCapability.name()); hash.put("description", input.mDescription); hash.put("name", input.mName); hash.put("value", input.mValue); IdentityCapability helper = new IdentityCapability(); IdentityCapability output = helper.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.describeContents(), output.describeContents()); assertEquals(input.mCapability, output.mCapability); assertEquals(input.mDescription, output.mDescription); assertEquals(input.mName, output.mName); assertEquals(input.mValue, output.mValue); } public void testIdentity() { Identity input = new Identity(); input.mPluginId = "pluginid"; input.mNetwork = "network"; input.mIdentityId = "identityId"; input.mDisplayName = "displayname"; input.mCreated = new Long(12); input.mUpdated = new Long(23); input.mActive = true; input.mAuthType = "none"; input.mIdentityType = "chat"; input.mUserId = new Integer(1234); input.mUserName = "bob"; input.mCountryList = new ArrayList<String>(); String urlString = "http://www.mobica.com/"; try { input.mNetworkUrl = new URL(urlString); } catch (MalformedURLException e) { input.mNetworkUrl = null; } Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("pluginid", input.mPluginId); hash.put("network", input.mNetwork); hash.put("identityid", input.mIdentityId); hash.put("displayname", input.mDisplayName); hash.put("networkurl", urlString); hash.put("created", input.mCreated); hash.put("updated", input.mUpdated); hash.put("active", true); hash.put("authtype",input.mAuthType); hash.put("identitytype",input.mIdentityType); hash.put("userid",new Long(1234)); hash.put("username",input.mUserName); hash.put("countrylist",input.mCountryList); Identity helper = new Identity(); Identity output = helper.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertTrue(input.isSameAs(output)); } public void testItemList() { ItemList groupPriv = new ItemList(ItemList.Type.group_privacy); int groupType = 1; boolean isReadOnly = true; boolean requiresLocalisation = true; boolean isSystemGroup = true; boolean isSmartGroup = true; long id = 3; long userId = 4; String name = "foo"; Hashtable<String, Object> hashGroup = new Hashtable<String, Object>(); hashGroup.put("grouptype", groupType); hashGroup.put("isreadonly", isReadOnly); hashGroup.put("requireslocalisation", requiresLocalisation); hashGroup.put("issystemgroup", isSystemGroup); hashGroup.put("issmartgroup", isSmartGroup); hashGroup.put("id", id); hashGroup.put("userid", userId); hashGroup.put("name", name); Vector<Hashtable<String, Object>> vect = new Vector<Hashtable<String, Object>>(); vect.add(hashGroup); Hashtable<String, Object> hashItemListGroup = new Hashtable<String, Object>(); hashItemListGroup.put("itemlist", vect); groupPriv.populateFromHashtable(hashItemListGroup); GroupItem helper = new GroupItem(); GroupItem input = helper.createFromHashtable(hashGroup); GroupItem output = (GroupItem) groupPriv.mItemList.get(0); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mGroupType, output.mGroupType); assertEquals(input.mIsReadOnly, output.mIsReadOnly); assertEquals(input.mRequiresLocalisation, output.mRequiresLocalisation); assertEquals(input.mIsSystemGroup, output.mIsSystemGroup); assertEquals(input.mIsSmartGroup, output.mIsSmartGroup); assertEquals(input.mId, output.mId); assertEquals(input.mUserId, output.mUserId); assertEquals(input.mName, output.mName); } public void testPublicKeyDetails() { byte[] modulo = new byte[] {0, 0}; byte[] exponential = new byte[] {0, 1}; byte[] key = new byte[] {1, 1}; String keyBase64 = "64"; PublicKeyDetails input = new PublicKeyDetails(); input.mModulus = modulo; input.mExponential = exponential; input.mKeyX509 = key; input.mKeyBase64 = keyBase64; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("modulo", modulo); hash.put("exponential", exponential); hash.put("key", key); hash.put("keybase64", keyBase64); PublicKeyDetails output = PublicKeyDetails.createFromHashtable(hash); assertEquals(input.describeContents(), output.describeContents()); - assertEquals(input.name(), output.name()); + assertEquals(input.getType(), output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mModulus, output.mModulus); assertEquals(input.mExponential, output.mExponential); assertEquals(input.mKeyX509, output.mKeyX509); assertEquals(input.mKeyBase64, output.mKeyBase64); } public void testCreatePushEvent() { RpgPushMessage msg = new RpgPushMessage(); msg.mType = PushMessageTypes.CONTACTS_CHANGE; EngineId engId = EngineId.ACTIVITIES_ENGINE; PushEvent input = (PushEvent) PushEvent.createPushEvent(msg, engId); - assertEquals("PushEvent", input.name()); + assertEquals(BaseDataType.PUSH_EVENT_DATA_TYPE, input.getType()); assertEquals(msg.mType, input.mMessageType); assertEquals(engId, input.mEngineId); } public void testStatusMsg() { boolean status = true; boolean dryRun = true; StatusMsg input = new StatusMsg(); input.mStatus = (Boolean) status; input.mDryRun = (Boolean) dryRun; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("status", status); hash.put("dryrun", dryRun); StatusMsg helper = new StatusMsg(); StatusMsg output = helper.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(BaseDataType.STATUS_MSG_DATA_TYPE, output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.mStatus, output.mStatus); assertEquals(input.mDryRun, output.mDryRun); } public void testUserProfile() { UserProfile input = new UserProfile(); input.userID = 50L; input.aboutMe = "newAboutMe"; input.contactID = 10L; input.gender = 1; input.profilePath = "foo"; input.updated = 2L; ContactDetail contactDetail = new ContactDetail(); contactDetail.value = "00000000"; Hashtable<String, Object> hash = new Hashtable<String, Object>(); hash.put("userid", input.userID); hash.put("aboutme", input.aboutMe); hash.put("contactid", input.contactID); hash.put("gender", input.gender); hash.put("profilepath", input.profilePath); hash.put("updated", input.updated); UserProfile output = UserProfile.createFromHashtable(hash); - assertEquals(input.name(), output.name()); + assertEquals(BaseDataType.USER_PROFILE_DATA_TYPE, output.getType()); assertEquals(input.toString(), output.toString()); assertEquals(input.userID, output.userID); assertEquals(input.aboutMe, output.aboutMe); assertEquals(input.contactID, output.contactID); assertEquals(input.gender, output.gender); assertEquals(input.profilePath, output.profilePath); assertEquals(input.updated, output.updated); } } diff --git a/tests/src/com/vodafone360/people/tests/engine/ActivitiesEngineTest.java b/tests/src/com/vodafone360/people/tests/engine/ActivitiesEngineTest.java index 070c543..0d3e910 100644 --- a/tests/src/com/vodafone360/people/tests/engine/ActivitiesEngineTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/ActivitiesEngineTest.java @@ -1,504 +1,502 @@ /* * 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.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(0, data, mEng.engineId()); 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(reqId, data, engine); 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(); data.add(item2); respQueue.addToResponseQueue(reqId, data, engine); 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"; 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(); for (int i = 0; i < 23; i++) { item4.mPreview.putChar((char)i); } item4.mPreviewMime = "jepg"; item4.mPreviewUrl = "storeurl"; item4.mStore = "google"; item4.mVisibilityFlags = 0; data.add(item4); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; case GET_ACTIVITIES_SERVER_ERR: - ServerError err = new ServerError(); - err.errorType = "Catastrophe"; - err.errorValue = "Fail"; + ServerError err = new ServerError("Catastrophe"); + err.errorDescription = "Fail"; data.add(err); respQueue.addToResponseQueue(reqId, data, engine); 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(reqId, data, engine); mEng.onCommsInMessage(); break; case SET_STATUS: Identity id3 = new Identity(); data.add(id3); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; case ON_SYNC_COMPLETE: - ServerError err2 = new ServerError(); - err2.errorType = "Catastrophe"; - err2.errorValue = "Fail"; + ServerError err2 = new ServerError("Catastrophe"); + err2.errorDescription = "Fail"; data.add(err2); respQueue.addToResponseQueue(reqId, data, engine); 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/EngineTestFramework.java b/tests/src/com/vodafone360/people/tests/engine/EngineTestFramework.java index acb5ed9..5d7eaa8 100644 --- a/tests/src/com/vodafone360/people/tests/engine/EngineTestFramework.java +++ b/tests/src/com/vodafone360/people/tests/engine/EngineTestFramework.java @@ -1,265 +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.tests.engine; import java.util.ArrayList; import java.util.List; import android.util.Log; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.datatypes.AuthSessionHolder; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.login.LoginEngine; 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.ResponseQueue; import com.vodafone360.people.service.transport.IConnection; import com.vodafone360.people.tests.IPeopleTestFramework; import com.vodafone360.people.tests.PeopleTestConnectionThread; public class EngineTestFramework implements IEngineEventCallback, IPeopleTestFramework { private Thread mEngineWorkerThread = null; private BaseEngine mEngine = null; private boolean mActive = false; private IEngineTestFrameworkObserver mObserver; private PeopleTestConnectionThread mConnThread = null; private Object mEngReqLock = new Object(); private Object mObjectLock = new Object(); private AuthSessionHolder mSession = new AuthSessionHolder(); private int mStatus; private Object mData = null; private boolean mRequestCompleted; private static int K_REQ_TIMEOUT_MSA = 60000; public EngineTestFramework(IEngineTestFrameworkObserver observer) { Log.d("TAG", "EngineTestFramework.EngineTestFramework"); mObserver = observer; // setup dummy session mSession.userID = 0; mSession.sessionSecret = new String("sssh"); mSession.userName = new String("bob"); mSession.sessionID = new String("session"); LoginEngine.setTestSession(mSession); // create a 'worker' thread for engines to kick mEngineWorkerThread = new Thread(new Runnable() { @Override public void run() { Log.d("TAG", "run"); while (mActive) { // Log.d("TAG", "eng framework active"); long mCurrentTime = System.currentTimeMillis(); long nextRunTime = -1; try { nextRunTime = mEngine.getNextRunTime(); } catch (Exception e) { onEngineException(e); } if (nextRunTime != -1 && nextRunTime <= mCurrentTime) { Log.d("TAG", "run the engine"); try { mEngine.run(); } catch (Exception e) { onEngineException(e); } } else { // Log.d("TAG", "eng framework inactive"); synchronized (mObjectLock) { try { // Log.d("TAG", "lock the engine"); mObjectLock.wait(500); } catch (Exception e) { } } } } } }); } public void setEngine(BaseEngine eng) { Log.d("TAG", "enginetestframework.setEngine"); if (eng == null) { throw (new RuntimeException("Engine is null")); } mEngine = eng; // start our 'worker' thread mActive = true; // start the connection thread mConnThread = new PeopleTestConnectionThread(this); mConnThread.startThread(); // start the worker thread mEngineWorkerThread.start(); QueueManager.getInstance().addQueueListener(mConnThread); } public ServiceStatus waitForEvent() { return waitForEvent(K_REQ_TIMEOUT_MSA); } public ServiceStatus waitForEvent(int ts) { Log.d("TAG", "EngineTestFramework waitForEvent"); NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); kickWorkerThread(); long endTime = System.nanoTime() + (((long)ts) * 1000000); ServiceStatus returnStatus = ServiceStatus.ERROR_UNEXPECTED_RESPONSE; mStatus = 5; // ERROR_COMMS_TIMEOUT synchronized (mEngReqLock) { while (!mRequestCompleted && System.nanoTime() < endTime) { try { mEngReqLock.wait(ts); } catch (InterruptedException e) { } } returnStatus = ServiceStatus.fromInteger(mStatus); } mRequestCompleted = false; return returnStatus; } @Override public void kickWorkerThread() { Log.d("TAG", "kickWorkerThread"); synchronized (mObjectLock) { mObjectLock.notify(); } } @Override public void onUiEvent(ServiceUiRequest event, int request, int status, Object data) { mRequestCompleted = true; // mActive = false; mStatus = status; mData = data; synchronized (mEngReqLock) { mEngReqLock.notify(); } } public Object data() { return mData; } @Override public void reportBackToFramework(int reqId, EngineId engine) { Log.d("TAG", "EngineTestFramework.reportBackToFramework"); mObserver.reportBackToEngine(reqId, engine); final QueueManager reqQ = QueueManager.getInstance(); final ResponseQueue respQ = ResponseQueue.getInstance(); if (reqQ.getRequest(reqId) != null) { List<BaseDataType> dataTypeList = new ArrayList<BaseDataType>(); - ServerError err = new ServerError(); - err.errorType = ServerError.ErrorTypes.UNKNOWN.toString(); + ServerError err = new ServerError(ServerError.ErrorType.UNKNOWN); dataTypeList.add(err); respQ.addToResponseQueue(reqId, dataTypeList, engine); } } @Override public IConnection testConnectionThread() { // TODO Auto-generated method stub return null; } public void callRun(int reqId, List<BaseDataType> data) { ResponseQueue.getInstance().addToResponseQueue(reqId, data, mEngine.engineId()); try { mEngine.onCommsInMessage(); mEngine.run(); } catch (Exception e) { onEngineException(e); } } public void stopEventThread() { QueueManager.getInstance().removeQueueListener(mConnThread); synchronized (mObjectLock) { mActive = false; mObjectLock.notify(); } mConnThread.stopThread(); } private void onEngineException(Exception e) { String strExceptionInfo = e + "\n"; for (int i = 0; i < e.getStackTrace().length; i++) { StackTraceElement v = e.getStackTrace()[i]; strExceptionInfo += "\t" + v + "\n"; } Log.e("TAG", "Engine exception occurred\n" + strExceptionInfo); mObserver.onEngineException(e); synchronized (mEngReqLock) { mActive = false; mStatus = ServiceStatus.ERROR_UNKNOWN.ordinal(); mData = e; mEngReqLock.notify(); } } @Override public UiAgent getUiAgent() { // TODO Auto-generated method stub return null; } @Override public ApplicationCache getApplicationCache() { // TODO Auto-generated method stub return null; } } \ No newline at end of file diff --git a/tests/src/com/vodafone360/people/tests/engine/IdentityEngineTest.java b/tests/src/com/vodafone360/people/tests/engine/IdentityEngineTest.java index 5b9521b..8c93a11 100644 --- a/tests/src/com/vodafone360/people/tests/engine/IdentityEngineTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/IdentityEngineTest.java @@ -1,352 +1,350 @@ /* * 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.net.URL; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.identities.IdentityEngine; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.io.ResponseQueue; public class IdentityEngineTest extends InstrumentationTestCase implements IEngineTestFrameworkObserver { /** * States for test harness */ enum IdentityTestState { IDLE, FETCH_IDENTITIES, GET_MY_IDENTITIES, FETCH_IDENTITIES_FAIL, FETCH_IDENTITIES_POPULATED, GET_CHATABLE_IDENTITIES, SET_IDENTITY_CAPABILTY, VALIDATE_ID_CREDENTIALS_SUCCESS, VALIDATE_ID_CREDENTIALS_FAIL, GET_NEXT_RUNTIME } EngineTestFramework mEngineTester = null; IdentityEngine mEng = null; IdentityTestState mState = IdentityTestState.IDLE; @Override protected void setUp() throws Exception { super.setUp(); mEngineTester = new EngineTestFramework(this); mEng = new IdentityEngine(mEngineTester); mEngineTester.setEngine(mEng); mState = IdentityTestState.IDLE; } @Override protected void tearDown() throws Exception { // stop our dummy thread? mEngineTester.stopEventThread(); mEngineTester = null; mEng = null; // call at the end!!! super.tearDown(); } @Suppress // Takes too long @MediumTest public void testFetchIdentities() { mState = IdentityTestState.FETCH_IDENTITIES; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.addUiFetchIdentities(); + mEng.getAvailableThirdPartyIdentities(); // mEng.run(); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); 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 @Suppress // Takes too long. public void testAddUiGetMyIdentities() { mState = IdentityTestState.GET_MY_IDENTITIES; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.addUiGetMyIdentities(); + mEng.getMyThirdPartyIdentities(); // mEng.run(); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); Object data = mEngineTester.data(); assertNull(null); try { ArrayList<Identity> identityList = ((Bundle)data).getParcelableArrayList("data"); assertEquals(identityList.size(), 1); } catch (Exception e) { throw (new RuntimeException("Expected identity list with 1 item")); } } @MediumTest @Suppress // Takes to long public void testFetchIdentitiesFail() { mState = IdentityTestState.FETCH_IDENTITIES_FAIL; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.addUiFetchIdentities(); + mEng.getAvailableThirdPartyIdentities(); // mEng.run(); ServiceStatus status = mEngineTester.waitForEvent(); assertFalse(ServiceStatus.SUCCESS == status); Object data = mEngineTester.data(); assertNull(data); } @MediumTest @Suppress // Breaks tests. public void testFetchIdentitiesPopulated() { mState = IdentityTestState.FETCH_IDENTITIES_POPULATED; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.addUiFetchIdentities(); + mEng.getAvailableThirdPartyIdentities(); // mEng.run(); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); Object data = mEngineTester.data(); assertTrue(data != null); } @MediumTest @Suppress // Breaks tests. 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); // AA mEng.addUiSetIdentityCapabilityStatus(network, identityId, fbund); mEng.addUiSetIdentityStatus(network, identityId, true); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); 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 @Suppress // Breaks tests. 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(); assertEquals(ServiceStatus.SUCCESS, status); Object data = mEngineTester.data(); assertTrue(data != null); } @MediumTest @Suppress // Breaks tests. public void testGetMyChatableIdentities() { mState = IdentityTestState.GET_CHATABLE_IDENTITIES; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.getMyChatableIdentities(); + mEng.getMy360AndThirdPartyChattableIdentities(); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); Object data = mEngineTester.data(); assertTrue(data != null); } @MediumTest @Suppress // Breaks tests. 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(); assertFalse(ServiceStatus.SUCCESS == status); 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 GET_MY_IDENTITIES: Log.d("TAG", "IdentityEngineTest.reportBackToEngine Get ids"); Identity myId = new Identity(); data.add(myId); 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"; + ServerError err = new ServerError("Catastrophe"); + err.errorDescription = "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"; + ServerError err2 = new ServerError("Catastrophe"); + err2.errorDescription = "Fail"; data.add(err2); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; case GET_NEXT_RUNTIME: break; case GET_CHATABLE_IDENTITIES: case FETCH_IDENTITIES_POPULATED: Identity id2 = new Identity(); id2.mActive = true; id2.mAuthType = "auth"; List<String> clist = new ArrayList<String>(); clist.add("uk"); clist.add("fr"); id2.mCountryList = clist; id2.mCreated = new Long(0); id2.mDisplayName = "Facebook"; // id2.mIcon2Mime = "jpeg"; id2.mIconMime = "jpeg"; try { id2.mIcon2Url = new URL("url2"); id2.mIconUrl = new URL("url"); id2.mNetworkUrl = new URL("network"); } catch (Exception e) { } id2.mIdentityId = "fb"; id2.mIdentityType = "type"; id2.mName = "Facebook"; id2.mNetwork = "Facebook"; id2.mOrder = 0; id2.mPluginId = ""; id2.mUpdated = new Long(0); id2.mUserId = 23; id2.mUserName = "user"; data.add(id2); List<IdentityCapability> capList = new ArrayList<IdentityCapability>(); IdentityCapability idcap = new IdentityCapability(); idcap.mCapability = IdentityCapability.CapabilityID.sync_contacts; idcap.mDescription = "sync cont"; idcap.mName = "sync cont"; idcap.mValue = true; capList.add(idcap); id2.mCapabilities = capList; data.add(id2); respQueue.addToResponseQueue(reqId, data, engine); Log.d("TAG", "IdentityEngineTest.reportBackToEngine add to Q"); mEng.onCommsInMessage(); break; default: } } @Override public void onEngineException(Exception exp) { // TODO Auto-generated method stub } } diff --git a/tests/src/com/vodafone360/people/tests/engine/LoginEngineTest.java b/tests/src/com/vodafone360/people/tests/engine/LoginEngineTest.java index a7d3a52..2c53fc9 100644 --- a/tests/src/com/vodafone360/people/tests/engine/LoginEngineTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/LoginEngineTest.java @@ -54,548 +54,548 @@ import com.vodafone360.people.tests.TestModule; @Suppress public class LoginEngineTest extends InstrumentationTestCase implements IEngineTestFrameworkObserver, ILoginEventsListener { /** * States for test harness */ enum LoginTestState { IDLE, ON_CREATE, ON_DESTROY, LOGIN_REQUEST, LOGIN_REQUEST_VALID, REMOVE_USER_DATA_REQ, LOGOUT_REQ, REGISTRATION, REGISTRATION_ERROR, GET_T_AND_C, FETCH_PRIVACY, USER_NAME_STATE, GET_NEXT_RUN_TIME, SERVER_ERROR, SMS_RESPONSE_SIGNIN, ON_REMOVE_USERDATA } EngineTestFramework mEngineTester = null; LoginEngine mEng = null; LoginTestState mState = LoginTestState.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(); mEngineTester = new EngineTestFramework(this); mEng = new LoginEngine(getInstrumentation().getTargetContext(), mEngineTester, mApplication .getDatabase()); mEngineTester.setEngine(mEng); mState = LoginTestState.IDLE; mEng.addListener(this); } @Override protected void tearDown() throws Exception { // stop our dummy thread? mEngineTester.stopEventThread(); mEngineTester = null; mEng.removeListener(this); mEng = null; // call at the end!!! super.tearDown(); } @MediumTest public void testOnCreate() { boolean testPassed = true; mState = LoginTestState.ON_CREATE; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { mEng.onCreate(); } catch (Exception e) { testPassed = false; } assertTrue(testPassed == true); } @MediumTest public void testOnDestroy() { boolean testPassed = true; mState = LoginTestState.ON_DESTROY; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { mEng.onCreate(); } catch (Exception e) { testPassed = false; } try { mEng.onDestroy(); } catch (Exception e) { Log.d("TAG", e.toString()); testPassed = false; } // expect failure as we've not assertTrue(testPassed == true); } @MediumTest @Suppress // Breaks tests. public void testLoginNullDetails() { mState = LoginTestState.LOGIN_REQUEST; LoginDetails loginDetails = null; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { synchronized (mEngineTester) { mEng.addUiLoginRequest(loginDetails); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, status); } } catch (Exception e) { displayException(e); fail("testLoginNullDetails test 1 failed with exception"); } loginDetails = new LoginDetails(); try { synchronized (mEngineTester) { mEng.addUiLoginRequest(loginDetails); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_COMMS, status); } } catch (Exception e) { displayException(e); fail("testLoginNullDetails test 2 failed with exception"); } } private void displayException(Exception e) { String strExceptionInfo = e + "\n"; for (int i = 0; i < e.getStackTrace().length; i++) { StackTraceElement v = e.getStackTrace()[i]; strExceptionInfo += "\t" + v + "\n"; } Log.e("TAG", "General exception occurred State = " + mState + "\n" + strExceptionInfo); } @MediumTest @Suppress // Breaks tests. public void testLoginValidDetails() { mState = LoginTestState.LOGIN_REQUEST; LoginDetails loginDetails = new LoginDetails(); loginDetails.mMobileNo = "123456789"; loginDetails.mUsername = "bob"; loginDetails.mPassword = "ajob"; try { synchronized (mEngineTester) { mEng.addUiLoginRequest(loginDetails); ServiceStatus status = mEngineTester.waitForEvent(120000); assertEquals(ServiceStatus.ERROR_SMS_CODE_NOT_RECEIVED, status); } // test actually receiving the SMS } catch (Exception e) { displayException(e); fail("testLoginValidDetails test 1 failed with exception"); } } @MediumTest public void testRemoveUserData() { boolean testPassed = true; mState = LoginTestState.REMOVE_USER_DATA_REQ; try { synchronized (mEngineTester) { mEng.addUiRemoveUserDataRequest(); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("SUCCESS")); } } // test actually receiving the SMS } catch (Exception e) { testPassed = false; } try { synchronized (mEngineTester) { mEng.onReset(); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("SUCCESS")); } } // test actually receiving the SMS } catch (Exception e) { testPassed = false; } assertTrue(testPassed == true); } @MediumTest public void testLogout() { boolean testPassed = true; mState = LoginTestState.LOGOUT_REQ; try { synchronized (mEngineTester) { mEng.addUiRequestToQueue(ServiceUiRequest.LOGOUT, null); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("SUCCESS")); } } // test actually receiving the SMS } catch (Exception e) { testPassed = false; } assertTrue(testPassed == true); } /* * addUiRegistrationRequest(non-Javadoc) * @seecom.vodafone360.people.tests.engine.IEngineTestFrameworkObserver# * reportBackToEngine(int, * com.vodafone360.people.engine.EngineManager.EngineId) */ @MediumTest @Suppress // Breaks tests. public void testRegistration() { mState = LoginTestState.REGISTRATION; NetworkAgent.setAgentState(NetworkAgent.AgentState.DISCONNECTED); RegistrationDetails details = null; try { synchronized (mEngineTester) { mEng.addUiRegistrationRequest(details); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, status); } } catch (Exception e) { displayException(e); fail("testRegistration test 1 failed with exception"); } NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { synchronized (mEngineTester) { mEng.addUiRegistrationRequest(details); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, status); } } catch (Exception e) { displayException(e); fail("testRegistration test 2 failed with exception"); } details = new RegistrationDetails(); try { synchronized (mEngineTester) { mEng.addUiRegistrationRequest(details); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, status); } } catch (Exception e) { displayException(e); fail("testRegistration test 3 failed with exception"); } details.mUsername = "bwibble"; details.mPassword = "qqqqqq"; try { synchronized (mEngineTester) { mEng.addUiRegistrationRequest(details); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_BAD_SERVER_PARAMETER, status); } } catch (Exception e) { displayException(e); fail("testRegistration test 4 failed with exception"); } details.mFullname = "Billy Wibble"; details.mBirthdayDate = "12345678"; details.mEmail = "[email protected]"; details.mMsisdn = "123456"; details.mAcceptedTAndC = true; details.mCountrycode = "uk"; details.mTimezone = "gmt"; details.mLanguage = "english"; details.mSendConfirmationMail = true; details.mSendConfirmationSms = true; details.mSubscribeToNewsLetter = true; details.mMobileOperatorId = new Long(1234); details.mMobileModelId = new Long(12345); try { synchronized (mEngineTester) { mEng.addUiRegistrationRequest(details); ServiceStatus status = mEngineTester.waitForEvent(120000); assertEquals(ServiceStatus.ERROR_SMS_CODE_NOT_RECEIVED, status); } } catch (Exception e) { displayException(e); fail("testRegistration test 5 failed with exception"); } } @MediumTest @Suppress // Breaks tests. public void testGetTermsAndConditions() { boolean testPassed = true; mState = LoginTestState.GET_T_AND_C; NetworkAgent.setAgentState(NetworkAgent.AgentState.DISCONNECTED); try { synchronized (mEngineTester) { mEng.addUiFetchTermsOfServiceRequest(); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("Expected SUCCESS")); } } } catch (Exception e) { testPassed = false; } NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { synchronized (mEngineTester) { mEng.addUiFetchTermsOfServiceRequest(); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("Expected SUCCESS")); } } } catch (Exception e) { testPassed = false; } assertTrue(testPassed == true); } @MediumTest @Suppress // Breaks tests. public void testFetchPrivacy() { boolean testPassed = true; mState = LoginTestState.FETCH_PRIVACY; NetworkAgent.setAgentState(NetworkAgent.AgentState.DISCONNECTED); try { synchronized (mEngineTester) { mEng.addUiFetchPrivacyStatementRequest(); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("Expected SUCCESS")); } } } catch (Exception e) { testPassed = false; } NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); try { synchronized (mEngineTester) { mEng.addUiFetchPrivacyStatementRequest(); ServiceStatus status = mEngineTester.waitForEvent(); if (status != ServiceStatus.SUCCESS) { throw (new RuntimeException("Expected SUCCESS")); } } } catch (Exception e) { testPassed = false; } assertTrue(testPassed == true); } @MediumTest @Suppress // Breaks tests. public void testFetchUserNameState() { mState = LoginTestState.USER_NAME_STATE; String userName = null; try { synchronized (mEngineTester) { mEng.addUiGetUsernameStateRequest(userName); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.ERROR_COMMS, status); } } catch (Exception e) { displayException(e); fail("testFetchUserNameState test 1 failed with exception"); } userName = "bwibble"; try { synchronized (mEngineTester) { mEng.addUiGetUsernameStateRequest(userName); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); } } catch (Exception e) { displayException(e); fail("testFetchUserNameState test 2 failed with exception"); } } @MediumTest public void testGetNextRuntime() { boolean testPassed = true; mState = LoginTestState.GET_NEXT_RUN_TIME; long nt = mEng.getNextRunTime(); if (nt != 0) { testPassed = false; } assertTrue(testPassed == true); } // @MediumTest // public void testSmsResponse(){ // LoginDetails loginDetails = new LoginDetails(); // loginDetails.mMobileNo = "123456789"; // loginDetails.mUsername = "bob"; // loginDetails.mPassword = "ajob"; // // mState = LoginTestState.LOGIN_REQUEST; // NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); // synchronized(mEngineTester){ // mEng.addUiLoginRequest(loginDetails); // // ServiceStatus status = mEngineTester.waitForEvent(); // assertEquals(ServiceStatus.SUCCESS, status); // } // // test actually receiving the SMS // mState = LoginTestState.SMS_RESPONSE_SIGNIN; // // mEng.handleSmsResponse(); // // ServiceStatus status = mEngineTester.waitForEvent(30000); // assertEquals(ServiceStatus.SUCCESS, status); // } @MediumTest public void testPublicFunctions() { mEng.getLoginRequired(); NetworkAgent.setAgentState(NetworkAgent.AgentState.DISCONNECTED); mEng.getNewPublicKey(); NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); mEng.getNewPublicKey(); mEng.isDeactivated(); mEng.setActivatedSession(new AuthSessionHolder()); } @Override public void reportBackToEngine(int reqId, EngineId engine) { Log.d("TAG", "LoginEngineTest.reportBackToEngine"); ResponseQueue respQueue = ResponseQueue.getInstance(); List<BaseDataType> data = new ArrayList<BaseDataType>(); // Request Activation code switch (mState) { case IDLE: break; case LOGIN_REQUEST: case SMS_RESPONSE_SIGNIN: Log.d("TAG", "IdentityEngineTest.reportBackToEngine FETCH ids"); StatusMsg msg = new StatusMsg(); data.add(msg); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); mState = LoginTestState.LOGIN_REQUEST_VALID; break; case LOGIN_REQUEST_VALID: Log.d("TAG", "IdentityEngineTest.reportBackToEngine FETCH ids"); AuthSessionHolder sesh = new AuthSessionHolder(); data.add(sesh); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); mState = LoginTestState.SMS_RESPONSE_SIGNIN; break; case REGISTRATION: Log.d("TAG", "IdentityEngineTest.reportBackToEngine Registration"); data.add(mTestModule.createDummyContactData()); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; case REGISTRATION_ERROR: - data.add(new ServerError()); + data.add(new ServerError(ServerError.ErrorType.UNKNOWN)); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; case GET_T_AND_C: case FETCH_PRIVACY: case USER_NAME_STATE: SimpleText txt = new SimpleText(); txt.addText("Simple text"); data.add(txt); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; case SERVER_ERROR: - data.add(new ServerError()); + data.add(new ServerError(ServerError.ErrorType.UNKNOWN)); respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); break; default: } } @Override public void onLoginStateChanged(boolean loggedIn) { // TODO Auto-generated method stub } @Override public void onEngineException(Exception exp) { // TODO Auto-generated method stub } } diff --git a/tests/src/com/vodafone360/people/tests/engine/contactsync/DownloadServerContactsTest.java b/tests/src/com/vodafone360/people/tests/engine/contactsync/DownloadServerContactsTest.java index 7b00321..e7d93c6 100644 --- a/tests/src/com/vodafone360/people/tests/engine/contactsync/DownloadServerContactsTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/contactsync/DownloadServerContactsTest.java @@ -1,779 +1,778 @@ /* * 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.util.ArrayList; import java.util.List; import android.app.Instrumentation; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; 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.ContactSummaryTable; 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.ContactSummary; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.contactsync.DownloadServerContacts; import com.vodafone360.people.engine.contactsync.IContactSyncCallback; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.io.ResponseQueue; import com.vodafone360.people.tests.TestModule; import com.vodafone360.people.tests.engine.EngineTestFramework; import com.vodafone360.people.tests.engine.IEngineTestFrameworkObserver; public class DownloadServerContactsTest extends InstrumentationTestCase implements IEngineTestFrameworkObserver { private static final String LOG_TAG = "DownloadServerContactsTest"; private static final long MAX_PROCESSOR_TIME = 30000000; private static final int CURRENT_SERVER_VERSION = 50; private static final long FIRST_MODIFIED_CONTACT_ID = 293822; private static final String MODIFIED_NICKNAME_STRING = "ModNickname"; private static final String MODIFIED_PHONE_STRING = "441292832827"; private static final ContactDetail.DetailKeyTypes MODIFIED_PHONE_TYPE = ContactDetail.DetailKeyTypes.MOBILE; private static final Integer MODIFIED_PHONE_ORDER = 60; private static final String NEW_PHONE_STRING = "10203040498"; private static final ContactDetail.DetailKeyTypes NEW_PHONE_TYPE = null; private static final Integer NEW_PHONE_ORDER = 0; private static final String NEW_EMAIL_STRING = "AddEmail"; private static final ContactDetail.DetailKeyTypes NEW_EMAIL_TYPE = ContactDetail.DetailKeyTypes.WORK; private static final Integer NEW_EMAIL_ORDER = 40; private static final String DEL_EMAIL_STRING2 = "1239383333"; private static final Long NEW_EMAIL_DETAIL_ID = 202033L; private static final Long NEW_PHONE_DETAIL_ID = 301020L; private static final Long OLD_PHONE_DETAIL_ID = 502292L; private static final Long ALT_PHONE_DETAIL_ID = 602292L; private static final String OLD_PHONE_DETAIL_VALUE = "OldPhoneValue"; private static final long WAIT_FOR_PAGE_MS = 100; private static final long MAX_WAIT_FOR_PAGE_MS = 10000L; private static final int BULK_TEST_NO_CONTACTS = 100; enum State { IDLE, RUN_WITH_NO_CHANGES, RUN_WITH_NEW_CONTACTS, RUN_WITH_DELETED_CONTACTS, RUN_WITH_MODIFIED_CONTACTS, RUN_WITH_DELETED_DETAILS } EngineTestFramework mEngineTester = null; MainApplication mApplication = null; DummyContactSyncEngine mEng = null; Context mContext; class DownloadServerContactProcessorTest extends DownloadServerContacts { DownloadServerContactProcessorTest(IContactSyncCallback callback, DatabaseHelper db) { super(callback, db); } public Integer testGetPageFromReqId(int reqId) { switch (mInternalState) { case FETCHING_NEXT_BATCH: long endTime = System.nanoTime() + (MAX_WAIT_FOR_PAGE_MS * 1000000); while (mPageReqIds.get(reqId) == null && System.nanoTime() < endTime) { try { synchronized (this) { wait(WAIT_FOR_PAGE_MS); } } catch (InterruptedException e) { e.printStackTrace(); } } return mPageReqIds.get(reqId); case FETCHING_FIRST_PAGE: return 0; default: return null; } } public int getDownloadPageSize() { return MAX_DOWN_PAGE_SIZE; } } DownloadServerContactProcessorTest mProcessor; DatabaseHelper mDb = null; State mState = State.IDLE; int mInitialCount; int mItemCount; int mPageCount; Contact mLastNewContact; TestModule mTestModule = new TestModule(); int mTestStep; @Override protected void setUp() throws Exception { super.setUp(); mApplication = (MainApplication)Instrumentation.newApplication(MainApplication.class, getInstrumentation().getTargetContext()); mApplication.onCreate(); mDb = mApplication.getDatabase(); mDb.removeUserData(); mEngineTester = new EngineTestFramework(this); mEng = new DummyContactSyncEngine(mEngineTester); mProcessor = new DownloadServerContactProcessorTest(mEng, mApplication.getDatabase()); mEng.setProcessor(mProcessor); mEngineTester.setEngine(mEng); mState = State.IDLE; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); } @Override protected void tearDown() throws Exception { // stop our dummy thread? mEngineTester.stopEventThread(); mEngineTester = null; mEng = null; SQLiteDatabase db = mDb.getReadableDatabase(); if (db.inTransaction()) { db.endTransaction(); } db.close(); super.tearDown(); } private void startSubTest(String function, String description) { Log.i(LOG_TAG, function + " - step " + mTestStep + ": " + description); mTestStep++; } private void runProcessor(int count, State state) { mInitialCount = count; mPageCount = 0; nextState(state); mLastNewContact = null; mEng.mProcessorCompleteFlag = false; mProcessor.start(); ServiceStatus status = mEng.waitForProcessorComplete(MAX_PROCESSOR_TIME); assertEquals(ServiceStatus.SUCCESS, status); } private void nextState(State state) { mItemCount = mInitialCount; if (mItemCount == 0) { mState = State.IDLE; } else { mState = state; } } @Override public void reportBackToEngine(int reqId, EngineId engine) { Log.d(LOG_TAG, "reportBackToEngine"); ResponseQueue respQueue = ResponseQueue.getInstance(); List<BaseDataType> data = new ArrayList<BaseDataType>(); try { assertEquals(mEng.engineId(), engine); switch (mState) { case RUN_WITH_NO_CHANGES: reportBackWithNoChanges(reqId, data); break; case RUN_WITH_NEW_CONTACTS: reportBackWithNewContacts(reqId, data); break; case RUN_WITH_DELETED_CONTACTS: reportBackWithDeletedContacts(reqId, data); break; case RUN_WITH_MODIFIED_CONTACTS: reportBackWithModifiedContacts(reqId, data); break; case RUN_WITH_DELETED_DETAILS: reportBackWithDeletedDetails(reqId, data); break; default: fail("Unexpected request rom processor"); } } catch (Throwable err) { - ServerError serverError = new ServerError(); - serverError.errorType = ServerError.ErrorTypes.INTERNALERROR.toString(); - serverError.errorValue = err + "\n"; + ServerError serverError = new ServerError(ServerError.ErrorType.INTERNALERROR); + serverError.errorDescription = err + "\n"; for (int i = 0; i < err.getStackTrace().length; i++) { StackTraceElement v = err.getStackTrace()[i]; - serverError.errorValue += "\t" + v + "\n"; + serverError.errorDescription += "\t" + v + "\n"; } - Log.e(LOG_TAG, "Exception:\n" + serverError.errorValue); + Log.e(LOG_TAG, "Exception:\n" + serverError.errorDescription); data.clear(); data.add(serverError); } respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); Log.d(LOG_TAG, "reportBackToEngine - message added to response queue"); } private void reportBackWithNoChanges(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackWithNoChanges"); Integer pageNo = mProcessor.testGetPageFromReqId(reqId); assertTrue(pageNo != null); assertEquals(Integer.valueOf(0), pageNo); ContactChanges contactChanges = new ContactChanges(); data.add(contactChanges); contactChanges.mCurrentServerVersion = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionBefore = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionAfter = CURRENT_SERVER_VERSION; contactChanges.mVersionAnchor = CURRENT_SERVER_VERSION; contactChanges.mNumberOfPages = 1; mItemCount--; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportBackWithNewContacts(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackWithNewContacts"); Integer pageNo = mProcessor.testGetPageFromReqId(reqId); int pageSize = mProcessor.getDownloadPageSize(); assertTrue(pageNo != null); assertEquals(Integer.valueOf(mPageCount), pageNo); ContactChanges contactChanges = new ContactChanges(); data.add(contactChanges); contactChanges.mCurrentServerVersion = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionBefore = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionAfter = CURRENT_SERVER_VERSION; contactChanges.mVersionAnchor = CURRENT_SERVER_VERSION; assertTrue(pageSize > 0); if (pageSize > 0) { contactChanges.mNumberOfPages = 1 + mPageCount + (mItemCount / pageSize); } int noOfContacts = Math.min(pageSize, mItemCount); for (int i = 0; i < noOfContacts; i++) { Contact newContact = mTestModule.createDummyContactData(); if (mLastNewContact == null) { mLastNewContact = newContact; } newContact.contactID = FIRST_MODIFIED_CONTACT_ID + mItemCount - 1; newContact.userID = generateTestUserID(newContact.contactID); ContactDetail detail1 = new ContactDetail(); detail1.key = ContactDetail.DetailKeys.VCARD_PHONE; detail1.unique_id = OLD_PHONE_DETAIL_ID + mItemCount - 1; detail1.value = OLD_PHONE_DETAIL_VALUE; newContact.details.add(detail1); for (int j = 0; j < newContact.details.size(); j++) { ContactDetail detail = newContact.details.get(j); switch (detail.key) { case VCARD_PHONE: case VCARD_EMAIL: if (detail.unique_id == null) { detail.unique_id = ALT_PHONE_DETAIL_ID + j; } break; } } contactChanges.mContacts.add(newContact); mItemCount--; } mPageCount++; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportBackWithDeletedContacts(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackWithDeletedContacts"); Integer pageNo = mProcessor.testGetPageFromReqId(reqId); int pageSize = mProcessor.getDownloadPageSize(); assertTrue(pageNo != null); assertEquals(Integer.valueOf(mPageCount), pageNo); ContactChanges contactChanges = new ContactChanges(); data.add(contactChanges); contactChanges.mCurrentServerVersion = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionBefore = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionAfter = CURRENT_SERVER_VERSION; contactChanges.mVersionAnchor = CURRENT_SERVER_VERSION; assertTrue(pageSize > 0); if (pageSize > 0) { contactChanges.mNumberOfPages = 1 + mPageCount + (mItemCount / pageSize); } int noOfContacts = Math.min(pageSize, mItemCount); for (int i = 0; i < noOfContacts; i++) { Contact deletedContact = new Contact(); deletedContact.contactID = FIRST_MODIFIED_CONTACT_ID + mItemCount - 1; deletedContact.deleted = true; contactChanges.mContacts.add(deletedContact); mItemCount--; } mPageCount++; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportBackWithModifiedContacts(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackWithModifiedContacts"); Integer pageNo = mProcessor.testGetPageFromReqId(reqId); int pageSize = mProcessor.getDownloadPageSize(); assertTrue(pageNo != null); assertEquals(Integer.valueOf(mPageCount), pageNo); ContactChanges contactChanges = new ContactChanges(); data.add(contactChanges); contactChanges.mCurrentServerVersion = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionBefore = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionAfter = CURRENT_SERVER_VERSION; contactChanges.mVersionAnchor = CURRENT_SERVER_VERSION; assertTrue(pageSize > 0); if (pageSize > 0) { contactChanges.mNumberOfPages = 1 + mPageCount + (mItemCount / pageSize); } int noOfContacts = Math.min(pageSize, mItemCount); for (int i = 0; i < noOfContacts; i++) { Contact modifiedContact = new Contact(); modifiedContact.contactID = FIRST_MODIFIED_CONTACT_ID + mItemCount - 1; // Modified details ContactDetail detail1 = new ContactDetail(); detail1.key = ContactDetail.DetailKeys.VCARD_NICKNAME; detail1.value = generateModifiedString(MODIFIED_NICKNAME_STRING, mItemCount - 1); modifiedContact.details.add(detail1); ContactDetail detail2 = new ContactDetail(); detail2.key = ContactDetail.DetailKeys.VCARD_PHONE; detail2.keyType = MODIFIED_PHONE_TYPE; detail2.order = MODIFIED_PHONE_ORDER; detail2.value = generateModifiedString(MODIFIED_PHONE_STRING, mItemCount - 1); detail2.unique_id = OLD_PHONE_DETAIL_ID + mItemCount - 1; modifiedContact.details.add(detail2); // New details ContactDetail detail3 = new ContactDetail(); detail3.key = ContactDetail.DetailKeys.VCARD_PHONE; detail3.keyType = NEW_PHONE_TYPE; detail3.order = NEW_PHONE_ORDER; detail3.value = generateModifiedString(NEW_PHONE_STRING, mItemCount - 1); detail3.unique_id = NEW_PHONE_DETAIL_ID + mItemCount - 1; modifiedContact.details.add(detail3); ContactDetail detail4 = new ContactDetail(); detail4.key = ContactDetail.DetailKeys.VCARD_EMAIL; detail4.keyType = NEW_EMAIL_TYPE; detail4.order = NEW_EMAIL_ORDER; detail4.value = generateModifiedString(NEW_EMAIL_STRING, mItemCount - 1); detail4.unique_id = NEW_EMAIL_DETAIL_ID + mItemCount - 1; modifiedContact.details.add(detail4); Log.d(LOG_TAG, "Contact " + modifiedContact.contactID + " has details " + detail1.unique_id + ", " + detail2.unique_id + ", " + detail3.unique_id + ", " + detail4.unique_id); contactChanges.mContacts.add(modifiedContact); mItemCount--; } mPageCount++; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportBackWithDeletedDetails(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackWithDeletedDetails"); Integer pageNo = mProcessor.testGetPageFromReqId(reqId); int pageSize = mProcessor.getDownloadPageSize(); assertTrue(pageNo != null); assertEquals(Integer.valueOf(mPageCount), pageNo); ContactChanges contactChanges = new ContactChanges(); data.add(contactChanges); contactChanges.mCurrentServerVersion = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionBefore = CURRENT_SERVER_VERSION; contactChanges.mServerRevisionAfter = CURRENT_SERVER_VERSION; contactChanges.mVersionAnchor = CURRENT_SERVER_VERSION; assertTrue(pageSize > 0); if (pageSize > 0) { contactChanges.mNumberOfPages = 1 + mPageCount + (mItemCount / pageSize); } int noOfContacts = Math.min(pageSize, mItemCount); for (int i = 0; i < noOfContacts; i++) { Contact curContact = new Contact(); curContact.contactID = FIRST_MODIFIED_CONTACT_ID + mItemCount - 1; contactChanges.mContacts.add(curContact); ContactDetail delDetail1 = new ContactDetail(); delDetail1.key = ContactDetail.DetailKeys.VCARD_NAME; delDetail1.deleted = true; ContactDetail delDetail2 = new ContactDetail(); delDetail2.key = ContactDetail.DetailKeys.VCARD_NICKNAME; delDetail2.deleted = true; ContactDetail delDetail3 = new ContactDetail(); delDetail3.key = ContactDetail.DetailKeys.VCARD_EMAIL; delDetail3.unique_id = NEW_EMAIL_DETAIL_ID + mItemCount - 1; delDetail3.deleted = true; curContact.details.add(delDetail1); curContact.details.add(delDetail2); curContact.details.add(delDetail3); mItemCount--; } mPageCount++; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private String generateModifiedString(String template, int index) { return template + "," + index; } private Long generateTestUserID(Long contactID) { if (contactID == null) { return null; } if ((contactID & 3) == 0) { return null; } return contactID + 5; } @Override public void onEngineException(Exception e) { mEng.onProcessorComplete(ServiceStatus.ERROR_UNKNOWN, "", e); } @SmallTest @Suppress // Breaks tests. public void testRunWithNoContactChanges() { final String fnName = "testRunWithNoContactChanges"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking database is empty"); Cursor cursor = mDb.openContactSummaryCursor(null, null); assertEquals(0, cursor.getCount()); startSubTest(fnName, "Running processor"); runProcessor(1, State.RUN_WITH_NO_CHANGES); assertEquals(State.IDLE, mState); cursor.close(); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests. public void testRunWithOneNewContact() { final String fnName = "testRunWithOneNewContact"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking database is empty"); Cursor cursor = mDb.openContactSummaryCursor(null, null); assertEquals(0, cursor.getCount()); startSubTest(fnName, "Running processor"); runProcessor(1, State.RUN_WITH_NEW_CONTACTS); startSubTest(fnName, "Checking database now has one contact"); cursor.requery(); assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToNext()); ContactSummary summary = ContactSummaryTable.getQueryData(cursor); Contact contact = new Contact(); ServiceStatus status = mDb.fetchContact(summary.localContactID, contact); assertEquals(ServiceStatus.SUCCESS, status); Long userId = generateTestUserID(contact.contactID); assertTrue(contact.contactID != null); assertEquals(userId, contact.userID); assertTrue(mLastNewContact != null); assertTrue(TestModule.doContactsMatch(contact, mLastNewContact)); assertTrue(TestModule.doContactsFieldsMatch(contact, mLastNewContact)); assertEquals(State.IDLE, mState); cursor.close(); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests. public void testRunWithOneDeletedContact() { final String fnName = "testRunWithOneDeletedContact"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking database is empty"); Cursor cursor = mDb.openContactSummaryCursor(null, null); assertEquals(0, cursor.getCount()); Contact contact = mTestModule.createDummyContactData(); contact.contactID = FIRST_MODIFIED_CONTACT_ID; List<Contact> contactList = new ArrayList<Contact>(); contactList.add(contact); ServiceStatus status = mDb.syncAddContactList(contactList, false, false); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Running processor"); runProcessor(1, State.RUN_WITH_DELETED_CONTACTS); startSubTest(fnName, "Checking database now has no contacts"); cursor.requery(); assertEquals(0, cursor.getCount()); cursor.close(); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests. public void testRunWithOneModifiedContact() { final String fnName = "testRunWithOneModifiedContact"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking database is empty"); Cursor cursor = mDb.openContactSummaryCursor(null, null); assertEquals(0, cursor.getCount()); Contact orgContact = mTestModule.createDummyContactData(); orgContact.contactID = FIRST_MODIFIED_CONTACT_ID; for (int j = 0; j < orgContact.details.size(); j++) { ContactDetail detail = orgContact.details.get(j); switch (detail.key) { case VCARD_PHONE: case VCARD_EMAIL: detail.unique_id = ALT_PHONE_DETAIL_ID + j; break; } } ContactDetail detail1 = new ContactDetail(); detail1.key = ContactDetail.DetailKeys.VCARD_PHONE; detail1.unique_id = OLD_PHONE_DETAIL_ID; detail1.value = OLD_PHONE_DETAIL_VALUE; orgContact.details.add(detail1); List<Contact> contactList = new ArrayList<Contact>(); int originalNoOfDetails = orgContact.details.size(); contactList.add(orgContact); ServiceStatus status = mDb.syncAddContactList(contactList, false, false); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Running processor"); runProcessor(1, State.RUN_WITH_MODIFIED_CONTACTS); startSubTest(fnName, "Checking database still has one contact"); cursor.requery(); assertEquals(1, cursor.getCount()); cursor.close(); Contact modContact = new Contact(); status = mDb.fetchContactByServerId(FIRST_MODIFIED_CONTACT_ID, modContact); assertEquals(ServiceStatus.SUCCESS, status); assertEquals(originalNoOfDetails + 2, modContact.details.size()); for (ContactDetail detail : modContact.details) { switch (detail.key) { case VCARD_NICKNAME: assertEquals(generateModifiedString(MODIFIED_NICKNAME_STRING, 0), detail.value); break; case VCARD_PHONE: if (detail.unique_id != null && detail.unique_id.equals(OLD_PHONE_DETAIL_ID)) { assertEquals(generateModifiedString(MODIFIED_PHONE_STRING, 0), detail.value); assertEquals(MODIFIED_PHONE_TYPE, detail.keyType); assertEquals(MODIFIED_PHONE_ORDER, detail.order); } else if (detail.unique_id != null && detail.unique_id.equals(NEW_PHONE_DETAIL_ID)) { assertEquals(generateModifiedString(NEW_PHONE_STRING, 0), detail.value); assertEquals(NEW_PHONE_TYPE, detail.keyType); assertEquals(NEW_PHONE_ORDER, detail.order); } break; case VCARD_EMAIL: if (detail.unique_id != null && detail.unique_id.equals(NEW_EMAIL_DETAIL_ID)) { assertEquals(generateModifiedString(NEW_EMAIL_STRING, 0), detail.value); assertEquals(NEW_EMAIL_TYPE, detail.keyType); assertEquals(NEW_EMAIL_ORDER, detail.order); assertEquals(NEW_EMAIL_DETAIL_ID, detail.unique_id); break; } // Fall through default: boolean done = false; for (int j = 0; j < orgContact.details.size(); j++) { if (orgContact.details.get(j).localDetailID.equals(detail.localDetailID)) { assertTrue(DatabaseHelper.doDetailsMatch(orgContact.details.get(j), detail)); assertFalse(DatabaseHelper.hasDetailChanged(orgContact.details.get(j), detail)); done = true; break; } } assertTrue(done); } } assertEquals(State.IDLE, mState); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests. public void testRunWithOneDeletedDetail() { final String fnName = "testRunWithOneDeletedDetail"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking database is empty"); Cursor cursor = mDb.openContactSummaryCursor(null, null); assertEquals(0, cursor.getCount()); Contact orgContact = mTestModule.createDummyContactData(); orgContact.contactID = FIRST_MODIFIED_CONTACT_ID; ContactDetail detail1 = new ContactDetail(); detail1.key = ContactDetail.DetailKeys.VCARD_EMAIL; detail1.keyType = NEW_EMAIL_TYPE; detail1.value = NEW_EMAIL_STRING; detail1.unique_id = NEW_EMAIL_DETAIL_ID; orgContact.details.add(detail1); ContactDetail detail2 = new ContactDetail(); detail2.key = ContactDetail.DetailKeys.VCARD_EMAIL; detail2.keyType = NEW_EMAIL_TYPE; detail2.value = DEL_EMAIL_STRING2; detail2.unique_id = NEW_EMAIL_DETAIL_ID + 1; orgContact.details.add(detail2); int originalNoOfDetails = orgContact.details.size(); List<Contact> contactList = new ArrayList<Contact>(); contactList.add(orgContact); ServiceStatus status = mDb.syncAddContactList(contactList, false, false); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Running processor"); runProcessor(1, State.RUN_WITH_DELETED_DETAILS); startSubTest(fnName, "Checking database still has 1 contact"); cursor.requery(); assertEquals(1, cursor.getCount()); cursor.close(); Contact modContact = new Contact(); status = mDb.fetchContactByServerId(FIRST_MODIFIED_CONTACT_ID, modContact); assertEquals(ServiceStatus.SUCCESS, status); assertEquals(originalNoOfDetails - 3, modContact.details.size()); for (ContactDetail detail : modContact.details) { switch (detail.key) { case VCARD_NAME: case VCARD_NICKNAME: fail("Unexpected detail after deletion: " + detail.key); break; case VCARD_EMAIL: if (detail.unique_id != null && detail.unique_id.equals(NEW_EMAIL_DETAIL_ID)) { fail("Unexpected detail after deletion: " + detail.key); break; } // Fall through default: boolean done = false; for (int j = 0; j < orgContact.details.size(); j++) { if (orgContact.details.get(j).localDetailID.equals(detail.localDetailID)) { assertTrue(DatabaseHelper.doDetailsMatch(orgContact.details.get(j), detail)); assertFalse(DatabaseHelper.hasDetailChanged(orgContact.details.get(j), detail)); done = true; break; } } diff --git a/tests/src/com/vodafone360/people/tests/engine/contactsync/UploadServerContactsTest.java b/tests/src/com/vodafone360/people/tests/engine/contactsync/UploadServerContactsTest.java index 5b2bd6f..df5b3e8 100644 --- a/tests/src/com/vodafone360/people/tests/engine/contactsync/UploadServerContactsTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/contactsync/UploadServerContactsTest.java @@ -1,810 +1,809 @@ /* * 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.util.ArrayList; import java.util.List; import java.util.ListIterator; import android.app.Instrumentation; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; 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.ContactChangeLogTable; import com.vodafone360.people.database.tables.ContactDetailsTable; import com.vodafone360.people.database.tables.ContactSummaryTable; 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.ContactSummary; import com.vodafone360.people.datatypes.GroupItem; import com.vodafone360.people.datatypes.ItemList; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.contactsync.IContactSyncCallback; import com.vodafone360.people.engine.contactsync.UploadServerContacts; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.io.ResponseQueue; import com.vodafone360.people.tests.TestModule; import com.vodafone360.people.tests.engine.EngineTestFramework; import com.vodafone360.people.tests.engine.IEngineTestFrameworkObserver; public class UploadServerContactsTest extends InstrumentationTestCase implements IEngineTestFrameworkObserver { private static final String LOG_TAG = "UploadServerContactsTest"; private static final long MAX_PROCESSOR_TIME = 3000000; private static final long MAX_WAIT_FOR_REQ_ID = 5000; private static final int NO_OF_CONTACTS_TO_ADD = 55; private static final String NEW_DETAIL_VALUE = "0123456789"; private static final ContactDetail.DetailKeys NEW_DETAIL_KEY = ContactDetail.DetailKeys.VCARD_PHONE; private static final ContactDetail.DetailKeyTypes NEW_DETAIL_TYPE = ContactDetail.DetailKeyTypes.CELL; private static final String MOD_DETAIL_VALUE = ";Test;One"; private static final ContactDetail.DetailKeys MOD_DETAIL_KEY = ContactDetail.DetailKeys.VCARD_NAME; private static final ContactDetail.DetailKeyTypes MOD_DETAIL_TYPE = null; private static final long TEST_GROUP_1 = 860909; private static final long TEST_GROUP_2 = 860910; enum State { IDLE, ADD_CONTACT_LIST, MODIFY_CONTACT_LIST, DELETE_CONTACT_LIST, DELETE_CONTACT_DETAIL_LIST, ADD_NEW_GROUP_LIST, DELETE_GROUP_LIST } EngineTestFramework mEngineTester = null; MainApplication mApplication = null; DummyContactSyncEngine mEng = null; class UploadServerContactProcessorTest extends UploadServerContacts { public UploadServerContactProcessorTest(IContactSyncCallback callback, DatabaseHelper db) { super(callback, db); } public void testFetchContactChangeList(List<Contact> contactChangeList) { contactChangeList.clear(); contactChangeList.addAll(getContactChangeList()); } public void testFetchAddGroupLists(List<Long> contactIdList, List<GroupItem> groupList) { contactIdList.clear(); groupList.clear(); contactIdList.addAll(getContactIdList()); groupList.addAll(getGroupList()); } public void testFetchContactDeleteList(List<Long> contactIdList) { contactIdList.clear(); contactIdList.addAll(getContactIdList()); } public void testFetchContactDetailDeleteList(Contact deleteDetailContact) { android.os.Parcel _data = android.os.Parcel.obtain(); getDeleteDetailContact().writeToParcel(_data, 0); _data.setDataPosition(0); deleteDetailContact.readFromParcel(_data); } public Long testFetchDeleteGroupList(List<Long> contactIdList) { contactIdList.clear(); contactIdList.addAll(getContactIdList()); return getActiveGroupId(); } public int testGetPageSize() { return MAX_UP_PAGE_SIZE; } public void verifyNewContactsState() { assertEquals(InternalState.PROCESSING_NEW_CONTACTS, getInternalState()); } public void verifyModifyDetailsState() { assertEquals(InternalState.PROCESSING_MODIFIED_DETAILS, getInternalState()); } public void verifyDeleteContactsState() { assertEquals(InternalState.PROCESSING_DELETED_CONTACTS, getInternalState()); } public void verifyDeleteDetailsState() { assertEquals(InternalState.PROCESSING_DELETED_DETAILS, getInternalState()); } public void verifyGroupAddsState() { assertEquals(InternalState.PROCESSING_GROUP_ADDITIONS, getInternalState()); } public void verifyGroupDelsState() { assertEquals(InternalState.PROCESSING_GROUP_DELETIONS, getInternalState()); } }; UploadServerContactProcessorTest mProcessor; DatabaseHelper mDb = null; State mState = State.IDLE; Contact mReplyContact = null; int mInitialCount; int mInitialContactGroupCount; int mItemCount; boolean mBulkContactTest; TestModule mTestModule = new TestModule(); int mTestStep; @Override protected void setUp() throws Exception { super.setUp(); mApplication = (MainApplication)Instrumentation.newApplication(MainApplication.class, getInstrumentation().getTargetContext()); mApplication.onCreate(); mDb = mApplication.getDatabase(); mDb.removeUserData(); mEngineTester = new EngineTestFramework(this); mEng = new DummyContactSyncEngine(mEngineTester); mProcessor = new UploadServerContactProcessorTest(mEng, mApplication.getDatabase()); mEng.setProcessor(mProcessor); mEngineTester.setEngine(mEng); mState = State.IDLE; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); mBulkContactTest = false; } @Override protected void tearDown() throws Exception { // stop our dummy thread? mEngineTester.stopEventThread(); mEngineTester = null; mEng = null; SQLiteDatabase db = mDb.getReadableDatabase(); if (db.inTransaction()) { db.endTransaction(); } db.close(); super.tearDown(); } private void startSubTest(String function, String description) { Log.i(LOG_TAG, function + " - step " + mTestStep + ": " + description); mTestStep++; } private void runProcessor(int count, State state) { mInitialCount = count; nextState(state); mEng.mProcessorCompleteFlag = false; mProcessor.start(); ServiceStatus status = mEng.waitForProcessorComplete(MAX_PROCESSOR_TIME); assertEquals(ServiceStatus.SUCCESS, status); } private void nextState(State state) { mItemCount = mInitialCount; if (mItemCount == 0) { mState = State.IDLE; } else { mState = state; } } @Override public void reportBackToEngine(int reqId, EngineId engine) { Log.d(LOG_TAG, "reportBackToEngine"); ResponseQueue respQueue = ResponseQueue.getInstance(); List<BaseDataType> data = new ArrayList<BaseDataType>(); try { assertEquals(mEng.engineId(), engine); synchronized (mEng.mWaitForReqIdLock) { if (mEng.mActiveReqId == null || mEng.mActiveReqId.intValue() != reqId) { try { mEng.mWaitForReqIdLock.wait(MAX_WAIT_FOR_REQ_ID); } catch (InterruptedException e) { } assertEquals(Integer.valueOf(reqId), mEng.mActiveReqId); } } switch (mState) { case ADD_CONTACT_LIST: reportBackAddContactSuccess(reqId, data); break; case MODIFY_CONTACT_LIST: reportModifyContactSuccess(reqId, data); break; case DELETE_CONTACT_LIST: reportDeleteContactSuccess(reqId, data); break; case DELETE_CONTACT_DETAIL_LIST: reportDeleteContactDetailSuccess(reqId, data); break; case ADD_NEW_GROUP_LIST: reportBackAddGroupSuccess(reqId, data); break; case DELETE_GROUP_LIST: reportDeleteGroupListSuccess(reqId, data); break; default: fail("Unexpected request from processor"); } } catch (Throwable err) { - ServerError serverError = new ServerError(); - serverError.errorType = ServerError.ErrorTypes.INTERNALERROR.toString(); - serverError.errorValue = err + "\n"; + ServerError serverError = new ServerError(ServerError.ErrorType.INTERNALERROR); + serverError.errorDescription = err + "\n"; for (int i = 0; i < err.getStackTrace().length; i++) { StackTraceElement v = err.getStackTrace()[i]; - serverError.errorValue += "\t" + v + "\n"; + serverError.errorDescription += "\t" + v + "\n"; } - Log.e(LOG_TAG, "Exception:\n" + serverError.errorValue); + Log.e(LOG_TAG, "Exception:\n" + serverError.errorDescription); data.clear(); data.add(serverError); } respQueue.addToResponseQueue(reqId, data, engine); mEng.onCommsInMessage(); Log.d(LOG_TAG, "reportBackToEngine - message added to response queue"); } private void reportBackAddContactSuccess(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackAddContactSuccess"); mProcessor.verifyNewContactsState(); List<Contact> contactChangeList = new ArrayList<Contact>(); mProcessor.testFetchContactChangeList(contactChangeList); assertEquals(Math.min(mItemCount, mProcessor.testGetPageSize()), contactChangeList.size()); ContactChanges contactChanges = new ContactChanges(); contactChanges.mServerRevisionAfter = 1; contactChanges.mServerRevisionBefore = 0; data.add(contactChanges); for (int i = 0; i < contactChangeList.size(); i++) { Contact actualContact = contactChangeList.get(i); Contact expectedContact = new Contact(); ServiceStatus status = mDb.fetchContact(actualContact.localContactID, expectedContact); assertEquals(ServiceStatus.SUCCESS, status); assertEquals(expectedContact.details.size(), actualContact.details.size()); assertEquals(null, actualContact.aboutMe); assertEquals(null, actualContact.profilePath); assertEquals(null, actualContact.contactID); assertEquals(null, actualContact.deleted); assertEquals(null, actualContact.friendOfMine); assertEquals(null, actualContact.gender); assertEquals(null, actualContact.groupList); assertEquals(null, actualContact.sources); assertEquals(expectedContact.synctophone, actualContact.synctophone); assertEquals(null, actualContact.updated); assertEquals(null, actualContact.userID); final ListIterator<ContactDetail> itActDetails = actualContact.details.listIterator(); for (ContactDetail expDetail : expectedContact.details) { ContactDetail actDetail = itActDetails.next(); assertTrue(DatabaseHelper.doDetailsMatch(expDetail, actDetail)); assertFalse(DatabaseHelper.hasDetailChanged(expDetail, actDetail)); } generateReplyContact(expectedContact); contactChanges.mContacts.add(mReplyContact); } mItemCount -= contactChangeList.size(); assertTrue(mItemCount >= 0); if (mItemCount == 0) { mInitialCount = mInitialContactGroupCount; nextState(State.ADD_NEW_GROUP_LIST); } } private void reportBackAddGroupSuccess(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportBackAddGroupSuccess"); mProcessor.verifyGroupAddsState(); final List<Long> contactIdList = new ArrayList<Long>(); final List<GroupItem> groupList = new ArrayList<GroupItem>(); mProcessor.testFetchAddGroupLists(contactIdList, groupList); assertEquals(1, groupList.size()); Long activeGroupId = groupList.get(0).mId; assertTrue(activeGroupId != null); ItemList itemList = new ItemList(ItemList.Type.contact_group_relations); data.add(itemList); for (Long contactServerId : contactIdList) { Contact expectedContact = new Contact(); ServiceStatus status = mDb.fetchContactByServerId(contactServerId, expectedContact); assertEquals(ServiceStatus.SUCCESS, status); boolean found = false; for (Long groupId : expectedContact.groupList) { if (groupId.equals(activeGroupId)) { found = true; break; } } assertTrue("Contact " + contactServerId + " has been added to group " + activeGroupId + " which is not in the database", found); mItemCount--; } Log.i(LOG_TAG, "Groups/contacts remaining = " + mItemCount); assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportModifyContactSuccess(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportModifyContactSuccess"); mProcessor.verifyModifyDetailsState(); List<Contact> contactChangeList = new ArrayList<Contact>(); mProcessor.testFetchContactChangeList(contactChangeList); assertEquals(Math.min(mItemCount, mProcessor.testGetPageSize()), contactChangeList.size()); ContactChanges contactChanges = new ContactChanges(); contactChanges.mServerRevisionAfter = 1; contactChanges.mServerRevisionBefore = 0; data.add(contactChanges); for (int i = 0; i < contactChangeList.size(); i++) { Contact actualContact = contactChangeList.get(i); assertTrue(actualContact.contactID != null); assertEquals(null, actualContact.aboutMe); assertEquals(null, actualContact.profilePath); assertEquals(null, actualContact.deleted); assertEquals(null, actualContact.friendOfMine); assertEquals(null, actualContact.gender); assertEquals(null, actualContact.groupList); assertEquals(null, actualContact.sources); assertEquals(null, actualContact.synctophone); assertEquals(null, actualContact.updated); assertEquals(null, actualContact.userID); assertEquals(2, actualContact.details.size()); ContactDetail modDetail = actualContact.details.get(0); // Modified // detail // always // first ContactDetail newDetail = actualContact.details.get(1); assertEquals(NEW_DETAIL_VALUE, newDetail.value); assertEquals(NEW_DETAIL_KEY, newDetail.key); assertEquals(NEW_DETAIL_TYPE, newDetail.keyType); assertEquals(MOD_DETAIL_VALUE, modDetail.value); assertEquals(MOD_DETAIL_KEY, modDetail.key); assertEquals(MOD_DETAIL_TYPE, modDetail.keyType); mReplyContact = new Contact(); mReplyContact.contactID = actualContact.contactID; mReplyContact.userID = generateTestUserID(mReplyContact.contactID); ContactDetail replyDetail1 = new ContactDetail(); ContactDetail replyDetail2 = new ContactDetail(); replyDetail1.key = modDetail.key; replyDetail1.unique_id = modDetail.unique_id; replyDetail2.key = newDetail.key; replyDetail2.unique_id = newDetail.localDetailID + 2; mReplyContact.details.add(replyDetail1); mReplyContact.details.add(replyDetail2); contactChanges.mContacts.add(mReplyContact); } mItemCount -= contactChangeList.size(); assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportDeleteContactSuccess(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportDeleteContactSuccess"); mProcessor.verifyDeleteContactsState(); List<Long> contactIdList = new ArrayList<Long>(); mProcessor.testFetchContactDeleteList(contactIdList); assertEquals(Math.min(mItemCount, mProcessor.testGetPageSize()), contactIdList.size()); ContactListResponse contactListResponse = new ContactListResponse(); contactListResponse.mServerRevisionAfter = 1; contactListResponse.mServerRevisionBefore = 0; data.add(contactListResponse); contactListResponse.mContactIdList = new ArrayList<Integer>(); for (Long serverID : contactIdList) { assertTrue(serverID != null); contactListResponse.mContactIdList.add(Integer.valueOf(serverID.intValue())); } mItemCount -= contactIdList.size(); assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportDeleteContactDetailSuccess(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportDeleteContactDetailSuccess"); mProcessor.verifyDeleteDetailsState(); Contact contact = new Contact(); mProcessor.testFetchContactDetailDeleteList(contact); assertEquals(2, contact.details.size()); assertEquals(ContactDetail.DetailKeys.VCARD_NAME, contact.details.get(0).key); assertEquals(ContactDetail.DetailKeys.VCARD_PHONE, contact.details.get(1).key); ContactDetailDeletion contactDetailDeletion = new ContactDetailDeletion(); contactDetailDeletion.mServerVersionAfter = 1; contactDetailDeletion.mServerVersionBefore = 0; data.add(contactDetailDeletion); contactDetailDeletion.mContactId = contact.contactID.intValue(); contactDetailDeletion.mDetails = new ArrayList<ContactDetail>(); for (ContactDetail detail : contact.details) { ContactDetail tempDetail = new ContactDetail(); tempDetail.key = detail.key; tempDetail.unique_id = detail.unique_id; contactDetailDeletion.mDetails.add(tempDetail); } mItemCount--; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private void reportDeleteGroupListSuccess(int reqId, List<BaseDataType> data) { Log.d(LOG_TAG, "reportDeleteGroupListSuccess"); mProcessor.verifyGroupDelsState(); final List<Long> contactIdList = new ArrayList<Long>(); Long activeGroupId = mProcessor.testFetchDeleteGroupList(contactIdList); if (mItemCount == 1) { assertEquals(Long.valueOf(TEST_GROUP_2), activeGroupId); } else if (mItemCount == 2) { assertEquals(Long.valueOf(TEST_GROUP_1), activeGroupId); } else { fail("Unexpected number of groups in delete group list"); } StatusMsg statusMsg = new StatusMsg(); statusMsg.mStatus = true; data.add(statusMsg); mItemCount--; assertTrue(mItemCount >= 0); if (mItemCount == 0) { nextState(State.IDLE); } } private Long generateTestUserID(Long contactID) { if (contactID == null) { return null; } if ((contactID & 15) == 0) { return null; } return contactID + 5; } private void generateReplyContact(Contact expContact) { mReplyContact = new Contact(); mReplyContact.contactID = expContact.localContactID + 1; if ((expContact.localContactID & 15) != 0) { mReplyContact.userID = expContact.localContactID + 2; } for (ContactDetail detail : expContact.details) { ContactDetail newDetail = new ContactDetail(); generateReplyDetail(newDetail, detail); mReplyContact.details.add(newDetail); } } private void generateReplyDetail(ContactDetail replyDetail, ContactDetail expDetail) { replyDetail.key = expDetail.key; switch (replyDetail.key) { case VCARD_NAME: case VCARD_NICKNAME: case VCARD_DATE: case VCARD_TITLE: case PRESENCE_TEXT: case PHOTO: case LOCATION: break; default: replyDetail.unique_id = expDetail.localDetailID + 3; break; } } @Override public void onEngineException(Exception e) { mEng.onProcessorComplete(ServiceStatus.ERROR_UNKNOWN, "", e); } @SmallTest @Suppress // Breaks tests public void testRunWithNoContactChanges() { final String fnName = "testRunWithNoContactChanges"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking change list is empty"); long noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Running processor"); mProcessor.start(); ServiceStatus status = mEng.waitForProcessorComplete(MAX_PROCESSOR_TIME); assertEquals(ServiceStatus.SUCCESS, status); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests public void testRunWithNewContactChange() { final String fnName = "testRunWithNewContactChange"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking change list is empty"); long noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Adding test contact to database"); Contact contact = mTestModule.createDummyContactData(); ServiceStatus status = mDb.addContact(contact); assertEquals(ServiceStatus.SUCCESS, status); mInitialContactGroupCount = contact.groupList.size(); startSubTest(fnName, "Running processor"); runProcessor(1, State.ADD_CONTACT_LIST); startSubTest(fnName, "Fetching contact after sync"); Contact syncContact = mTestModule.createDummyContactData(); status = mDb.fetchContact(contact.localContactID, syncContact); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Check contact server ID is correct"); assertEquals(syncContact.contactID, mReplyContact.contactID); startSubTest(fnName, "Check detail server IDs are correct"); final ListIterator<ContactDetail> itReplyDetails = mReplyContact.details.listIterator(); for (ContactDetail syncDetail : syncContact.details) { ContactDetail replyDetail = itReplyDetails.next(); assertEquals(replyDetail.key, syncDetail.key); assertEquals(replyDetail.unique_id, syncDetail.unique_id); } noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); assertEquals(State.IDLE, mState); startSubTest(fnName, "Running processor with no contact changes"); runProcessor(0, State.IDLE); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests public void testRunWithDetailChanges() { final String fnName = "testRunWithDetailChanges"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking change list is empty"); long noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Adding test contact to database"); Contact contact = mTestModule.createDummyContactData(); contact.contactID = TestModule.generateRandomLong(); contact.userID = generateTestUserID(contact.contactID); List<Contact> contactList = new ArrayList<Contact>(); contactList.add(contact); ServiceStatus status = mDb.syncAddContactList(contactList, false, false); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Adding new detail to contact"); ContactDetail newDetail = new ContactDetail(); newDetail.value = NEW_DETAIL_VALUE; newDetail.key = NEW_DETAIL_KEY; newDetail.keyType = NEW_DETAIL_TYPE; newDetail.localContactID = contact.localContactID; status = mDb.addContactDetail(newDetail); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Modifying detail in contact"); ContactDetail modDetail = contact.details.get(0); modDetail.value = MOD_DETAIL_VALUE; modDetail.key = MOD_DETAIL_KEY; modDetail.keyType = MOD_DETAIL_TYPE; status = mDb.modifyContactDetail(modDetail); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Running processor"); runProcessor(1, State.MODIFY_CONTACT_LIST); startSubTest(fnName, "Fetching detail after sync"); Contact syncContact = new Contact(); status = mDb.fetchContact(contact.localContactID, syncContact); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Check contact server ID is correct"); boolean done = false; for (ContactDetail detail : syncContact.details) { if (detail.localDetailID.equals(newDetail.localDetailID)) { assertEquals(detail.unique_id, Long.valueOf(detail.localDetailID + 2)); done = true; break; } } assertTrue(done); assertEquals(syncContact.contactID, mReplyContact.contactID); assertEquals(syncContact.userID, mReplyContact.userID); assertEquals(State.IDLE, mState); noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Running processor with no contact changes"); runProcessor(0, State.IDLE); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests public void testRunWithContactDeletion() { final String fnName = "testRunWithContactDeletion"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking change list is empty"); long noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Adding test contact to database - no sync"); Contact contact = mTestModule.createDummyContactData(); contact.contactID = TestModule.generateRandomLong(); contact.userID = generateTestUserID(contact.contactID); List<Contact> contactList = new ArrayList<Contact>(); contactList.add(contact); ServiceStatus status = mDb.syncAddContactList(contactList, false, false); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Deleting contact"); status = mDb.deleteContact(contact.localContactID); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Running processor"); runProcessor(1, State.DELETE_CONTACT_LIST); assertEquals(State.IDLE, mState); startSubTest(fnName, "Checking change list is empty"); noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Running processor with no contact changes"); runProcessor(0, State.IDLE); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, fnName + " has completed successfully"); Log.i(LOG_TAG, "*************************************************************************"); Log.i(LOG_TAG, ""); } @MediumTest @Suppress // Breaks tests public void testRunWithContactDetailDeletion() { final String fnName = "testRunWithContactDetailDeletion"; Log.i(LOG_TAG, "***** EXECUTING " + fnName + " *****"); mTestStep = 1; startSubTest(fnName, "Checking change list is empty"); long noOfChanges = ContactChangeLogTable.fetchNoOfContactDetailChanges(null, mDb .getReadableDatabase()); assertEquals(0, noOfChanges); noOfChanges = ContactDetailsTable.syncNativeFetchNoOfChanges(mDb.getReadableDatabase()); assertEquals(0, noOfChanges); startSubTest(fnName, "Adding test contact to database - no sync"); Contact contact = mTestModule.createDummyContactData(); contact.contactID = TestModule.generateRandomLong(); contact.userID = generateTestUserID(contact.contactID); List<Contact> contactList = new ArrayList<Contact>(); contactList.add(contact); ServiceStatus status = mDb.syncAddContactList(contactList, false, false); assertEquals(ServiceStatus.SUCCESS, status); startSubTest(fnName, "Adding test contact detail to database - no sync"); ContactDetail detail = new ContactDetail(); detail.value = NEW_DETAIL_VALUE; detail.key = ContactDetail.DetailKeys.VCARD_PHONE; detail.keyType = ContactDetail.DetailKeyTypes.CELL; detail.localContactID = contact.localContactID; diff --git a/tests/src/com/vodafone360/people/tests/service/PeopleServiceTest.java b/tests/src/com/vodafone360/people/tests/service/PeopleServiceTest.java index c1687c0..eeb688c 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.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.fetchAvailableIdentities(filter); + 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.fetchMyIdentities(filter); + 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(); - se1.errorValue = "Test error produced by test framework, ignore it"; - se1.errorType = "INTERNALERROR"; + ServerError se1 = new ServerError(ServerError.ErrorType.INTERNALERROR); + se1.errorDescription = "Test error produced by test framework, ignore it"; data.add(se1); respQueue.addToResponseQueue(reqId, data, engine); } } \ No newline at end of file diff --git a/tests/src/com/vodafone360/people/tests/service/utils/TimeOutWatcherTest.java b/tests/src/com/vodafone360/people/tests/service/utils/TimeOutWatcherTest.java index 06608c7..fcab75e 100644 --- a/tests/src/com/vodafone360/people/tests/service/utils/TimeOutWatcherTest.java +++ b/tests/src/com/vodafone360/people/tests/service/utils/TimeOutWatcherTest.java @@ -1,299 +1,299 @@ /* * 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.utils; import android.app.Instrumentation; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import com.vodafone360.people.MainApplication; import com.vodafone360.people.datatypes.BaseDataType; 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.Response; import com.vodafone360.people.service.utils.TimeOutWatcher; /** * JUnit tests for the TimeOutWatcher class. */ public class TimeOutWatcherTest extends InstrumentationTestCase { private final static long TIMEOUT_2000_MS = 2000; private final static long TIMEOUT_10000_MS = 10000; private TimeOutWatcher mWatcher = null; private MainApplication mApplication; protected void setUp() throws Exception { super.setUp(); mApplication = (MainApplication)Instrumentation.newApplication(MainApplication.class, getInstrumentation().getTargetContext()); mApplication.onCreate(); mWatcher = new TimeOutWatcher(); } protected void tearDown() throws Exception { mWatcher.kill(); super.tearDown(); } /** * Tests adding and removing requests with different cases: * -same expiry dates * -increasing dates * -decreasing dates */ public void testAddingAndRemovingRequests() { Log.i("testAddingAndRemovingRequests()", "-begin"); Request[] requests = new Request[10]; assertEquals(0, mWatcher.getRequestsCount()); // requests with same expiry date Log.i("testAddingAndRemovingRequests()", "-checking requests with same expiry date"); for(int i = 0; i < requests.length; i++) { requests[i] = createRequestWithTimeout(TIMEOUT_2000_MS); requests[i].calculateExpiryDate(); mWatcher.addRequest(requests[i]); } assertEquals(requests.length, mWatcher.getRequestsCount()); assertTrue(compareRequestArraysIdentical(requests, mWatcher.getRequestsArray())); for(int i = 0; i < requests.length; i++) { mWatcher.removeRequest(requests[i]); } assertEquals(0, mWatcher.getRequestsCount()); Log.i("testAddingAndRemovingRequests()", "-checking requests that don't wake up the thread each time they are added (but wake up the thread when removed with the same order)"); for(int i = 0; i < requests.length; i++) { requests[i] = createRequestWithTimeout(TIMEOUT_10000_MS * (i+1)); requests[i].calculateExpiryDate(); mWatcher.addRequest(requests[i]); } assertEquals(requests.length, mWatcher.getRequestsCount()); assertTrue(compareRequestArraysIdentical(requests, mWatcher.getRequestsArray())); for(int i = 0; i < requests.length; i++) { mWatcher.removeRequest(requests[i]); } assertEquals(0, mWatcher.getRequestsCount()); Log.i("testAddingAndRemovingRequests()", "-checking requests that wake up the thread each time they are added (but don't wake up the thread when removed with the same order"); for(int i = 0; i < requests.length; i++) { requests[i] = createRequestWithTimeout(TIMEOUT_10000_MS * (requests.length-i)); requests[i].calculateExpiryDate(); mWatcher.addRequest(requests[i]); } assertEquals(requests.length, mWatcher.getRequestsCount()); assertTrue(compareRequestArraysSameContent(requests, mWatcher.getRequestsArray())); for(int i = 0; i < requests.length; i++) { mWatcher.removeRequest(requests[i]); } assertEquals(0, mWatcher.getRequestsCount()); Log.i("testAddingAndRemovingRequests()", "-end"); } /** * Tests the invalidateAllRequests() method. */ @Suppress public void testTimingOutAllRequests() { Log.i("testTimingOutAllRequests()", "-begin"); Request[] requests = new Request[10]; assertEquals(0, QueueManager.getInstance().getRequestTimeoutWatcher().getRequestsCount()); for(int i = 0; i < requests.length; i++) { requests[i] = createRequestWithTimeout(TIMEOUT_2000_MS); QueueManager.getInstance().addRequest(requests[i]); } assertEquals(requests.length, QueueManager.getInstance().getRequestTimeoutWatcher().getRequestsCount()); assertTrue(compareRequestArraysIdentical(requests, QueueManager.getInstance().getRequestTimeoutWatcher().getRequestsArray())); QueueManager.getInstance().getRequestTimeoutWatcher().invalidateAllRequests(); assertEquals(0, QueueManager.getInstance().getRequestTimeoutWatcher().getRequestsCount()); Log.i("testTimingOutAllRequests()", "-end"); } /** * Tests that when requests are added, they are stored in an ascending ordered list. */ public void testRequestsAreSorted() { Log.i("testRequestsAreSorted()", "-begin"); assertEquals(0, mWatcher.getRequestsCount()); final int[] order = { 7, 10, 9, 6, 2, 8, 1, 5, 3, 4 }; // add the requests with following timeout order: 7, 10, 9, 6, 2, 8, 1, 5, 3, 4 for (int i = 0; i < order.length; i++) { final Request request = createRequestWithTimeout(TIMEOUT_10000_MS * order[i]); request.calculateExpiryDate(); mWatcher.addRequest(request); } final Request[] requests = mWatcher.getRequestsArray(); assertEquals(order.length, requests.length); // check that the requests are given back in the ascending order: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 for (int i = 0; i < requests.length; i++) { final Request request = requests[i]; assertEquals((i+1), request.getTimeout() / TIMEOUT_10000_MS); } Log.i("testRequestsAreSorted()", "-end"); } /** * Tests that a timeout error is thrown if the response of the request has not been received after the timeout period. */ @Suppress public void testThrowingTimeout() { Log.i("testThrowingTimeout()", "-begin"); final Request request = createRequestWithTimeout(TIMEOUT_2000_MS); // check that the response queue is empty for the engine with EngineId.UNDEFINED id (we use this one for the test) Response response = ResponseQueue.getInstance().getNextResponse(EngineId.UNDEFINED); assertNull(response); // adding the request to the queue should add it to the TimeOutWatcher final int reqId = QueueManager.getInstance().addRequest(request); // check that the response queue is still empty response = ResponseQueue.getInstance().getNextResponse(EngineId.UNDEFINED); assertNull(response); // let's give at least 2 times the timeout to the system before checking long stopTime = System.currentTimeMillis() + (TIMEOUT_2000_MS * 2); while (System.currentTimeMillis() < stopTime) { try { Thread.sleep(TIMEOUT_2000_MS); } catch(InterruptedException ie) { Log.i("testThrowingTimeout()", "Error while sleeping: "+ie); } } // check that the response is still empty response = ResponseQueue.getInstance().getNextResponse(EngineId.UNDEFINED); assertNotNull(response); // check response request id is the same as the request id assertEquals(reqId, response.mReqId.intValue()); // check the timeout error returned is as expected assertNotNull(response.mDataTypes); assertEquals(1, response.mDataTypes.size()); BaseDataType error = response.mDataTypes.get(0); assertTrue(error instanceof ServerError); ServerError srvError = (ServerError)error; - assertEquals(ServerError.ErrorTypes.REQUEST_TIMEOUT, srvError.getType()); + assertEquals(ServerError.ErrorType.REQUEST_TIMEOUT, srvError.getType()); Log.i("testThrowingTimeout()", "-end"); } //////////////////// // HELPER METHODS // //////////////////// /** * Creates a request for the "undefined" engine. * @param timeout the timeout for the request in milliseconds */ private Request createRequestWithTimeout(long timeout) { final Request request = new Request("", Type.PRESENCE_LIST, EngineId.UNDEFINED, false, timeout); request.setActive(true); return request; } /** * Checks if two arrays are exactly the same. * @param array1 the first array to compare * @param array2 the second array to compare * @return true if identical, false otherwise */ private boolean compareRequestArraysIdentical(Request[] array1, Request[] array2) { if (array1 == null || array2 == null) { throw new NullPointerException(); } if (array1.length != array2.length) { return false; } for (int i = 0; i < array1.length; i++) { if (array1[i] != array2[i]) { return false; } } return true; } /** * Checks if two arrays have the same content but not necessarily in the same order. * @param array1 the first array to compare * @param array2 the second array to compare * @return true if both arrays have the same content, false otherwise */ private boolean compareRequestArraysSameContent(Request[] array1, Request[] array2) { if (array1 == null || array2 == null) { throw new NullPointerException(); } if (array1.length != array2.length) { return false; } int count; for (int i = 0; i < array1.length; i++) { count = 0; for (int j = 0; j < array1.length; j++) { if (array1[i] == array2[j]) { count++; // more than one if (count > 1) return false; } } // none if (count == 0) return false; } // arrays contain the same requests return true; } }
360/360-Engine-for-Android
5ad8eab758ec9a9b172feae5bc99ab63240738f5
added ui pushes for uncached identities. readded loading progress bar. caching of identities now works. committed fixes to keep client with old ui running.
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index a50990e..61f941e 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,713 +1,748 @@ /* * 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.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.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_CAPABILITY_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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; 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; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; + public static final String KEY_AVAILABLE_IDS = "availableids"; + 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(); } HttpConnectionThread.logE("getAvailableThirdPartyIdentities", mAvailableIdentityList.toString(), null); 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(); } HttpConnectionThread.logE("IE.getMyThirdPartyIdentities", mMyIdentityList.toString(), null); 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>(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < mMyIdentityList.size(); 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 iCapability = new IdentityCapability(); iCapability.mCapability = IdentityCapability.CapabilityID.chat; iCapability.mValue = new Boolean(true); ArrayList<IdentityCapability> mobileCapabilities = new ArrayList<IdentityCapability>(); mobileCapabilities.add(iCapability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = "mobile"; 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())); } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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: // changed the method called // startSetIdentityCapabilityStatus(data); 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_CAPABILITY_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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { 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: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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) { HttpConnectionThread.logE("IE.handleGetAvailableIdentitiesResponse", "", null); 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) { HttpConnectionThread.logE("handleGetMyIdentitiesResponse", "", null); 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); HttpConnectionThread.logE("Identity: ", ((Identity)item).toString(), null); } } } + 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 handleSetIdentityCapabilityStatus(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, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } }
360/360-Engine-for-Android
b1a7bef4a35e525da00944e5d8991280ee20687a
Added Eclipse project files to ignore list.
diff --git a/.gitignore b/.gitignore index 8ea3ee8..97f9dac 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ config.properties tests/bin/* bin gen - +.classpath +.project
360/360-Engine-for-Android
8c50aeb00e83400b44d291a8221ad30446aaf2f5
- cached identities now working 90% - synchronization of getters of identities in IdentityEngine - fixed methods that would give wrong identity back - refactored Identity-class to use primitive data types instead of complex
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/datatypes/Identity.java b/src/com/vodafone360/people/datatypes/Identity.java index e88c3df..9ab2aaf 100644 --- a/src/com/vodafone360/people/datatypes/Identity.java +++ b/src/com/vodafone360/people/datatypes/Identity.java @@ -1,614 +1,612 @@ /* * 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.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Vector; import android.os.Parcel; import android.os.Parcelable; import com.vodafone360.people.utils.LogUtils; /** * BaseDataType encapsulating an Identity issued to or retrieved from server */ public class Identity extends BaseDataType implements Parcelable { /** * Tags associated with Identity item. */ private enum Tags { IDENTITY_MAIN_TAG("availableidentity"), IDENTITY_CAPABILITY_LIST("identitycapabilitylist"), PLUGIN_ID("pluginid"), NETWORK_URL("networkurl"), AUTH_TYPE("authtype"), ICON_MIME("iconmime"), ICON2_MIME("icon2mime"), ORDER("order"), NAME("name"), ICON_URL("iconurl"), ICON2_URL("icon2url"), NETWORK("network"), // Properties below are only present after // GetMyIdentities. ACTIVE("active"), CREATED("created"), IDENTITY_ID("identityid"), UPDATED("updated"), IDENTITY_TYPE("identitytype"), USER_ID("userid"), USER_NAME("username"), DISPLAY_NAME("displayname"), COUNTRY_LIST("countrylist"); private final String tag; /** * Construct Tags item from supplied String * * @param s String value for Tags item. */ private Tags(String s) { tag = s; } /** * String value for 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 in Tags items. * @return Tags item for specified String, NULL otherwise. */ private static Tags findTag(String tag) { for (Tags tags : Tags.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } return null; } } - public String mPluginId = null; + public String mPluginId; - public String mNetwork = null; + public String mNetwork; - public URL mNetworkUrl = null; + public URL mNetworkUrl; - public URL mIconUrl = null; + public URL mIconUrl; - public URL mIcon2Url = null; + public URL mIcon2Url; public String mAuthType; - public String mIconMime = null; + public String mIconMime; - public Integer mOrder = null; + public int mOrder; - public String mName = null; + public String mName; - public List<IdentityCapability> mCapabilities = null; + public List<IdentityCapability> mCapabilities; /** Properties below are only present after GetMyIdentities. */ - public Boolean mActive = null; + public boolean mActive; - public Long mCreated = null; + public long mCreated; - public Long mUpdated = null; + public long mUpdated; - public String mIdentityId = null; + public String mIdentityId; - public Integer mUserId = null; + public int mUserId; - public String mUserName = null; + public String mUserName; - public String mDisplayName = null; + public String mDisplayName; - public List<String> mCountryList = null; + public List<String> mCountryList; - public String mIdentityType = null; + public String mIdentityType; private int mType; /** * Comparator class used to compare Identities retrieved from server to * remove duplicates from list passed to People client UI. */ public static class IdentityComparator implements Comparator<Identity> { @Override public int compare(Identity object1, Identity object2) { - return object1.mOrder.compareTo(object2.mOrder); + return new Integer(object1.mOrder).compareTo(new Integer(object2.mOrder)); } } /** * Test whether current Identity is identical to supplied Identity. * * @param id Identity to compare against. * @return true if Identities match, false otherwise. */ public boolean isSameAs(Identity id) { boolean isSame = true; if (!areStringValuesSame(mPluginId, id.mPluginId) || !areStringValuesSame(mNetwork, id.mNetwork) || !areStringValuesSame(mIdentityId, id.mIdentityId) || !areStringValuesSame(mDisplayName, id.mDisplayName)) { isSame = false; } if (mNetworkUrl != null && id.mNetworkUrl != null) { if (!mNetworkUrl.sameFile(id.mNetworkUrl)) { isSame = false; } } else if (mNetworkUrl == null && id.mNetworkUrl == null) { // Do nothing. } else { isSame = false; } if (mIconUrl != null && id.mIconUrl != null) { if (!mIconUrl.sameFile(id.mIconUrl)) { isSame = false; } } else if (mIconUrl == null && id.mIconUrl == null) { // Do nothing. } else { isSame = false; } return isSame; } /** * String values comparison * * @param s1 First String to test. * @param s2 Second String to test. * @return true if Strings match (or both are null), false otherwise. */ private boolean areStringValuesSame(String s1, String s2) { boolean isSame = true; if (s1 == null && s2 == null) { // Do nothing. } else if (s1 != null && s2 != null) { if (s1.compareTo(s2) != 0) { isSame = false; } } else { isSame = false; } return isSame; } /** * Default constructor. */ public Identity() { // Do nothing. } public Identity(int type) { mType = type; } /** * Create Identity from Parcel. * * @param in Parcel containing Identity. */ private Identity(Parcel in) { readFromParcel(in); } /** {@inheritDoc} */ @Override public int getType() { - // TODO: Return appropriate type if its - // an available identity instead of my identity - return MY_IDENTITY_DATA_TYPE; + return mType; } /** * Populate Identity from supplied Hashtable. * * @param hash Hashtable containing identity details. * @return Identity instance. */ public Identity createFromHashtable(Hashtable<String, Object> hash) { Enumeration<String> e = hash.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); Object value = hash.get(key); Tags tag = Tags.findTag(key); if (tag != null) setValue(tag, value); } 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 val) { switch (tag) { case AUTH_TYPE: mAuthType = (String)val; break; case ICON_MIME: mIconMime = (String)val; break; case ICON2_MIME: // TODO: Remove TAG value? // mIcon2Mime = (String)val; break; case ICON_URL: try { mIconUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIconUrl = null; } break; case ICON2_URL: try { mIcon2Url = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIcon2Url = null; } break; case IDENTITY_CAPABILITY_LIST: /** Create id capability list. */ @SuppressWarnings("unchecked") Vector<Hashtable<String, Object>> v = (Vector<Hashtable<String, Object>>)val; if (mCapabilities == null) { mCapabilities = new ArrayList<IdentityCapability>(); } for (Hashtable<String, Object> obj : v) { IdentityCapability cap = new IdentityCapability(); cap.createFromHashtable(obj); mCapabilities.add(cap); } break; case IDENTITY_MAIN_TAG: // Not currently handled. break; case NAME: mName = (String)val; break; case NETWORK: mNetwork = (String)val; break; case NETWORK_URL: try { mNetworkUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong network url: '" + val + "'"); mNetworkUrl = null; } break; case ORDER: mOrder = (Integer)val; break; case PLUGIN_ID: mPluginId = (String)val; break; case ACTIVE: mActive = (Boolean)val; break; case CREATED: mCreated = (Long)val; break; case DISPLAY_NAME: mDisplayName = (String)val; break; case IDENTITY_ID: mIdentityId = (String)val; break; case IDENTITY_TYPE: mIdentityType = (String)val; break; case UPDATED: mUpdated = (Long)val; break; case USER_ID: mUserId = ((Long)val).intValue(); break; case USER_NAME: mUserName = (String)val; break; case COUNTRY_LIST: if (mCountryList == null) { mCountryList = new ArrayList<String>(); } break; default: // Do nothing. break; } } /** {@inheritDoc} */ @Override public String toString() { final StringBuffer sb = new StringBuffer("Name:"); sb.append(mName); sb.append("\nPluginID:"); sb.append(mPluginId); sb.append("\nNetwork:"); sb.append(mNetwork); sb.append("\nNetworkURL:"); sb.append(mNetworkUrl); sb.append("\nAuthType:"); sb.append(mAuthType); sb.append("\nIcon mime:"); sb.append(mIconMime); sb.append("\nIconURL:"); sb.append(mIconUrl); sb.append("\nOrder:"); sb.append(mOrder); sb.append("\nActive:"); sb.append(mActive); sb.append("\nCreated:"); sb.append(mCreated); sb.append("\nUpdated:"); sb.append(mUpdated); sb.append("\nIdentityId:"); sb.append(mIdentityId); sb.append("\nUserId:"); sb.append(mUserId); sb.append("\nUserName:"); sb.append(mUserName); sb.append("\nDisplayName:"); sb.append(mDisplayName); sb.append("\nIdentityType:"); sb.append(mIdentityType); if (mCountryList != null) { sb.append("\nCountry List: ("); sb.append(mCountryList.size()); sb.append(") = ["); for (int i = 0; i < mCountryList.size(); i++) { sb.append(mCountryList.get(i)); if (i < mCountryList.size() - 1) sb.append(", "); } sb.append("]"); } if (mCapabilities != null) { sb.append("\nCapabilities ("); sb.append(mCapabilities.size()); sb.append(")"); for (int i = 0; i < mCapabilities.size(); i++) { sb.append("\n" + mCapabilities.get(i).toString()); if (i < mCapabilities.size() - 1) { sb.append("\n\t---"); } } } return sb.toString(); } /** {@inheritDoc} */ @Override public int describeContents() { return 1; } /** * Enumeration containing items contained within Identity Parcel. */ private enum MemberData { PLUGIN_ID, NETWORK, NETWORK_URL, ICON_URL, AUTH_TYPE, ICON_MIME, ORDER, NAME; } /** * Read Identity item from Parcel. * * @param in Parcel containing Identity information. */ private void readFromParcel(Parcel in) { mPluginId = null; mNetwork = null; mNetworkUrl = null; mIconUrl = null; mAuthType = null; mIconMime = null; - mOrder = null; + mOrder = -1; mName = null; mCapabilities = null; boolean[] validDataList = new boolean[MemberData.values().length]; in.readBooleanArray(validDataList); if (validDataList[MemberData.PLUGIN_ID.ordinal()]) { mPluginId = in.readString(); } if (validDataList[MemberData.NETWORK.ordinal()]) { mNetwork = in.readString(); } if (validDataList[MemberData.NETWORK_URL.ordinal()]) { try { mNetworkUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.NETWORK_URL"); } } if (validDataList[MemberData.ICON_URL.ordinal()]) { try { mIconUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.ICON_URL"); } } if (validDataList[MemberData.AUTH_TYPE.ordinal()]) { mAuthType = in.readString(); } if (validDataList[MemberData.ICON_MIME.ordinal()]) { mIconMime = in.readString(); } if (validDataList[MemberData.ORDER.ordinal()]) { mOrder = in.readInt(); } if (validDataList[MemberData.NAME.ordinal()]) { mName = in.readString(); } int noOfCapabilities = in.readInt(); if (noOfCapabilities > 0) { mCapabilities = new ArrayList<IdentityCapability>(noOfCapabilities); for (int i = 0; i < noOfCapabilities; i++) { IdentityCapability cap = IdentityCapability.CREATOR.createFromParcel(in); mCapabilities.add(cap); } } } /** {@inheritDoc} */ @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 (mPluginId != null) { validDataList[MemberData.PLUGIN_ID.ordinal()] = true; dest.writeString(mPluginId); } if (mNetwork != null) { validDataList[MemberData.NETWORK.ordinal()] = true; dest.writeString(mNetwork); } if (mNetworkUrl != null) { validDataList[MemberData.NETWORK_URL.ordinal()] = true; dest.writeString(mNetworkUrl.toString()); } if (mIconUrl != null) { validDataList[MemberData.ICON_URL.ordinal()] = true; dest.writeString(mIconUrl.toString()); } if (mAuthType != null) { validDataList[MemberData.AUTH_TYPE.ordinal()] = true; dest.writeString(mAuthType); } if (mIconMime != null) { validDataList[MemberData.ICON_MIME.ordinal()] = true; dest.writeString(mIconMime); } - if (mOrder != null) { + if (mOrder != -1) { validDataList[MemberData.ORDER.ordinal()] = true; dest.writeInt(mOrder); } if (mName != null) { validDataList[MemberData.NAME.ordinal()] = true; dest.writeString(mName); } if (mCapabilities != null) { dest.writeInt(mCapabilities.size()); for (IdentityCapability cap : mCapabilities) { cap.writeToParcel(dest, 0); } } else { dest.writeInt(0); } int currentPos = dest.dataPosition(); dest.setDataPosition(validDataPos); dest.writeBooleanArray(validDataList); // Real array. dest.setDataPosition(currentPos); } /** Interface to allow Identity to be written and restored from a Parcel. */ public static final Parcelable.Creator<Identity> CREATOR = new Parcelable.Creator<Identity>() { public Identity createFromParcel(Parcel in) { return new Identity(in); } public Identity[] newArray(int size) { return new Identity[size]; } }; } diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 9eabfd5..a50990e 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,804 +1,713 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { - // private String mNetwork; - // private String mIdentityId; - // private Map<String, Object> mStatus = null; - // - // /** - // * Supply filter containing required capabilities. - // * @param filter Bundle containing capabilities filter. - // */ - // public void setCapabilityStatus(Bundle filter){ - // mStatus = prepareBoolFilter(filter); - // } - // } - /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; 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; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; /** * 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 ((mMyIdentityList.size() == 0) && ( + if ((mAvailableIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } + HttpConnectionThread.logE("getAvailableThirdPartyIdentities", mAvailableIdentityList.toString(), null); + 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(); } + HttpConnectionThread.logE("IE.getMyThirdPartyIdentities", mMyIdentityList.toString(), null); + 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>(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < mMyIdentityList.size(); 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 iCapability = new IdentityCapability(); + iCapability.mCapability = IdentityCapability.CapabilityID.chat; + iCapability.mValue = new Boolean(true); + ArrayList<IdentityCapability> mobileCapabilities = + new ArrayList<IdentityCapability>(); + mobileCapabilities.add(iCapability); + + Identity mobileIdentity = new Identity(); + mobileIdentity.mNetwork = "mobile"; + 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())); } - - - /** - * Add request to fetch available identities. The request is added to the UI - * request and processed when the engine is ready. - * - */ -// private void addUiGetAvailableIdentities() { -// LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); -// emptyUiRequestQueue(); -// addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); -// } - - /** - * Add request to fetch the current user's identities. - * - */ -// private void addUiGetMyIdentities() { -// LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); -// emptyUiRequestQueue(); -// addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); -// } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: - executeGetAvailableIdentitiesRequest(data); - break; - case GET_MY_IDENTITIES: - executeGetMyIdentitiesRequest(data); - break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } - - /** - * Issue request to retrieve 'My' Identities. (Request is not issued if - * there is currently no connectivity). - * - * TODO: remove parameter as soon as branch ui-refresh is merged. - * - * @param data Bundled request data. - * - */ - private void executeGetMyIdentitiesRequest(Object data) { - if (!isConnected()) { - return; - } - newState(State.GETTING_MY_IDENTITIES); - if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { - completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); - } - } /** * 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_CAPABILITY_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); } } - - /** - * Sends a getAvailableIdentities request to the backend. - * - * TODO: remove the parameter as soon as we have merged with the ui-refresh - * branch. - * - * @param data Bundled request data. - */ - private void executeGetAvailableIdentitiesRequest(Object data) { - if (!isConnected()) { - return; - } - newState(State.FETCHING_IDENTITIES); - mAvailableIdentityList.clear(); - if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { - 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { 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: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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) { + HttpConnectionThread.logE("IE.handleGetAvailableIdentitiesResponse", "", null); + 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); } } } 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) { + HttpConnectionThread.logE("handleGetMyIdentitiesResponse", "", null); + LogUtils.logD("IdentityEngine: handleGetMyIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.MY_IDENTITY_DATA_TYPE, data); - if (errorStatus == ServiceStatus.SUCCESS) { - // create mobile identity to support 360 chat - IdentityCapability iCapability = new IdentityCapability(); - iCapability.mCapability = IdentityCapability.CapabilityID.chat; - iCapability.mValue = new Boolean(true); - ArrayList<IdentityCapability> capabilities = - new ArrayList<IdentityCapability>(); - capabilities.add(iCapability); - - Identity mobileIdentity = new Identity(); - mobileIdentity.mNetwork = "mobile"; - mobileIdentity.mName = "Vodafone"; - mobileIdentity.mCapabilities = capabilities; - // end: create mobile identity to support 360 chat - - synchronized (mAvailableIdentityList) { + if (errorStatus == ServiceStatus.SUCCESS) { + synchronized (mMyIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); + HttpConnectionThread.logE("Identity: ", ((Identity)item).toString(), null); } - mMyIdentityList.add(mobileIdentity); } } 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 handleSetIdentityCapabilityStatus(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); } /** * 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); } - - /** - * Create cache of 'chat-able' identities. - * - * @param list List array of retrieved Identities. - */ - private void makeChatableIdentitiesCache(List<Identity> list) { - if (mMyChatableIdentityList == null) { - mMyChatableIdentityList = new ArrayList<String>(); - } else { - mMyChatableIdentityList.clear(); - } - - for (Identity id : list) { - if (id.mActive && id.mCapabilities != null) { - for (IdentityCapability ic : id.mCapabilities) { - if (ic.mCapability == CapabilityID.chat && ic.mValue) { - mMyChatableIdentityList.add(id.mNetwork); - } - } - } - } - } /** * * 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(); - addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); + 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, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } } diff --git a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java index 5ed76c7..c842743 100644 --- a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java +++ b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java @@ -1,498 +1,498 @@ /* * 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.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 data byte array containing Hessian encoded data * @param type Event type * @return List of BaseDataType items parsed from Hessian data * @throws IOException */ public List<BaseDataType> decodeHessianByteArray(byte[] data, Request.Type type, boolean isZipped) 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); } List<BaseDataType> mBaseDataTypeList = null; mMicroHessianInput.init(is); LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); try { mBaseDataTypeList = decodeResponse(is, type); } catch (IOException e) { LogUtils.logE("HessianDecoder.decodeHessianByteArray() " + "IOException during decodeResponse", e); } CloseUtils.close(bis); CloseUtils.close(is); return mBaseDataTypeList; } @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; } } /** * TODO: we cast every response to a Map, losing e.g. push event "c0" which * only contains a string - to fix * * @param is * @param type * @return * @throws IOException */ @SuppressWarnings("unchecked") private List<BaseDataType> decodeResponse(InputStream is, Request.Type type) throws IOException { boolean usesReplyTag = false; List<BaseDataType> mResultList = 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()); mResultList.add(zybErr); return mResultList; } // 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(mResultList, is, tag); return mResultList; } // 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); decodeResponseByRequestType(mResultList, hash, type); } else { // if we have a common request 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); mResultList.add(auth.createFromHashtable(authHash)); } else if (map.containsKey(KEY_CONTACT_LIST)) { // contact list getContacts(mResultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); } 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) { mResultList.add(UserProfile.createFromHashtable(obj)); } } else if (map.containsKey(KEY_USER_PROFILE)) { Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map .get(KEY_USER_PROFILE); mResultList.add(UserProfile.createFromHashtable(userProfileHash)); } else if ((map.containsKey(KEY_IDENTITY_LIST)) || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { int mType = 0; Vector<Hashtable<String, Object>> idcap = null; if (map.containsKey(KEY_IDENTITY_LIST)) { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); - mType = BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE; + mType = BaseDataType.MY_IDENTITY_DATA_TYPE; } else { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); - mType = BaseDataType.MY_IDENTITY_DATA_TYPE; + mType = BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE; } for (Hashtable<String, Object> obj : idcap) { Identity id = new Identity(mType); mResultList.add(id.createFromHashtable(obj)); } } 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) { mResultList.add(ActivityItem.createFromHashtable(obj)); } } } if (usesReplyTag) { is.read(); // read the last 'z' } return mResultList; } 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); } private void decodeResponseByRequestType(List<BaseDataType> clist, Hashtable<String, Object> hash, Request.Type type) { switch (type) { case CONTACT_CHANGES_OR_UPDATES: // create ContactChanges ContactChanges contChanges = new ContactChanges(); contChanges = contChanges.createFromHashtable(hash); clist.add(contChanges); break; case ADD_CONTACT: case SIGN_UP: clist.add(Contact.createFromHashtable(hash)); break; case RETRIEVE_PUBLIC_KEY: // AA define new object type clist.add(PublicKeyDetails.createFromHashtable(hash)); break; case FRIENDSHIP_REQUEST: 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); break; case CONTACT_DETAIL_DELETE: ContactDetailDeletion cdel = new ContactDetailDeletion(); clist.add(cdel.createFromHashtable(hash)); break; case USER_INVITATION: // Not currently supported. break; case CONTACT_GROUP_RELATION_LIST: ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); groupRelationList.populateFromHashtable(hash); clist.add(groupRelationList); break; case CONTACT_GROUP_RELATIONS: ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); groupRelationsList.populateFromHashtable(hash); clist.add(groupRelationsList); break; case GROUP_LIST: ItemList zyblist = new ItemList(ItemList.Type.group_privacy); zyblist.populateFromHashtable(hash); clist.add(zyblist); break; case ITEM_LIST_OF_LONGS: ItemList listOfLongs = new ItemList(ItemList.Type.long_value); listOfLongs.populateFromHashtable(hash); clist.add(listOfLongs); break; case STATUS_LIST: ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); zybstatlist.populateFromHashtable(hash); clist.add(zybstatlist); 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); } break; case EXPECTING_STATUS_ONLY: StatusMsg statMsg = new StatusMsg(); clist.add(statMsg.createFromHashtable(hash)); break; case STATUS: StatusMsg s = new StatusMsg(); s.mStatus = true; clist.add(s); break; case PRESENCE_LIST: PresenceList mPresenceList = new PresenceList(); mPresenceList.createFromHashtable(hash); clist.add(mPresenceList); break; case PUSH_MSG: // parse content of RPG Push msg parsePushMessage(clist, hash); break; case CREATE_CONVERSATION: Conversation mConversation = new Conversation(); mConversation.createFromHashtable(hash); clist.add(mConversation); break; default: LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" + type.name() + "]"); } } 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
3b3d0c4a1529403cd67a17aeca02b90fcfc89f79
PAND-1700, fixed data processing onTimeout()
diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index bd92260..8c24375 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,325 +1,326 @@ /* * 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.ContactSummary.OnlineStatus; 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 // TODO: this hard code needs change, must filter the identities // info by VCARD.IMADRESS Hashtable<String, String> status = new Hashtable<String, String>(); status.put("google", "online"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("facebook.com", "online"); status.put("hyves.nl", "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 users 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 modifications. */ protected static boolean updateDatabase(List<User> users, long idListeningTo, DatabaseHelper dbHelper) { boolean presenceChanged = false; boolean deleteNetworks = false; // the list of networks presence information for me we ignore - the networks where 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); } } return !ignoredNetworks.isEmpty(); } protected static boolean updateMyPresence(User user, DatabaseHelper dbHelper) { boolean contactsChanged = false; SQLiteDatabase writableDb = dbHelper.getWritableDatabase(); if (PresenceTable.updateUser(user, null, writableDb) != 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); } } /** * @param input * @return */ public static boolean notNullOrBlank(String input) { return (input != null) && input.length() > 0; } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 6991a95..5faadf8 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,806 +1,728 @@ /* * 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.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.contactsync.ContactSyncEngine.IContactSyncObserver; -import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; -import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; 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.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, - IContactSyncObserver, ITcpConnectionListener { - /** Check every 10 minutes. **/ + 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 long mNextRuntime = -1; - private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private List<TimelineSummaryItem> mFailedMessagesList; // (to, network) - - private boolean mContObsAdded; /** 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>(); - addAsContactSyncObserver(); } @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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { - if (!mContObsAdded) { - addAsContactSyncObserver(); + 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 (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { + 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 (mNextRuntime == -1) { - LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!"); - return 0; - } else { - return mNextRuntime; + if (firstRun) { + getPresenceList(); + initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); + firstRun = false; } + return getCurrentTimeout(); } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" - + 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) { - if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) { - if (canRun()) { - getPresenceList(); - initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); - // Request to update the UI - setNextRuntime(); - } else { // check after 30 seconds - LogUtils.logE("Can't run PresenceEngine before the contact" - + " list is downloaded:3 - set next runtime in 30 seconds"); - mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20; - } - } - } else { + 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); } - private void setNextRuntime() { - LogUtils.logV("PresenceEngine.setNextRuntime() Run again in [" - + (CHECK_FREQUENCY / (1000 * 60)) + "] minutes"); - mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY; - } - - private void setRunNow() { - LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW"); - mNextRuntime = 0; - } - @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { - initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); - setNextRuntime(); + if (canRun()) { + getPresenceList(); + initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); + setTimeout(CHECK_FREQUENCY); + } } else { - setPresenceOffline(); - mContObsAdded = false; + 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); } @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: - setRunNow(); + if (mLoggedIn) { + if (canRun()) { + 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++; } } - if (mUsers.size() > 0) { - this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS); - } + 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 + "]"); UiAgent uiAgent = mEventCallback.getUiAgent(); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { uiAgent.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 (!canRun()) { - LogUtils.logE("PresenceEngine.handleServerResponce(): " - + "Can't run PresenceEngine before the contact list is downloaded:2"); - return; - } + if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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()) { - LogUtils.logE("PresenceEngine.processUIRequest():" - + " Can't run PresenceEngine before the contact list is downloaded:1"); - return; - } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { Presence.setMyAvailability((Hashtable<String, String>)data); completeUiRequest(ServiceStatus.SUCCESS, null); - setNextRuntime(); + setTimeout(CHECK_FREQUENCY); } break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); completeUiRequest(ServiceStatus.SUCCESS, null); - setNextRuntime(); + setTimeout(CHECK_FREQUENCY); break; case CREATE_CONVERSATION: if (data != null) { List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI - setNextRuntime(); + setTimeout(CHECK_FREQUENCY); } break; case SEND_CHAT_MESSAGE: if (data != null) { 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); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI - setNextRuntime(); + setTimeout(CHECK_FREQUENCY); } break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); } } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } private void initSetMyAvailabilityRequest(User myself) { if (myself == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && - ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) - || !canRun()) { + ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED)) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the state of the engine. Also displays the login notification if * necessary. * * @param accounts */ public void setMyAvailability(Hashtable<String, String> myselfPresence) { if (myselfPresence == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with:" + myselfPresence); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), myselfPresence); Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values for myself myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } 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); } } } - /** - * 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. - */ - private void addAsContactSyncObserver() { - if (EngineManager.getInstance() != null - && EngineManager.getInstance().getContactSyncEngine() != null) { - EngineManager.getInstance().getContactSyncEngine().addEventCallback(this); - mContObsAdded = true; - LogUtils.logD("ActivityEngine contactSync observer added."); - } else { - LogUtils.logE("ActivityEngine can't add to contactSync observers."); - } - } - @Override - public void onContactSyncStateChange(Mode mode, State oldState, State newState) { - LogUtils.logD("PresenceEngine onContactSyncStateChange called."); - } - - @Override - public void onProgressEvent(State currentState, int percent) { - if (percent == 100) { - switch (currentState) { - case FETCHING_SERVER_CONTACTS: - LogUtils - .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_CONTACTS is done"); - // mDownloadServerContactsComplete = true; - // break; - // case SYNCING_SERVER_ME_PROFILE: - // LogUtils - // .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_ME_PROFILE is done"); - // mDownloadMeProfileComplete = true; - // break; - default: - // nothing to do now + public void onConnectionStateChanged(int state) { + if (mLoggedIn && canRun()) { + switch (state) { + case STATE_CONNECTED: + getPresenceList(); + initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; - } + case STATE_CONNECTING: + case STATE_DISCONNECTED: + setPresenceOffline(); + mFailedMessagesList.clear(); + mSendMessagesHash.clear(); + break; + } } } - - @Override - public void onSyncComplete(ServiceStatus status) { - LogUtils.logD("PresenceEngine onSyncComplete called."); - } - - @Override - public void onConnectionStateChanged(int state) { - 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()); } }
360/360-Engine-for-Android
41523906c1af5cf47060a40f1eed22eaed3083fd
modified wrong message name
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index ae1f820..9eabfd5 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,730 +1,730 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; 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; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; /** * 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 the user is currently signed up for. + * Gets all third party identities and adds the mobile identity + * from 360 to them. * - * @return A list of 3rd party identities the user is signed in to or an - * empty list if something went wrong retrieving the identities. + * @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> getMyThirdPartyIdentities() { + public ArrayList<Identity> getAvailableThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( - (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) + (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { - sendGetMyIdentitiesRequest(); + sendGetAvailableIdentitiesRequest(); } - return mMyIdentityList; - } + return mAvailableIdentityList; + } /** * - * Gets all third party identities and adds the mobile identity - * from 360 to them. + * Gets all third party identities the user is currently signed up for. * - * @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. + * @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> getMy360AndThirdPartyIdentities() { + public ArrayList<Identity> getMyThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( - (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) + (System.currentTimeMillis() - mLastMyIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { - sendGetAvailableIdentitiesRequest(); + sendGetMyIdentitiesRequest(); } - return mAvailableIdentityList; - } + 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>(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < mMyIdentityList.size(); 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; } } } return chatableIdentities; } private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ // private void addUiGetAvailableIdentities() { // LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to fetch the current user's identities. * */ // private void addUiGetMyIdentities() { // LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * TODO: remove parameter as soon as branch ui-refresh is merged. * * @param data Bundled request data. * */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { 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: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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); } } } 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) { // create mobile identity to support 360 chat IdentityCapability iCapability = new IdentityCapability(); iCapability.mCapability = IdentityCapability.CapabilityID.chat; iCapability.mValue = new Boolean(true); ArrayList<IdentityCapability> capabilities = new ArrayList<IdentityCapability>(); capabilities.add(iCapability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = "mobile"; mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = capabilities; // end: create mobile identity to support 360 chat synchronized (mAvailableIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } mMyIdentityList.add(mobileIdentity); } } 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 handleSetIdentityCapabilityStatus(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); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } /** * * 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(); addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); } } /** * Return the next run-time for the IdentitiesEngine. Will run as soon as diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index 2355a29..f7a1129 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,361 +1,361 @@ /* * 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 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.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 the user is currently signed up for. + * Gets all third party identities and adds the mobile identity + * from 360 to them. * - * @return A list of 3rd party identities the user is signed in to or an - * empty list if something went wrong retrieving the identities. + * @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> getMyThirdPartyIdentities(); + public ArrayList<Identity> getAvailableThirdPartyIdentities(); /** * - * Gets all third party identities and adds the mobile identity - * from 360 to them. + * Gets all third party identities the user is currently signed up for. * - * @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. + * @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> getMy360AndThirdPartyIdentities(); + 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 availability state for a single network. * @param presence Network-presence to set */ void setAvailability(NetworkPresence presence); /*** * 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 a47dabd..3cf2bb3 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,433 +1,433 @@ /* * 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> getMy360AndThirdPartyIdentities() { - return EngineManager.getInstance().getIdentityEngine().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); } /*** * @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
6ba5657e88a2e90b845dc513722af971a1c4fdcd
now calling the correct method for identities I hope
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index b65d693..152e6d9 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -291,531 +291,529 @@ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, break; case IDLE: default: setRunNow(); } } @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++; } } if (mUsers.size() > 0) { 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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { final int type = mBaseDataType.getType(); switch(type) { case BaseDataType.PRESENCE_LIST_DATA_TYPE: handlePresenceList((PresenceList)mBaseDataType); break; case BaseDataType.PUSH_EVENT_DATA_TYPE: handlePushEvent(((PushEvent)mBaseDataType)); break; case BaseDataType.CONVERSATION_DATA_TYPE: // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); break; case BaseDataType.SYSTEM_NOTIFICATION_DATA_TYPE: handleSystemNotification((SystemNotification)mBaseDataType); break; case BaseDataType.SERVER_ERROR_DATA_TYPE: handleServerError((ServerError)mBaseDataType); break; default: 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.mMessageType); } } 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()) { 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 SET_MY_AVAILABILITY_FOR_COMMUNITY: Presence.setMyAvailabilityForCommunity(); 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); setNextRuntime(); } /** * 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()) { 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 presence list constructed from identities Hashtable<String, String> presences = getPresencesForStatus(status); if(presences == null) { LogUtils.logW("setMyAvailability() Ignoring setMyAvailability request because there are no identities!"); return; } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), presences); // set the DB values for myself me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(me); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presences); } /** * 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) { 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().getMy360AndThirdPartyIdentities(); + 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) { - if(!identity.mNetwork.equals(SocialNetwork.PC.toString())) { presences.put(identity.mNetwork, statusString); - } } return presences; } }
360/360-Engine-for-Android
93617b15697b76b8a141f1f9e343bff5ed61f475
added changes to prepare the UI for the new getters
diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index 4181983..2355a29 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,333 +1,361 @@ /* * 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 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.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(); - /*** - * Begins the process of retrieving Third party Accounts that the user is - * already registered with from the Vodafone 360 back end. The response is - * sent to any currently registered Activity handlers. + /** + * + * 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(); + + /** + * + * 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> getMy360AndThirdPartyIdentities(); + + /** + * + * 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. * - * @param Bundle filter the kind of identities to return. */ - //void fetchMyIdentities(Bundle data); + 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 availability state for a single network. * @param presence Network-presence to set */ void setAvailability(NetworkPresence presence); /*** * 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 4da73ae..a47dabd 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,427 +1,433 @@ /* * 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#fetchAvailableIdentities(Bundle) + /** + * @see com.vodafone360.people.service.interfaces.IPeopleService#getMyThirdPartyIdentities() */ -/* @Override - public void fetchAvailableIdentities(Bundle data) { - EngineManager.getInstance().getIdentityEngine().addUiGetAvailableIdentities(); - }*/ + public ArrayList<Identity> getMyThirdPartyIdentities() { + return EngineManager.getInstance().getIdentityEngine().getMyThirdPartyIdentities(); + } - /*** - * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchMyIdentities(Bundle) + /** + * @see com.vodafone360.people.service.interfaces.IPeopleService#getMy360AndThirdPartyIdentities() */ - /*@Override - public void fetchMyIdentities(Bundle data) { - EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(); - }*/ + public ArrayList<Identity> getMy360AndThirdPartyIdentities() { + return EngineManager.getInstance().getIdentityEngine().getMy360AndThirdPartyIdentities(); + } + + /** + * @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); } /*** * @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
f7f86610ac3e0d370cc9e71a95a20db8b083af57
PAND-1553 JUnit Tests fixed
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 977e4f8..589235e 100644 --- a/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeContactsApiTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeContactsApiTest.java @@ -1,800 +1,825 @@ /* * 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 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; - private static final String PEOPLE_ACCOUNT_TYPE = "com.vodafone360.people.android.account"; + /** + * 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); + 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("ghewoih4oihoi")); - assertNull(mNabApi.getAccountsByType("xpto")); + 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("xpto")); + 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("xpto")); + 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 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)); } } } /** * 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 { 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 df8d87d..82b5f43 100644 --- a/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeImporterTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/contactsync/NativeImporterTest.java @@ -1,1227 +1,1252 @@ /* * 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 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 { + /** - * The gmail account type. + * 360 client account type. */ - private final static String GMAIL_ACCOUNT_TYPE = "com.google"; - + protected static final int PEOPLE_ACCOUNT_TYPE = 1; + /** - * A third party account type. + * Google account type. */ - private final static String THIRD_PARTY_ACCOUNT_TYPE = "com.thirdparty"; - + 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"; + /** - * The 360 People account type. + * Google account, there can be more than one of these */ - private final static String PEOPLE_ACCOUNT_TYPE = (String)getField("PEOPLE_ACCOUNT_TYPE", com.vodafone360.people.engine.contactsync.NativeContactsApi.class); + 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); /** * 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; /** * 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); /** * A test Gmail account. */ - public final static Account GMAIL_ACCOUNT_1 = new Account("[email protected]", GMAIL_ACCOUNT_TYPE); + 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]", GMAIL_ACCOUNT_TYPE); + 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); + 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); + 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) { 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); // 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) { 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(String type) { - - return filterAccountsByType(getAccounts(), type); + 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); 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
e7bb320d36268cc900ec770c17201cf734d3749b
PAND-1553 and PAND-1689 final commit
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java index 89305cd..84dfeab 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java @@ -1,390 +1,393 @@ /* * 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); /** * 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 vendro specific one. All vendor specific + * 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/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index bc70ea3..52cf59d 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,2164 +1,2158 @@ /* * 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 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.LogUtils; -import com.vodafone360.people.utils.CursorUtils; -import com.vodafone360.people.utils.VersionUtils; - -import dalvik.system.PathClassLoader; - 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.Event; -import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Email; -import android.provider.ContactsContract.CommonDataKinds.Organization; +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.Website; -import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; +import android.provider.ContactsContract.CommonDataKinds.Organization; +import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; -import android.provider.ContactsContract.CommonDataKinds.GroupMembership; +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. + * 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; - /** +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 - }; - - /** - * 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 ("; + 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"; + 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+"\""; + 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. + * 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); - } + + /** + * 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!?). + * 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 + * 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; + private boolean mYield = true; + /** * Batch used for Contact Writing operations. */ - private BatchOperation mBatch = new BatchOperation(); - + private BatchOperation mBatch = new BatchOperation(); + /** - * Inner class for applying batches. - * TODO: Move to own class if batches become supported in other areas + * 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 + * + * @param cpo The */ public void add(ContentProviderOperation cpo) { mOperations.add(cpo); } - + /** - * Clears all operations in the batch - * Effectively resets the batch. + * Clears all operations in the batch Effectively resets the batch. */ public void clear() { mOperations.clear(); } - - public ContentProviderResult[] execute() { + + public ContentProviderResult[] execute() { ContentProviderResult[] resultArray = null; - - if(mOperations.size() > 0) { + + 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. + * 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"; - + 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) + * 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 + * 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. + * 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+")"); + LogUtils.logI("NativeContactsApi2.NativeContentObserver.onChange(" + selfChange + ")"); mAbstractedObserver.onChange(); } } - + /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { - LogUtils.logI("NativeContactsApi2.registerObserver()"); + LogUtils.logI("NativeContactsApi2.registerObserver()"); if (mAbstractedObserver != null) { - throw new RuntimeException("Only one observer at a time supported... Please unregister first."); + 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) { + 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]; + accounts = new Account[accounts2xApi.length]; for (int i = 0; i < accounts2xApi.length; i++) { - accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); + 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; } } case PHONE_ACCOUNT_TYPE: { 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); + 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)) { + 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); + // TODO: RE-ENABLE SYNC VIA SYSTEM + ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0); + // ContentResolver.setSyncAutomatically(account, + // ContactsContract.AUTHORITY, true); } - } catch(Exception ex) { + } 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); + 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); - if(accounts != null && accounts.length > 0) { + 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) - */ + + /** + * @see NativeContactsApi#getContactIds(Account) + */ @Override - public long[] getContactIds(Account account) { + public long[] getContactIds(Account account) { // Need to construct a where clause - if(account != null) { + 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 + @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 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; - } - - /** + 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); + addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI)).withYieldAllowed(mYield) + .withValues(mValues); mBatch.add(builder.build()); - + final int ccListSize = ccList.length; - for(int i = 0 ; i < ccListSize; i++) { + for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; - if(cc != null) { + if (cc != null) { final int key = cc.getKey(); - if(key == ContactChange.KEY_VCARD_ORG && - mMarkedOrganizationIndex < 0) { + if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; - } - if(key == ContactChange.KEY_VCARD_TITLE && - mMarkedTitleIndex < 0) { + } + 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 + + // 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!"); + 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()); + + 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++) { + 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) { + if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; - } - if(key == ContactChange.KEY_VCARD_TITLE && - mMarkedTitleIndex < 0) { + } + if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } - - switch(cc.getType()) { + + 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) { + 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()); + 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) { + 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()); + 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); + 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; + // 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. + * 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, + final Cursor cursor = mCr.query(RawContacts.CONTENT_URI, CONTACTID_PROJECTION, selection, null, null); - - if(cursor == null) { - return null; + + if (cursor == null) { + return null; } - + try { final int cursorCount = cursor.getCount(); - if(cursorCount > 0) { + if (cursorCount > 0) { tempIds = new long[cursorCount]; - - while(cursor.moveToNext()) { + + while (cursor.moveToNext()) { final long id = cursor.getLong(CONTACTID_PROJECTION_RAW_ID); - final String accountType = - cursor.getString(CONTACTID_PROJECTION_ACCOUNT_TYPE); + final String accountType = cursor.getString(CONTACTID_PROJECTION_ACCOUNT_TYPE); // TODO: Remove hardcoding (if statement) - if(TextUtils.isEmpty(accountType) || - accountType.equals(NativeContactsApi.PEOPLE_ACCOUNT_TYPE) || - isContactInMyContactsGroup(id)) { + 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 + + 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 + * 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, + final Cursor cursor = mCr.query(Groups.CONTENT_URI, GROUPID_PROJECTION, MY_CONTACTS_GROUP_WHERE_CLAUSE, null, null); - - if(cursor == null) { - return; + + if (cursor == null) { + return; } - + try { final int count = cursor.getCount(); - if(count > 0) { + if (count > 0) { mMyContactsGroupRowIds = new long[count]; - for(int i = 0; i < count; i++) { + 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); - + 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++) { + for (int i = 0; i < rowIdCount; i++) { sb.append(mMyContactsGroupRowIds[i]); - if(i < rowIdCount - 1) { + if (i < rowIdCount - 1) { sb.append(','); } } - + sb.append(')'); - final Cursor cursor = mCr.query(dataUri, null, sb.toString(), - null, null); + 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. + * 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 + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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. + */ + 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 + 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); + 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) { + 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) { + 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) { + 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) { + } + + /** + * 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); + 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); + } + } + + /** + * 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(); + } + + /** + * 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)); + 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()) { + } + + // 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); 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 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); - } - - /** + 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); - } - - /** + 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) { + 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); - } - - /** + 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); - + 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.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); - } - - /** + 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); -// } -// } - - + 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) { + int flags = ContactChange.FLAG_NONE; + if (mMarkedOrganizationIndex > -1) { final ContactChange cc = ccList[mMarkedOrganizationIndex]; - flags|= cc.getFlags(); + flags |= cc.getFlags(); final Organisation organization = VCardHelper.getOrg(cc.getValue()); - if(organization != null) { + 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 + 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) { + + if (mMarkedTitleIndex > -1) { final ContactChange cc = ccList[mMarkedTitleIndex]; - flags|= cc.getFlags(); + 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); + + 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 + + /** + * 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) { + 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); + 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()) { + 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) { + 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) { + + 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) { + 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) { + if (organization.unitNames.size() > 0) { department = organization.unitNames.get(0); } } - + flags = cc.getFlags(); } else { // Delete case company = null; department = null; } } - - if(mMarkedTitleIndex >= 0) { + + 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. + 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.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) { + 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. + } 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) + * @return {@link ContactChange} array containing new IDs (may contain some + * null elements) */ private ContactChange[] executeNewContactBatch(ContactChange[] ccList) { - if(mBatch.size() == 0) { + if (mBatch.size() == 0) { // Nothing to execute return null; } final ContentProviderResult[] results = mBatch.execute(); - - if(results == null || results.length == 0) { + + 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) { + + 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], + 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) { + while (resultsIndex < resultsSize) { + if (ccListIndex == mMarkedOrganizationIndex || ccListIndex == mMarkedTitleIndex) { ccListIndex++; continue; } - - if(results[resultsIndex].uri == null) { + + if (results[resultsIndex].uri == null) { throw new RuntimeException("NativeContactsApi2.executeNewContactBatch()" - + "Unexpected null URI for NAB Contact:"+nabContactId); + + "Unexpected null URI for NAB Contact:" + nabContactId); } - - if(resultsIndex == resultsSize - 1 && haveOrganization) { - // for readability we leave Organization/Title for outside the loop - break; + + 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], + 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); + + 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); + idChange.setNabDetailId(nabDetailId); idChangeList[mMarkedOrganizationIndex + 1] = idChange; } - - if(mMarkedTitleIndex > -1) { - final ContactChange idChange = - ContactChange.createIdsChange( - ccList[mMarkedTitleIndex], - ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); + + 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) + * @return {@link ContactChange} array containing new IDs (may contain some + * null elements) */ private ContactChange[] executeUpdateContactBatch(ContactChange[] ccList) { - if(mBatch.size() == 0) { + if (mBatch.size() == 0) { // Nothing to execute return null; } final ContentProviderResult[] results = mBatch.execute(); final int resultsSize = results.length; - if(results == null || resultsSize == 0) { + 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) { + 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 (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; + + 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], + 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) { + + if (haveOrganization) { long nabDetailId = ContactChange.INVALID_ID; - if(mExistingOrganizationId != nabDetailId) { + if (mExistingOrganizationId != nabDetailId) { nabDetailId = mExistingOrganizationId; - } else if (results[resultsIndex].uri != null){ + } 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()); + + "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); + + 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); + + 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 + * + * @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(); + 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. + * 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); + 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. + * 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; - } - + 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 + 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; - } - + 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 + 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; - } - + 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) { + if ((flags & ContactChange.FLAG_HOME) == ContactChange.FLAG_HOME) { return StructuredPostal.TYPE_HOME; } - - if((flags & ContactChange.FLAG_WORK) == - ContactChange.FLAG_WORK) { + + 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 + * 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; - } + private static int mapFromNabOrganizationType(int nabType) { + if (nabType == Organization.TYPE_WORK) { + return ContactChange.FLAG_WORK; + } + + return ContactChange.FLAG_NONE; + } - 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) { + 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 + * 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; - } - + 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) { + 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) { + + if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return Website.TYPE_WORK; } - + return Website.TYPE_OTHER; - } + } } diff --git a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java index 4c8707e..81b55e9 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java @@ -1,736 +1,750 @@ /* * 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. + * 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 - final String accountType = firstTimeImport ? GOOGLE_ACCOUNT_TYPE : NativeContactsApi.PEOPLE_ACCOUNT_TYPE; - - mAccounts = mNativeContactsApi.getAccountsByType(accountType); - - if (firstTimeImport) mIsFirstImportOn2X = true; + // account to import from: 360 account if created, all the google + // accounts otherwise + if (firstTimeImport) { + ArrayList<Account> accountList = new ArrayList<Account>(); + for (Account account : mNativeContactsApi + .getAccountsByType(NativeContactsApi.GOOGLE_ACCOUNT_TYPE)) { + accountList.add(account); + } + for (Account account : mNativeContactsApi + .getAccountsByType(NativeContactsApi.PHONE_ACCOUNT_TYPE)) { + 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) { // 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;
360/360-Engine-for-Android
79f83664d2dec1e2021944e02dde6ccd9b989859
Fixing the wrecked code from my failed merge
diff --git a/src/com/vodafone360/people/datatypes/ActivityContact.java b/src/com/vodafone360/people/datatypes/ActivityContact.java index 9f25c69..73b91ac 100644 --- a/src/com/vodafone360/people/datatypes/ActivityContact.java +++ b/src/com/vodafone360/people/datatypes/ActivityContact.java @@ -1,244 +1,244 @@ /* * 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.nio.ByteBuffer; import java.util.Enumeration; import java.util.Hashtable; import com.vodafone360.people.datatypes.ContactDetail.DetailKeyTypes; /** * BaseDataType encapsulating an Activity Contact which contains contact * information associated with an Activity response retrieved from the server. */ public class ActivityContact extends BaseDataType { /** * Tags for fields associated with Activity Contacts. */ private enum Tags { CONTACT_ID("contactid"), USER_ID("userid"), NAME("name"), ADDRESS("address"), TYPE("type"), NETWORK("network"), AVATAR("avatar"), AVATAR_MIME("avatarmime"), AVATAR_URL("avatarurl"); private final String tag; /** * Constructor for Tags item. * * @param s String value associated with Tags item. */ private Tags(final String s) { tag = s; } /** * String value associated with Tags item * * @return String 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 */ private static Tags findTag(String tag) { for (Tags tags : Tags.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } return null; } } /** The contact server id if the activity can be related to a contact. */ public Long mContactId = null; /** Local id for a Contact if activity can be related to a Contact. */ public Long mLocalContactId = null; /** * The user id if the activity can be related to a user, e.g. a message from * a VF user but non-contact contains userid but not contactid, whereas a * message from a contact that is also a VF user contains both contactid and * userid. */ public Long mUserId = null; /** * Contains the name of the other user. When contactid is present, the name * from the addressbook. When only userid is present, the name on the user's * profile. When none is present, the name captured from the outside, if * possible, e.g. the name on the email From header. In a case like a SMS * received from an unknown number, there is no name. */ public String mName = null; /** * Optional for non-messages. Contains the MSISDN, email, etc, needed to * reply back. */ public String mAddress = null; /** * Optional for non-messages. Contains the type (mobile, work, etc.) * captured from the addressbook, if available. */ private ContactDetail.DetailKeyTypes mType = null; /** * This field contains information about the network (e.g. phone, flickr, * google). */ public String mNetwork = null; /** * Defines the binary data for the user's icon. The type of the binary data * is defined into the avatarmime field. */ private ByteBuffer mAvatar = null; /** Defines the MIME type of the avatar binary data. */ private String mAvatarMime = null; /** * Defines an http url that the client can use to retrieve the avatar binary * data. Can be used to embed the url into an IMG HTML tag. */ public String mAvatarUrl = null; /** {@inheritDoc} */ @Override - public int type() { + public int getType() { return ACTIVITY_CONTACT_DATA_TYPE; } /** * Create ActivityContact from Hashtable (generated from Hessian encoded * response). * * @param hash Hashtable containing ActivityContact data * @return ActivityContact created from supplied Hashtable. */ public static ActivityContact createFromHashTable(Hashtable<String, Object> hash) { final ActivityContact zcon = new ActivityContact(); Enumeration<String> e = hash.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); Object value = hash.get(key); Tags tag = Tags.findTag(key); zcon.setValue(tag, value); } return zcon; } /** * 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 val) { if (tag != null) { switch (tag) { case ADDRESS: mAddress = (String)val; break; case AVATAR: byte[] avabytes = (byte[])val; mAvatar = ByteBuffer.allocate(avabytes.length); mAvatar.put(avabytes); break; case AVATAR_MIME: mAvatarMime = (String)val; break; case AVATAR_URL: mAvatarUrl = (String)val; break; case CONTACT_ID: mContactId = (Long)val; break; case NAME: mName = (String)val; break; case NETWORK: mNetwork = (String)val; break; case TYPE: mType = DetailKeyTypes.findKey((String)val); break; case USER_ID: mUserId = (Long)val; break; default: // Do nothing. break; } } } /** {@inheritDoc} */ @Override public String toString() { final StringBuffer sb = new StringBuffer("ActivityContact:\n\t\tContact Id = "); sb.append(mContactId); sb.append("\n\t\tLocal contact Id = "); sb.append(mLocalContactId); sb.append("\n\t\tUser Id = "); sb.append(mUserId); sb.append("\n\t\tName = "); sb.append(mName); sb.append("\n\t\tAddress = "); sb.append(mAddress); sb.append("\n\t\tType = "); sb.append(mType); sb.append("\n\t\tNetwork = "); sb.append(mNetwork); if (mAvatar != null) { sb.append("\n\t\tAvatar = "); sb.append(String.valueOf(mAvatar)); } sb.append("\n\t\tAvatar mime = "); sb.append(mAvatarMime); sb.append("\n\t\tAvatar URL = "); sb.append(mAvatarUrl); return sb.toString(); } } diff --git a/src/com/vodafone360/people/datatypes/AuthSessionHolder.java b/src/com/vodafone360/people/datatypes/AuthSessionHolder.java index 8e24c11..aa44c9c 100644 --- a/src/com/vodafone360/people/datatypes/AuthSessionHolder.java +++ b/src/com/vodafone360/people/datatypes/AuthSessionHolder.java @@ -1,167 +1,162 @@ /* * 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; } - /** {@inheritDoc} */ - @Override -<<<<<<< HEAD - public int type() { -======= - public int getType() { ->>>>>>> 5ab21f731a48ab98689573eeae02afa669913d42 + + public int getType() { return AUTH_SESSION_HOLDER_TYPE; } /** {@inheritDoc} */ public String toString() { final StringBuilder sb = 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); 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; } } } diff --git a/src/com/vodafone360/people/datatypes/BaseDataType.java b/src/com/vodafone360/people/datatypes/BaseDataType.java index 2cd405b..10915d9 100644 --- a/src/com/vodafone360/people/datatypes/BaseDataType.java +++ b/src/com/vodafone360/people/datatypes/BaseDataType.java @@ -1,148 +1,140 @@ /* * 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 { - /** -<<<<<<< HEAD - * Return name of the current Data-type. - * - * @return int containing the data-type. - */ - abstract public int type(); -======= + /** * Get the data type * @return The data-type. */ - abstract public int getType(); ->>>>>>> 5ab21f731a48ab98689573eeae02afa669913d42 + 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; } diff --git a/src/com/vodafone360/people/datatypes/ChatMessage.java b/src/com/vodafone360/people/datatypes/ChatMessage.java index bcbe18d..09121d2 100644 --- a/src/com/vodafone360/people/datatypes/ChatMessage.java +++ b/src/com/vodafone360/people/datatypes/ChatMessage.java @@ -1,220 +1,216 @@ /* * 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.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Vector; import com.vodafone360.people.service.io.rpg.RpgPushMessage; import com.vodafone360.people.utils.LogUtils; public class ChatMessage extends BaseDataType { /** Unique server-supplied conversation id */ private String mConversationId; /** The "from" user */ private String mUserId; /** localContactId of the "from" user in the Contacts table */ private long mLocalContactId; /** Network id of the "from" user (as in the SocialNetwork enumeration) */ private int mNetworkId; private String mBody; /** The "to" user */ private List<String> mTos; /** * When the message was created (for sent messages) /received by the client. */ private long mTimeStamp; public enum Tags { CONVERSATION_ID("conversation"), RECIPIENTS_LIST("tos"), FROM("from"), BODY("body"); private final String mTag; private Tags(String tag) { mTag = tag; } public String tag() { return mTag; } private static Tags findTag(String tag) { for (Tags tags : Tags.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } return null; } } /** * Create ChatMessage from Hashtable generated by Hessian-decoder. * * @param hash Hashtable containing ChatMessage parameters */ private void createFromHashtable(Hashtable<String, Object> hash) { LogUtils.logI("ChatMessage.createFromHashtable() hash[" + hash.toString() + "]"); 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)); } } } private void setValue(Tags key, Object value) { switch (key) { case BODY: mBody = (String)value; break; case CONVERSATION_ID: mConversationId = (String)value; break; case FROM: mUserId = (String)value; break; case RECIPIENTS_LIST: @SuppressWarnings("unchecked") Vector<String> vect = (Vector<String>)value; mTos = new ArrayList<String>(vect); break; default: LogUtils.logE("ChatMessage.setValue() key[" + key + "] value[" + value + "] Unsupported KEY"); } } public ChatMessage() { // Do nothing. } protected ChatMessage(RpgPushMessage msg) { createFromHashtable(msg.mHash); } - @Override -<<<<<<< HEAD - public int type() { -======= - public int getType() { ->>>>>>> 5ab21f731a48ab98689573eeae02afa669913d42 + @Override + public int getType() { return CHAT_MSG_DATA_TYPE; } public String getConversationId() { return mConversationId; } public void setConversationId(String conversationId) { this.mConversationId = conversationId; } public String getBody() { return mBody; } public void setBody(String body) { this.mBody = body; } public List<String> getTos() { return mTos; } public void setTos(List<String> tos) { this.mTos = tos; } public Long getLocalContactId() { return mLocalContactId; } public void setLocalContactId(Long localContactId) { this.mLocalContactId = localContactId; } public String getUserId() { return mUserId; } public void setUserId(String senderUserId) { this.mUserId = senderUserId; } public int getNetworkId() { return mNetworkId; } public void setNetworkId(int networkId) { this.mNetworkId = networkId; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Chat Message [mBody="); sb.append(mBody); sb.append(", mConversationId="); sb.append(mConversationId); sb.append(", mLocalContactId="); sb.append(mLocalContactId); sb.append(", mNetworkId="); sb.append(mNetworkId); sb.append(", mUserId="); sb.append(mUserId); sb.append(", mTos="); sb.append(mTos); sb.append("]"); return sb.toString(); } /** * This method returns the time when the message was created/sent. */ public long getTimeStamp() { return mTimeStamp; } /** * This method sets the time when the message was created/sent into this ChatMessage. * @param timeStamp long - the time when the message was created. */ public void setTimeStamp(long timeStamp) { this.mTimeStamp = timeStamp; } } diff --git a/src/com/vodafone360/people/datatypes/Contact.java b/src/com/vodafone360/people/datatypes/Contact.java index 279b337..bca9374 100644 --- a/src/com/vodafone360/people/datatypes/Contact.java +++ b/src/com/vodafone360/people/datatypes/Contact.java @@ -1,657 +1,653 @@ /* * 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.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Vector; import android.os.Parcel; import android.os.Parcelable; import com.vodafone360.people.database.persistenceHelper.Persistable; import com.vodafone360.people.database.persistenceHelper.Persistable.Entity; import com.vodafone360.people.database.persistenceHelper.Persistable.Table; import com.vodafone360.people.utils.LogUtils; /** * BaseDataType encapsulating a Contact retrieved from, or sent to, Now+ server. * <p> * Represents a contact in the people client database with all the associated * information. Information stored in a contact is fetched from multiple * sub-tables. For example a contact is made up of multiple details which are * fetched from the contact details table. * <p> * The lighter weight {@link ContactSummary} object should be used if only the * contact name and essential details are needed. */ @Entity @Table(name = "Contacts") public class Contact extends BaseDataType implements Parcelable, Persistable { /** * Tags for fields associated with Contact items. */ private enum Tags { CONTACT_ID("contactid"), GENDER("gender"), DELETED("deleted"), USER_ID("userid"), ABOUT_ME("aboutme"), UPDATED("updated"), SOURCES("sources"), DETAIL_LIST("detaillist"), DETAIL("detail"), GROUP_LIST("groupidlist"), FRIEND("friend"), PROFILE_PATH("profilepath"), // only for user profile SYNCTOPHONE("synctophone"); // used for 'Phonebook' group private final String tag; /** * Constructor for Tags item. * * @param s String value associated with Tag. */ private Tags(String s) { tag = s; } /** * String value associated with Tags item. * * @return String value associated with Tags item. */ private String tag() { return tag; } } /** * Primary key in the database */ @Id @Column(name = "LocalId") public Long localContactID = null; /** * Contains the about me string provided by the server */ @Column(name = "AboutMe") public String aboutMe = null; /** * The server ID (or null if the contact has not yet been synchronised) */ @Column(name = "ServerId") public Long contactID = null; /** * 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 -<<<<<<< HEAD - public int type() { -======= - public int getType() { ->>>>>>> 5ab21f731a48ab98689573eeae02afa669913d42 + @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; } /** * 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
ec6ef58bc8bb87b83bacb32161241b264dd59f38
Trying to correct the previous commit
diff --git a/src/com/vodafone360/people/datatypes/Identity.java b/src/com/vodafone360/people/datatypes/Identity.java index 8a0741d..46bc01e 100644 --- a/src/com/vodafone360/people/datatypes/Identity.java +++ b/src/com/vodafone360/people/datatypes/Identity.java @@ -1,619 +1,614 @@ /* * 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.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Vector; import android.os.Parcel; import android.os.Parcelable; import com.vodafone360.people.utils.LogUtils; /** * BaseDataType encapsulating an Identity issued to or retrieved from server */ public class Identity extends BaseDataType implements Parcelable { /** * Tags associated with Identity item. */ private enum Tags { IDENTITY_MAIN_TAG("availableidentity"), IDENTITY_CAPABILITY_LIST("identitycapabilitylist"), PLUGIN_ID("pluginid"), NETWORK_URL("networkurl"), AUTH_TYPE("authtype"), ICON_MIME("iconmime"), ICON2_MIME("icon2mime"), ORDER("order"), NAME("name"), ICON_URL("iconurl"), ICON2_URL("icon2url"), NETWORK("network"), // Properties below are only present after // GetMyIdentities. ACTIVE("active"), CREATED("created"), IDENTITY_ID("identityid"), UPDATED("updated"), IDENTITY_TYPE("identitytype"), USER_ID("userid"), USER_NAME("username"), DISPLAY_NAME("displayname"), COUNTRY_LIST("countrylist"); private final String tag; /** * Construct Tags item from supplied String * * @param s String value for Tags item. */ private Tags(String s) { tag = s; } /** * String value for 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 in Tags items. * @return Tags item for specified String, NULL otherwise. */ private static Tags findTag(String tag) { for (Tags tags : Tags.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } return null; } } public String mPluginId = null; public String mNetwork = null; public URL mNetworkUrl = null; public URL mIconUrl = null; public URL mIcon2Url = null; public String mAuthType; public String mIconMime = null; public Integer mOrder = null; public String mName = null; public List<IdentityCapability> mCapabilities = null; /** Properties below are only present after GetMyIdentities. */ public Boolean mActive = null; public Long mCreated = null; public Long mUpdated = null; public String mIdentityId = null; public Integer mUserId = null; public String mUserName = null; public String mDisplayName = null; public List<String> mCountryList = null; public String mIdentityType = null; private int mType; /** * Comparator class used to compare Identities retrieved from server to * remove duplicates from list passed to People client UI. */ public static class IdentityComparator implements Comparator<Identity> { @Override public int compare(Identity object1, Identity object2) { return object1.mOrder.compareTo(object2.mOrder); } } /** * Test whether current Identity is identical to supplied Identity. * * @param id Identity to compare against. * @return true if Identities match, false otherwise. */ public boolean isSameAs(Identity id) { boolean isSame = true; if (!areStringValuesSame(mPluginId, id.mPluginId) || !areStringValuesSame(mNetwork, id.mNetwork) || !areStringValuesSame(mIdentityId, id.mIdentityId) || !areStringValuesSame(mDisplayName, id.mDisplayName)) { isSame = false; } if (mNetworkUrl != null && id.mNetworkUrl != null) { if (!mNetworkUrl.sameFile(id.mNetworkUrl)) { isSame = false; } } else if (mNetworkUrl == null && id.mNetworkUrl == null) { // Do nothing. } else { isSame = false; } if (mIconUrl != null && id.mIconUrl != null) { if (!mIconUrl.sameFile(id.mIconUrl)) { isSame = false; } } else if (mIconUrl == null && id.mIconUrl == null) { // Do nothing. } else { isSame = false; } return isSame; } /** * String values comparison * * @param s1 First String to test. * @param s2 Second String to test. * @return true if Strings match (or both are null), false otherwise. */ private boolean areStringValuesSame(String s1, String s2) { boolean isSame = true; if (s1 == null && s2 == null) { // Do nothing. } else if (s1 != null && s2 != null) { if (s1.compareTo(s2) != 0) { isSame = false; } } else { isSame = false; } return isSame; } /** * Default constructor. */ public Identity() { // Do nothing. } public Identity(int type) { mType = type; } /** * Create Identity from Parcel. * * @param in Parcel containing Identity. */ private Identity(Parcel in) { readFromParcel(in); } /** {@inheritDoc} */ - @Override -<<<<<<< HEAD - public int type() { - return mType; -======= + @Override public int getType() { // TODO: Return appropriate type if its // an available identity instead of my identity - return MY_IDENTITY_DATA_TYPE; ->>>>>>> Correction to my previous type() modification and cleaned up a lot of toString() methods + return MY_IDENTITY_DATA_TYPE; } /** * Populate Identity from supplied Hashtable. * * @param hash Hashtable containing identity details. * @return Identity instance. */ public Identity createFromHashtable(Hashtable<String, Object> hash) { Enumeration<String> e = hash.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); Object value = hash.get(key); Tags tag = Tags.findTag(key); if (tag != null) setValue(tag, value); } 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 val) { switch (tag) { case AUTH_TYPE: mAuthType = (String)val; break; case ICON_MIME: mIconMime = (String)val; break; case ICON2_MIME: // TODO: Remove TAG value? // mIcon2Mime = (String)val; break; case ICON_URL: try { mIconUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIconUrl = null; } break; case ICON2_URL: try { mIcon2Url = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIcon2Url = null; } break; case IDENTITY_CAPABILITY_LIST: /** Create id capability list. */ @SuppressWarnings("unchecked") Vector<Hashtable<String, Object>> v = (Vector<Hashtable<String, Object>>)val; if (mCapabilities == null) { mCapabilities = new ArrayList<IdentityCapability>(); } for (Hashtable<String, Object> obj : v) { IdentityCapability cap = new IdentityCapability(); cap.createFromHashtable(obj); mCapabilities.add(cap); } break; case IDENTITY_MAIN_TAG: // Not currently handled. break; case NAME: mName = (String)val; break; case NETWORK: mNetwork = (String)val; break; case NETWORK_URL: try { mNetworkUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong network url: '" + val + "'"); mNetworkUrl = null; } break; case ORDER: mOrder = (Integer)val; break; case PLUGIN_ID: mPluginId = (String)val; break; case ACTIVE: mActive = (Boolean)val; break; case CREATED: mCreated = (Long)val; break; case DISPLAY_NAME: mDisplayName = (String)val; break; case IDENTITY_ID: mIdentityId = (String)val; break; case IDENTITY_TYPE: mIdentityType = (String)val; break; case UPDATED: mUpdated = (Long)val; break; case USER_ID: mUserId = ((Long)val).intValue(); break; case USER_NAME: mUserName = (String)val; break; case COUNTRY_LIST: if (mCountryList == null) { mCountryList = new ArrayList<String>(); } break; default: // Do nothing. break; } } /** {@inheritDoc} */ @Override public String toString() { final StringBuffer sb = new StringBuffer("Name:"); sb.append(mName); sb.append("\nPluginID:"); sb.append(mPluginId); sb.append("\nNetwork:"); sb.append(mNetwork); sb.append("\nNetworkURL:"); sb.append(mNetworkUrl); sb.append("\nAuthType:"); sb.append(mAuthType); sb.append("\nIcon mime:"); sb.append(mIconMime); sb.append("\nIconURL:"); sb.append(mIconUrl); sb.append("\nOrder:"); sb.append(mOrder); sb.append("\nActive:"); sb.append(mActive); sb.append("\nCreated:"); sb.append(mCreated); sb.append("\nUpdated:"); sb.append(mUpdated); sb.append("\nIdentityId:"); sb.append(mIdentityId); sb.append("\nUserId:"); sb.append(mUserId); sb.append("\nUserName:"); sb.append(mUserName); sb.append("\nDisplayName:"); sb.append(mDisplayName); sb.append("\nIdentityType:"); sb.append(mIdentityType); if (mCountryList != null) { sb.append("\nCountry List: ("); sb.append(mCountryList.size()); sb.append(") = ["); for (int i = 0; i < mCountryList.size(); i++) { sb.append(mCountryList.get(i)); if (i < mCountryList.size() - 1) sb.append(", "); } sb.append("]"); } if (mCapabilities != null) { sb.append("\nCapabilities ("); sb.append(mCapabilities.size()); sb.append(")"); for (int i = 0; i < mCapabilities.size(); i++) { sb.append("\n" + mCapabilities.get(i).toString()); if (i < mCapabilities.size() - 1) { sb.append("\n\t---"); } } } return sb.toString(); } /** {@inheritDoc} */ @Override public int describeContents() { return 1; } /** * Enumeration containing items contained within Identity Parcel. */ private enum MemberData { PLUGIN_ID, NETWORK, NETWORK_URL, ICON_URL, AUTH_TYPE, ICON_MIME, ORDER, NAME; } /** * Read Identity item from Parcel. * * @param in Parcel containing Identity information. */ private void readFromParcel(Parcel in) { mPluginId = null; mNetwork = null; mNetworkUrl = null; mIconUrl = null; mAuthType = null; mIconMime = null; mOrder = null; mName = null; mCapabilities = null; boolean[] validDataList = new boolean[MemberData.values().length]; in.readBooleanArray(validDataList); if (validDataList[MemberData.PLUGIN_ID.ordinal()]) { mPluginId = in.readString(); } if (validDataList[MemberData.NETWORK.ordinal()]) { mNetwork = in.readString(); } if (validDataList[MemberData.NETWORK_URL.ordinal()]) { try { mNetworkUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.NETWORK_URL"); } } if (validDataList[MemberData.ICON_URL.ordinal()]) { try { mIconUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.ICON_URL"); } } if (validDataList[MemberData.AUTH_TYPE.ordinal()]) { mAuthType = in.readString(); } if (validDataList[MemberData.ICON_MIME.ordinal()]) { mIconMime = in.readString(); } if (validDataList[MemberData.ORDER.ordinal()]) { mOrder = in.readInt(); } if (validDataList[MemberData.NAME.ordinal()]) { mName = in.readString(); } int noOfCapabilities = in.readInt(); if (noOfCapabilities > 0) { mCapabilities = new ArrayList<IdentityCapability>(noOfCapabilities); for (int i = 0; i < noOfCapabilities; i++) { IdentityCapability cap = IdentityCapability.CREATOR.createFromParcel(in); mCapabilities.add(cap); } } } /** {@inheritDoc} */ @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 (mPluginId != null) { validDataList[MemberData.PLUGIN_ID.ordinal()] = true; dest.writeString(mPluginId); } if (mNetwork != null) { validDataList[MemberData.NETWORK.ordinal()] = true; dest.writeString(mNetwork); } if (mNetworkUrl != null) { validDataList[MemberData.NETWORK_URL.ordinal()] = true; dest.writeString(mNetworkUrl.toString()); } if (mIconUrl != null) { validDataList[MemberData.ICON_URL.ordinal()] = true; dest.writeString(mIconUrl.toString()); } if (mAuthType != null) { validDataList[MemberData.AUTH_TYPE.ordinal()] = true; dest.writeString(mAuthType); } if (mIconMime != null) { validDataList[MemberData.ICON_MIME.ordinal()] = true; dest.writeString(mIconMime); } if (mOrder != null) { validDataList[MemberData.ORDER.ordinal()] = true; dest.writeInt(mOrder); } if (mName != null) { validDataList[MemberData.NAME.ordinal()] = true; dest.writeString(mName); } if (mCapabilities != null) { dest.writeInt(mCapabilities.size()); for (IdentityCapability cap : mCapabilities) { cap.writeToParcel(dest, 0); } } else { dest.writeInt(0); } int currentPos = dest.dataPosition(); dest.setDataPosition(validDataPos); dest.writeBooleanArray(validDataList); // Real array. dest.setDataPosition(currentPos); } /** Interface to allow Identity to be written and restored from a Parcel. */ public static final Parcelable.Creator<Identity> CREATOR = new Parcelable.Creator<Identity>() { public Identity createFromParcel(Parcel in) { return new Identity(in); } public Identity[] newArray(int size) { return new Identity[size]; } }; } diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 5184272..9344b05 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,810 +1,810 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; 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; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; /** * 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 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. * */ private void handlePushRequest(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: addUiFetchIdentities(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); addUiGetMyIdentities(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * * 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> getMy360AndThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } /** * * 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>(); // checking each identity for its chat capability and adding it to the // list if it does for (int i = 0; i < mMyIdentityList.size(); 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; } } } return chatableIdentities; } private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ // private void addUiGetAvailableIdentities() { // LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to fetch the current user's identities. * */ // private void addUiGetMyIdentities() { // LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * TODO: remove parameter as soon as branch ui-refresh is merged. * * @param data Bundled request data. * */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { - switch (resp.mDataTypes.get(0).type()) { + 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: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case BaseDataType.STATUS_MSG_DATA_TYPE: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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); } } } 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) { // create mobile identity to support 360 chat IdentityCapability iCapability = new IdentityCapability(); iCapability.mCapability = IdentityCapability.CapabilityID.chat; iCapability.mValue = new Boolean(true); ArrayList<IdentityCapability> capabilities = new ArrayList<IdentityCapability>(); capabilities.add(iCapability); Identity mobileIdentity = new Identity(); mobileIdentity.mNetwork = "mobile"; mobileIdentity.mName = "Vodafone"; mobileIdentity.mCapabilities = capabilities; // end: create mobile identity to support 360 chat synchronized (mAvailableIdentityList) { mMyIdentityList.clear(); for (BaseDataType item : data) { mMyIdentityList.add((Identity)item); } mMyIdentityList.add(mobileIdentity); } } 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 handleSetIdentityCapabilityStatus(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); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } /** * * 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(); addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); } } /** * 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, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } }
360/360-Engine-for-Android
16d4945a286fcbf513795c548c81021217df4d52
Codereview changes
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index 7469df3..399cfbd 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,959 +1,962 @@ /* * 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; } } case PHONE_ACCOUNT_TYPE: { 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
360/360-Engine-for-Android
7ece7fbe5759d5539d4242eef6ecb15d2176c1f9
Codereview changes
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java index 6c2d0cf..bdea56d 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java @@ -1,369 +1,374 @@ /* * 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 com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.VersionUtils; import android.content.ContentResolver; import android.content.Context; import android.text.TextUtils; /** * 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"; - protected static final String GOOGLE_ACCOUNT_TYPE_STRING = "com.google"; - /** - * Vendor specific account. Only used in 2.x API. + * Google account, there can be more than one of these */ - protected static Account PHONE_ACCOUNT = null; + 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); /** * 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 vendro 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/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index b09ce7a..7469df3 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,2142 +1,2156 @@ /* * 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 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.LogUtils; -import com.vodafone360.people.utils.CursorUtils; -import com.vodafone360.people.utils.VersionUtils; - -import dalvik.system.PathClassLoader; - 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.Event; -import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Email; -import android.provider.ContactsContract.CommonDataKinds.Organization; +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.Website; -import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; +import android.provider.ContactsContract.CommonDataKinds.Organization; +import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; -import android.provider.ContactsContract.CommonDataKinds.GroupMembership; +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. + * 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; - /** +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 - }; - - /** - * 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 ("; + 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"; + 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+"\""; + 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. + * 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); - } + + /** + * 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!?). + * 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 + * 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; + private boolean mYield = true; + /** * Batch used for Contact Writing operations. */ - private BatchOperation mBatch = new BatchOperation(); - + private BatchOperation mBatch = new BatchOperation(); + /** - * Inner class for applying batches. - * TODO: Move to own class if batches become supported in other areas + * 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 + * + * @param cpo The */ public void add(ContentProviderOperation cpo) { mOperations.add(cpo); } - + /** - * Clears all operations in the batch - * Effectively resets the batch. + * Clears all operations in the batch Effectively resets the batch. */ public void clear() { mOperations.clear(); } - - public ContentProviderResult[] execute() { + + public ContentProviderResult[] execute() { ContentProviderResult[] resultArray = null; - - if(mOperations.size() > 0) { + + 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. + * 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"; - + 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) + * 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 + * 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. + * 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+")"); + LogUtils.logI("NativeContactsApi2.NativeContentObserver.onChange(" + selfChange + ")"); mAbstractedObserver.onChange(); } } - + /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { - LogUtils.logI("NativeContactsApi2.registerObserver()"); + LogUtils.logI("NativeContactsApi2.registerObserver()"); if (mAbstractedObserver != null) { - throw new RuntimeException("Only one observer at a time supported... Please unregister first."); + 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) { + if (mContentObservers[i] != null) { mCr.unregisterContentObserver(mContentObservers[i]); mContentObservers[i] = null; } } } } - + /** * @see NativeContactsApi#initialize() */ @Override protected void initialize() { - PHONE_ACCOUNT = getVendorSpecificAccount(); - } + // 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]; + accounts = new Account[accounts2xApi.length]; for (int i = 0; i < accounts2xApi.length; i++) { - accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); + 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 c = mContext.getContentResolver().query(Settings.CONTENT_URI, PROJECTION, null, - null, null); - String[] values = new String[c.getCount()]; - for (int i = 0; i < values.length; i++) { - c.moveToNext(); + Cursor cursor = mCr.query(Settings.CONTENT_URI, PROJECTION, null, null, null); + // Got no cursor? Return with null! + if (null == cursor) { + return null; + } - if (isVendorSpecificAccount(c.getString(1))) { - return new Account(c.getString(0), c.getString(1)); + 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; } - - c.close(); + CursorUtils.closeCursor(cursor); // nothing found in the settings? try accountmanager Account[] accounts = getAccounts(); 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; } } case PHONE_ACCOUNT_TYPE: { 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)) { + 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); + // TODO: RE-ENABLE SYNC VIA SYSTEM + ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0); + // ContentResolver.setSyncAutomatically(account, + // ContactsContract.AUTHORITY, true); } - } catch(Exception ex) { + } 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 + // 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) - */ + + /** + * @see NativeContactsApi#getContactIds(Account) + */ @Override - public long[] getContactIds(Account account) { + public long[] getContactIds(Account account) { // Need to construct a where clause - if(account != null) { + 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 + @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 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; - } - - /** + 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); + addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI)).withYieldAllowed(mYield) + .withValues(mValues); mBatch.add(builder.build()); - + final int ccListSize = ccList.length; - for(int i = 0 ; i < ccListSize; i++) { + for (int i = 0; i < ccListSize; i++) { final ContactChange cc = ccList[i]; - if(cc != null) { + if (cc != null) { final int key = cc.getKey(); - if(key == ContactChange.KEY_VCARD_ORG && - mMarkedOrganizationIndex < 0) { + if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; - } - if(key == ContactChange.KEY_VCARD_TITLE && - mMarkedTitleIndex < 0) { + } + 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 + + // 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!"); + 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()); + + 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++) { + 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) { + if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; - } - if(key == ContactChange.KEY_VCARD_TITLE && - mMarkedTitleIndex < 0) { + } + if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } - - switch(cc.getType()) { + + 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) { + 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()); + 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) { + 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()); + 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); + 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; + // 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. + * 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, + final Cursor cursor = mCr.query(RawContacts.CONTENT_URI, CONTACTID_PROJECTION, selection, null, null); - - if(cursor == null) { - return 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 + + 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 + * 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, + final Cursor cursor = mCr.query(Groups.CONTENT_URI, GROUPID_PROJECTION, MY_CONTACTS_GROUP_WHERE_CLAUSE, null, null); - - if(cursor == null) { - return; + + if (cursor == null) { + return; } - + try { final int count = cursor.getCount(); - if(count > 0) { + if (count > 0) { mMyContactsGroupRowIds = new long[count]; - for(int i = 0; i < count; i++) { + 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); - + 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++) { + for (int i = 0; i < rowIdCount; i++) { sb.append(mMyContactsGroupRowIds[i]); - if(i < rowIdCount - 1) { + if (i < rowIdCount - 1) { sb.append(','); } } - + sb.append(')'); - final Cursor cursor = mCr.query(dataUri, null, sb.toString(), - null, null); + 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. + * 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 + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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. + */ + 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 + 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); + 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) { + 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) { + 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) { + 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) { + } + + /** + * 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); + 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); + } + } + + /** + * 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(); + } + + /** + * 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)); + 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()) { + } + + // 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); 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 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); - } - - /** + 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); - } - - /** + 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) { + 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); - } - - /** + 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); - + 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.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); - } - - /** + 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); -// } -// } - - + 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) { + int flags = ContactChange.FLAG_NONE; + if (mMarkedOrganizationIndex > -1) { final ContactChange cc = ccList[mMarkedOrganizationIndex]; - flags|= cc.getFlags(); + flags |= cc.getFlags(); final Organisation organization = VCardHelper.getOrg(cc.getValue()); - if(organization != null) { + 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 + 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) { + + if (mMarkedTitleIndex > -1) { final ContactChange cc = ccList[mMarkedTitleIndex]; - flags|= cc.getFlags(); + 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); + + 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 + + /** + * 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) { + 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); + 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()) { + 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) { + 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) { + + 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) { + 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) { + if (organization.unitNames.size() > 0) { department = organization.unitNames.get(0); } } - + flags = cc.getFlags(); } else { // Delete case company = null; department = null; } } - - if(mMarkedTitleIndex >= 0) { + + 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. + 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.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) { + 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. + } 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) + * @return {@link ContactChange} array containing new IDs (may contain some + * null elements) */ private ContactChange[] executeNewContactBatch(ContactChange[] ccList) { - if(mBatch.size() == 0) { + if (mBatch.size() == 0) { // Nothing to execute return null; } final ContentProviderResult[] results = mBatch.execute(); - - if(results == null || results.length == 0) { + + 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) { + + 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], + 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) { + while (resultsIndex < resultsSize) { + if (ccListIndex == mMarkedOrganizationIndex || ccListIndex == mMarkedTitleIndex) { ccListIndex++; continue; } - - if(results[resultsIndex].uri == null) { + + if (results[resultsIndex].uri == null) { throw new RuntimeException("NativeContactsApi2.executeNewContactBatch()" - + "Unexpected null URI for NAB Contact:"+nabContactId); + + "Unexpected null URI for NAB Contact:" + nabContactId); } - - if(resultsIndex == resultsSize - 1 && haveOrganization) { - // for readability we leave Organization/Title for outside the loop - break; + + 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], + 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); + + 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); + idChange.setNabDetailId(nabDetailId); idChangeList[mMarkedOrganizationIndex + 1] = idChange; } - - if(mMarkedTitleIndex > -1) { - final ContactChange idChange = - ContactChange.createIdsChange( - ccList[mMarkedTitleIndex], - ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); + + 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) + * @return {@link ContactChange} array containing new IDs (may contain some + * null elements) */ private ContactChange[] executeUpdateContactBatch(ContactChange[] ccList) { - if(mBatch.size() == 0) { + if (mBatch.size() == 0) { // Nothing to execute return null; } final ContentProviderResult[] results = mBatch.execute(); final int resultsSize = results.length; - if(results == null || resultsSize == 0) { + 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) { + 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 (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; + + 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], + 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) { + + if (haveOrganization) { long nabDetailId = ContactChange.INVALID_ID; - if(mExistingOrganizationId != nabDetailId) { + if (mExistingOrganizationId != nabDetailId) { nabDetailId = mExistingOrganizationId; - } else if (results[resultsIndex].uri != null){ + } 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()); + + "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); + + 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); + + 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 + * + * @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(); + 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. + * 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. + * 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; - } - + 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 + 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; - } - + 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 + 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; - } - + 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) { + if ((flags & ContactChange.FLAG_HOME) == ContactChange.FLAG_HOME) { return StructuredPostal.TYPE_HOME; } - - if((flags & ContactChange.FLAG_WORK) == - ContactChange.FLAG_WORK) { + + 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 + * 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; - } + private static int mapFromNabOrganizationType(int nabType) { + if (nabType == Organization.TYPE_WORK) { + return ContactChange.FLAG_WORK; + } + + return ContactChange.FLAG_NONE; + } - 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) { + 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 + * 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; - } - + 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) { + 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) { + + if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return Website.TYPE_WORK; } - + return Website.TYPE_OTHER; - } + } }
360/360-Engine-for-Android
184aa9f2dd34f869a126fb780cf9af9aa5ff5221
PAND-1553 [Android 2.X] Import Contacts from Phone and Sim accounts
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java index d6448d0..6c2d0cf 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi.java @@ -1,350 +1,369 @@ /* * 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 com.vodafone360.people.utils.LogUtils; +import com.vodafone360.people.utils.VersionUtils; + 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. + * 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 { +public abstract class NativeContactsApi { + /** - * Account type for 360 People in the Native Accounts. MUST be a copy of - * type in 'res/xml/authenticator.xml' + * 360 client account type. */ - protected static final String PEOPLE_ACCOUNT_TYPE = "com.vodafone360.people.android.account"; + protected static final int PEOPLE_ACCOUNT_TYPE = 1; /** - * {@link NativeContactsApi} the singleton instance providing access to the - * correct Contacts API interface + * Google account type. */ - private static NativeContactsApi sInstance; + 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"; + + protected static final String GOOGLE_ACCOUNT_TYPE_STRING = "com.google"; + + /** + * Vendor specific account. Only used in 2.x API. + */ + protected static Account PHONE_ACCOUNT = null; + + /** + * 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 + * 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 - */ + * 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 + * 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() - * + * 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() + * @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()) { + 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); + 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() - * + * Destroy NativeContactsApi singleton instance if created. + * The instance can be recreated by calling createInstance() * @see NativeContactsApi#createInstance() */ public static void destroyInstance() { - if (sInstance != null) { + 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() " + 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. + * 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. + * 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); + return TextUtils.equals(mType, PEOPLE_ACCOUNT_TYPE_STRING); } - + /** * Returns a String representation of the account. */ public String toString() { - return "Account: name=" + mName + ", type=" + mType; + return "Account: name="+mName+", type="+mType; } } - + /** - * The Observer interface to receive notifications about changes in the - * native address book. + * 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. + * 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. + * This method effectively acts as a replacement for the constructor + * because of the use of reflection. */ - protected abstract void initialize(); - + protected abstract void initialize(); + /** - * Registers a content observer. Note: the method only supports one observer - * at a time. + * 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 + * @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. + * 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 + * @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. - * + * 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 + * @return An array containing all the Accounts of the provided Type, or null if none exist */ - public abstract Account[] getAccountsByType(String type); - + 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. - * + * 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. - * + * 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. + * 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. - * + * 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 + * @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. + * 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. - * + * 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 + * @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); - + /** - * Checks whether or not a {@link ContactChange} key is supported. Results - * may vary in 1.X and 2.X - * + * 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); + + 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 a7b790b..78c843d 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java @@ -1,686 +1,686 @@ /* * 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(String type) { + 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#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); } } } diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index e00d1a6..b09ce7a 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,2078 +1,2142 @@ /* * 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 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.LogUtils; +import com.vodafone360.people.utils.CursorUtils; +import com.vodafone360.people.utils.VersionUtils; + +import dalvik.system.PathClassLoader; + 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.Phone; +import android.provider.ContactsContract.CommonDataKinds.Email; +import android.provider.ContactsContract.CommonDataKinds.Organization; 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.provider.ContactsContract.CommonDataKinds.StructuredPostal; +import android.provider.ContactsContract.CommonDataKinds.StructuredName; +import android.provider.ContactsContract.CommonDataKinds.GroupMembership; 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. + * 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; - - /** +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 - }; - - /** - * 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 ("; - + private static final int CONTACTID_PROJECTION_ACCOUNT_TYPE = 1; + /** + * Group ID Projection + */ + private static final String[] GROUPID_PROJECTION = new String[] { + Groups._ID + }; + + /** + * 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"; - + 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 + "\""; - + 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. + * 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); - } - + /** + * 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!?). + * 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 + * 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; - + private boolean mYield = true; /** * Batch used for Contact Writing operations. */ - private BatchOperation mBatch = new BatchOperation(); - + private BatchOperation mBatch = new BatchOperation(); + /** - * Inner class for applying batches. TODO: Move to own class if batches - * become supported in other areas + * 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 + * @param cpo The */ public void add(ContentProviderOperation cpo) { mOperations.add(cpo); } - + /** - * Clears all operations in the batch Effectively resets the batch. + * Clears all operations in the batch + * Effectively resets the batch. */ public void clear() { mOperations.clear(); } - - public ContentProviderResult[] execute() { + + public ContentProviderResult[] execute() { ContentProviderResult[] resultArray = null; - - if (mOperations.size() > 0) { + + 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. + * 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"; - + 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) + * 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 + * 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. + * 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 + ")"); + LogUtils.logI("NativeContactsApi2.NativeContentObserver.onChange("+selfChange+")"); mAbstractedObserver.onChange(); } } - + /** * @see NativeContactsApi#registerObserver(ContactsObserver) */ @Override public void registerObserver(ContactsObserver observer) { - LogUtils.logI("NativeContactsApi2.registerObserver()"); + LogUtils.logI("NativeContactsApi2.registerObserver()"); if (mAbstractedObserver != null) { - throw new RuntimeException( - "Only one observer at a time supported... Please unregister first."); + 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) { + 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]; + accounts = new Account[accounts2xApi.length]; for (int i = 0; i < accounts2xApi.length; i++) { - accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); + accounts[i] = new Account(accounts2xApi[i].name, accounts2xApi[i].type); } } return accounts; } + 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 c = mContext.getContentResolver().query(Settings.CONTENT_URI, PROJECTION, null, + null, null); + String[] values = new String[c.getCount()]; + for (int i = 0; i < values.length; i++) { + c.moveToNext(); + + if (isVendorSpecificAccount(c.getString(1))) { + return new Account(c.getString(0), c.getString(1)); + } + } + + c.close(); + + // nothing found in the settings? try accountmanager + Account[] accounts = getAccounts(); + for (Account account : accounts) { + if (isVendorSpecificAccount(account.getType())) { + return account; + } + + } + return null; + } + /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override - public Account[] getAccountsByType(String type) { - AccountManager accountMan = AccountManager.get(mContext); - android.accounts.Account[] accounts2xApi = accountMan.getAccountsByType(type); - 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); + public Account[] getAccountsByType(int type) { + switch (type) { + case PEOPLE_ACCOUNT_TYPE: + case GOOGLE_ACCOUNT_TYPE: { + AccountManager accountMan = AccountManager.get(mContext); + android.accounts.Account[] accounts2xApi = null; + if (PEOPLE_ACCOUNT_TYPE == type) { + accounts2xApi = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE_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; + } + } + case PHONE_ACCOUNT_TYPE: { + return new Account[] { + PHONE_ACCOUNT + }; } - return accounts; + default: + return null; } - 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); + PEOPLE_ACCOUNT_TYPE_STRING); AccountManager accountMan = AccountManager.get(mContext); isAdded = accountMan.addAccountExplicitly(account, null, null); - if (isAdded) { - if (VersionUtils.isHtcSenseDevice(mContext)) { + 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); + // TODO: RE-ENABLE SYNC VIA SYSTEM + ContentResolver.setIsSyncable(account, + ContactsContract.AUTHORITY, 0); + // ContentResolver.setSyncAutomatically(account, + // ContactsContract.AUTHORITY, true); } - } catch (Exception ex) { + } 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); + 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); + 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) - */ + + /** + * @see NativeContactsApi#getContactIds(Account) + */ @Override - public long[] getContactIds(Account account) { + public long[] getContactIds(Account account) { // Need to construct a where clause - if (account != null) { + 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 + @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 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; - } - - /** + 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); + addCallerIsSyncAdapterParameter(RawContacts.CONTENT_URI)).withYieldAllowed(mYield).withValues(mValues); mBatch.add(builder.build()); - + final int ccListSize = ccList.length; - for (int i = 0; i < ccListSize; i++) { + for(int i = 0 ; i < ccListSize; i++) { final ContactChange cc = ccList[i]; - if (cc != null) { + if(cc != null) { final int key = cc.getKey(); - if (key == ContactChange.KEY_VCARD_ORG && mMarkedOrganizationIndex < 0) { + if(key == ContactChange.KEY_VCARD_ORG && + mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; - } - if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { + } + 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 + + // 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!"); + 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()); + + 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++) { + 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) { + if(key == ContactChange.KEY_VCARD_ORG && + mMarkedOrganizationIndex < 0) { // Mark for later writing mMarkedOrganizationIndex = i; continue; - } - if (key == ContactChange.KEY_VCARD_TITLE && mMarkedTitleIndex < 0) { + } + if(key == ContactChange.KEY_VCARD_TITLE && + mMarkedTitleIndex < 0) { // Mark for later writing mMarkedTitleIndex = i; continue; } - - switch (cc.getType()) { + + 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) { + 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()); + 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) { + 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()); + 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); + 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; + // 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. - * + * 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, + final Cursor cursor = mCr.query( + RawContacts.CONTENT_URI, + CONTACTID_PROJECTION, + selection, null, null); - - if (cursor == null) { - return 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) + || 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 + + 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 + * 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, + final Cursor cursor = mCr.query(Groups.CONTENT_URI, GROUPID_PROJECTION, MY_CONTACTS_GROUP_WHERE_CLAUSE, null, null); - - if (cursor == null) { - return; + + if(cursor == null) { + return; } - + try { final int count = cursor.getCount(); - if (count > 0) { + if(count > 0) { mMyContactsGroupRowIds = new long[count]; - for (int i = 0; i < count; i++) { + 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); - + 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++) { + for(int i = 0; i < rowIdCount; i++) { sb.append(mMyContactsGroupRowIds[i]); - if (i < rowIdCount - 1) { + if(i < rowIdCount - 1) { sb.append(','); } } - + sb.append(')'); - final Cursor cursor = mCr.query(dataUri, null, sb.toString(), null, null); + 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. - * + * 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 + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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. + */ + 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 - * + 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); + 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) { + 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) { + 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) { + 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) { + } + + /** + * 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); + 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); + } + } + + /** + * 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(); + } + + /** + * 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)); + 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 + "=?"; - // } + } + +// 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()) { +// 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); 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 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); - } - - /** + 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); - } - - /** + 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) { + 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); - } - - /** + 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); - + 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.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); - } - - /** + 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; - // } + 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 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) { + int flags = ContactChange.FLAG_NONE; + if(mMarkedOrganizationIndex > -1) { final ContactChange cc = ccList[mMarkedOrganizationIndex]; - flags |= cc.getFlags(); + flags|= cc.getFlags(); final Organisation organization = VCardHelper.getOrg(cc.getValue()); - if (organization != null) { + 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 + 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) { + + if(mMarkedTitleIndex > -1) { final ContactChange cc = ccList[mMarkedTitleIndex]; - flags |= cc.getFlags(); + 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); + + 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 + + /** + * 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) { + 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); + 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()) { + 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) { + 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) { + + 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) { + 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) { + if(organization.unitNames.size() > 0) { department = organization.unitNames.get(0); } } - + flags = cc.getFlags(); } else { // Delete case company = null; department = null; } } - - if (mMarkedTitleIndex >= 0) { + + 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. + 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.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) { + 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. + } 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) + * @return {@link ContactChange} array containing new IDs (may contain some null elements) */ private ContactChange[] executeNewContactBatch(ContactChange[] ccList) { - if (mBatch.size() == 0) { + if(mBatch.size() == 0) { // Nothing to execute return null; } final ContentProviderResult[] results = mBatch.execute(); - - if (results == null || results.length == 0) { + + 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) { + + 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], + 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) { + while(resultsIndex < resultsSize) { + if(ccListIndex == mMarkedOrganizationIndex || + ccListIndex == mMarkedTitleIndex) { ccListIndex++; continue; } - - if (results[resultsIndex].uri == null) { + + if(results[resultsIndex].uri == null) { throw new RuntimeException("NativeContactsApi2.executeNewContactBatch()" - + "Unexpected null URI for NAB Contact:" + nabContactId); + + "Unexpected null URI for NAB Contact:"+nabContactId); } - - if (resultsIndex == resultsSize - 1 && haveOrganization) { - // for readability we leave Organization/Title for outside the - // loop - break; + + 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], + 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); + + 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); + idChange.setNabDetailId(nabDetailId); idChangeList[mMarkedOrganizationIndex + 1] = idChange; } - - if (mMarkedTitleIndex > -1) { - final ContactChange idChange = ContactChange.createIdsChange( - ccList[mMarkedTitleIndex], ContactChange.TYPE_UPDATE_NAB_DETAIL_ID); + + 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) + * @return {@link ContactChange} array containing new IDs (may contain some null elements) */ private ContactChange[] executeUpdateContactBatch(ContactChange[] ccList) { - if (mBatch.size() == 0) { + if(mBatch.size() == 0) { // Nothing to execute return null; } final ContentProviderResult[] results = mBatch.execute(); final int resultsSize = results.length; - if (results == null || resultsSize == 0) { + 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) { + 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(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; + + 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], + 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) { + + if(haveOrganization) { long nabDetailId = ContactChange.INVALID_ID; - if (mExistingOrganizationId != nabDetailId) { + if(mExistingOrganizationId != nabDetailId) { nabDetailId = mExistingOrganizationId; - } else if (results[resultsIndex].uri != null) { + } 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()); + + "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); + + 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); + + 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 + * @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(); + 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. - * + * 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); + 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. - * + * 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; - } - + 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 - * + 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; - } - + 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 - * + 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; - } - + 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) { + if((flags & ContactChange.FLAG_HOME) == + ContactChange.FLAG_HOME) { return StructuredPostal.TYPE_HOME; } - - if ((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { + + 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 - * + * 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; - } + 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) { + 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 - * + * 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; - } - + 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) { + 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) { + + if((flags & ContactChange.FLAG_WORK) == + ContactChange.FLAG_WORK) { return Website.TYPE_WORK; } - + return Website.TYPE_OTHER; - } + } } diff --git a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java index 773eb9f..06f4b12 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeImporter.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeImporter.java @@ -1,934 +1,904 @@ /* * 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.Arrays; -import java.util.Comparator; - +import java.util.ArrayList; 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; +import java.util.Arrays; +import java.util.Comparator; + /** - * 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...) + * 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 { - /** - * - */ - private final String GOOGLE_ACCOUNT_TYPE = "com.google"; - + /** * 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. + * 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. + * 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). + * 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). + * 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. + * 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. + * 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. + * 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 + * @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 - final String accountType = firstTimeImport ? GOOGLE_ACCOUNT_TYPE - : NativeContactsApi.PEOPLE_ACCOUNT_TYPE; - - mAccounts = mNativeContactsApi.getAccountsByType(accountType); + if (firstTimeImport) { + ArrayList<Account> accountList = new ArrayList<Account>(); + for (Account account : mNativeContactsApi + .getAccountsByType(NativeContactsApi.GOOGLE_ACCOUNT_TYPE)) { + accountList.add(account); + } + for (Account account : mNativeContactsApi + .getAccountsByType(NativeContactsApi.PHONE_ACCOUNT_TYPE)) { + 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. + * 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) { + 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. + * 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) { - + // 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]); + 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]); + + 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 + // 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 + + // 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) + + 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"); + && (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]) { + || mPeopleNativeContactsIds[mCurrentPeopleId] > mNativeContactsIds[mCurrentNativeId]) { // has to be a new contact LogUtils.logD("NativeImporter.iterateThroughNativeIds(): found a new contact"); addNewContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; - } else { + } + else { // has to be an existing contact or one that will be deleted - LogUtils - .logD("NativeImporter.iterateThroughNativeIds(): check existing contact"); + LogUtils.logD("NativeImporter.iterateThroughNativeIds(): check existing contact"); checkExistingContact(mNativeContactsIds[mCurrentNativeId]); mProcessedIds++; mCurrentPeopleId++; } } - + mCurrentNativeId++; } - - // check if we are done with ids list from native + + // 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 + + // 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"); + 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 { + } + 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); - + + 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()); + // 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 + + // 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 + + // 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); + LogUtils.logE("NativeImporter.addNewContact() - failed to import native contact id=" + nativeId); } } } - + /** - * Check changes between an existing contact on both native and people - * database. + * 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 + + 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. + * 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. + // 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. + * 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)) { - + + 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. + * Computes the difference between the provided arrays of ContactChange. * - * @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 + * 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 + + // 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]; + 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)) { - + + 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 + && (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 + + 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)) { + 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]; + && (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) { - + } 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. + * 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; - + + 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. - * + * 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; - + 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. + * 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. + * 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 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) { - + 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) { - + + 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 + + // 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()); - + 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); - + 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); + 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 + * 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 + * @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) { - + + 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"); + 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()); - + 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"); + + 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"); + 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 + * 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()); - + + 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()); - + + // 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
8c772cf0c449d38b280848607494d097e25b6c37
- changed ui accessors in IdentityEngine - added different types to Identity to be able to distinguish between GetAvailableIdentities and GetMyIdentities - HessianDecoder now distinguishes between GetAvailableIdentities and GetMyIdentities, too
diff --git a/src/com/vodafone360/people/datatypes/Identity.java b/src/com/vodafone360/people/datatypes/Identity.java index 8d288b2..28d8446 100644 --- a/src/com/vodafone360/people/datatypes/Identity.java +++ b/src/com/vodafone360/people/datatypes/Identity.java @@ -1,605 +1,609 @@ /* * 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.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Vector; import android.os.Parcel; import android.os.Parcelable; import com.vodafone360.people.utils.LogUtils; /** * BaseDataType encapsulating an Identity issued to or retrieved from server */ public class Identity extends BaseDataType implements Parcelable { /** * Tags associated with Identity item. */ private enum Tags { IDENTITY_MAIN_TAG("availableidentity"), IDENTITY_CAPABILITY_LIST("identitycapabilitylist"), PLUGIN_ID("pluginid"), NETWORK_URL("networkurl"), AUTH_TYPE("authtype"), ICON_MIME("iconmime"), ICON2_MIME("icon2mime"), ORDER("order"), NAME("name"), ICON_URL("iconurl"), ICON2_URL("icon2url"), NETWORK("network"), // Properties below are only present after // GetMyIdentities. ACTIVE("active"), CREATED("created"), IDENTITY_ID("identityid"), UPDATED("updated"), IDENTITY_TYPE("identitytype"), USER_ID("userid"), USER_NAME("username"), DISPLAY_NAME("displayname"), COUNTRY_LIST("countrylist"); private final String tag; /** * Construct Tags item from supplied String * * @param s String value for Tags item. */ private Tags(String s) { tag = s; } /** * String value for 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 in Tags items. * @return Tags item for specified String, NULL otherwise. */ private static Tags findTag(String tag) { for (Tags tags : Tags.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } return null; } } public String mPluginId = null; public String mNetwork = null; public URL mNetworkUrl = null; public URL mIconUrl = null; public URL mIcon2Url = null; public String mAuthType; public String mIconMime = null; public Integer mOrder = null; public String mName = null; public List<IdentityCapability> mCapabilities = null; /** Properties below are only present after GetMyIdentities. */ public Boolean mActive = null; public Long mCreated = null; public Long mUpdated = null; public String mIdentityId = null; public Integer mUserId = null; public String mUserName = null; public String mDisplayName = null; public List<String> mCountryList = null; public String mIdentityType = null; + + private int mType; /** * Comparator class used to compare Identities retrieved from server to * remove duplicates from list passed to People client UI. */ public static class IdentityComparator implements Comparator<Identity> { @Override public int compare(Identity object1, Identity object2) { return object1.mOrder.compareTo(object2.mOrder); } } /** * Test whether current Identity is identical to supplied Identity. * * @param id Identity to compare against. * @return true if Identities match, false otherwise. */ public boolean isSameAs(Identity id) { boolean isSame = true; if (!areStringValuesSame(mPluginId, id.mPluginId) || !areStringValuesSame(mNetwork, id.mNetwork) || !areStringValuesSame(mIdentityId, id.mIdentityId) || !areStringValuesSame(mDisplayName, id.mDisplayName)) { isSame = false; } if (mNetworkUrl != null && id.mNetworkUrl != null) { if (!mNetworkUrl.sameFile(id.mNetworkUrl)) { isSame = false; } } else if (mNetworkUrl == null && id.mNetworkUrl == null) { // Do nothing. } else { isSame = false; } if (mIconUrl != null && id.mIconUrl != null) { if (!mIconUrl.sameFile(id.mIconUrl)) { isSame = false; } } else if (mIconUrl == null && id.mIconUrl == null) { // Do nothing. } else { isSame = false; } return isSame; } /** * String values comparison * * @param s1 First String to test. * @param s2 Second String to test. * @return true if Strings match (or both are null), false otherwise. */ private boolean areStringValuesSame(String s1, String s2) { boolean isSame = true; if (s1 == null && s2 == null) { // Do nothing. } else if (s1 != null && s2 != null) { if (s1.compareTo(s2) != 0) { isSame = false; } } else { isSame = false; } return isSame; } /** * Default constructor. */ public Identity() { // Do nothing. } + + public Identity(int type) { + mType = type; + } /** * Create Identity from Parcel. * * @param in Parcel containing Identity. */ private Identity(Parcel in) { readFromParcel(in); } /** {@inheritDoc} */ @Override public int type() { - // TODO: Return appropriate type if its - // an available identity instead of my identity - return MY_IDENTITY_DATA_TYPE; + return mType; } /** * Populate Identity from supplied Hashtable. * * @param hash Hashtable containing identity details. * @return Identity instance. */ public Identity createFromHashtable(Hashtable<String, Object> hash) { Enumeration<String> e = hash.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); Object value = hash.get(key); Tags tag = Tags.findTag(key); if (tag != null) setValue(tag, value); } 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 val) { switch (tag) { case AUTH_TYPE: mAuthType = (String)val; break; case ICON_MIME: mIconMime = (String)val; break; case ICON2_MIME: // TODO: Remove TAG value? // mIcon2Mime = (String)val; break; case ICON_URL: try { mIconUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIconUrl = null; } break; case ICON2_URL: try { mIcon2Url = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIcon2Url = null; } break; case IDENTITY_CAPABILITY_LIST: /** Create id capability list. */ @SuppressWarnings("unchecked") Vector<Hashtable<String, Object>> v = (Vector<Hashtable<String, Object>>)val; if (mCapabilities == null) { mCapabilities = new ArrayList<IdentityCapability>(); } for (Hashtable<String, Object> obj : v) { IdentityCapability cap = new IdentityCapability(); cap.createFromHashtable(obj); mCapabilities.add(cap); } break; case IDENTITY_MAIN_TAG: // Not currently handled. break; case NAME: mName = (String)val; break; case NETWORK: mNetwork = (String)val; break; case NETWORK_URL: try { mNetworkUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong network url: '" + val + "'"); mNetworkUrl = null; } break; case ORDER: mOrder = (Integer)val; break; case PLUGIN_ID: mPluginId = (String)val; break; case ACTIVE: mActive = (Boolean)val; break; case CREATED: mCreated = (Long)val; break; case DISPLAY_NAME: mDisplayName = (String)val; break; case IDENTITY_ID: mIdentityId = (String)val; break; case IDENTITY_TYPE: mIdentityType = (String)val; break; case UPDATED: mUpdated = (Long)val; break; case USER_ID: mUserId = ((Long)val).intValue(); break; case USER_NAME: mUserName = (String)val; break; case COUNTRY_LIST: if (mCountryList == null) { mCountryList = new ArrayList<String>(); } break; default: // Do nothing. break; } } /** {@inheritDoc} */ @Override public String toString() { StringBuffer ret = new StringBuffer(); ret.append("Name: " + mName); ret.append("\nPluginID: " + mPluginId); ret.append("\nNetwork: " + mNetwork); ret.append("\nNetworkURL: " + mNetworkUrl); ret.append("\nAuthType: " + mAuthType); ret.append("\nIcon mime: " + mIconMime); ret.append("\nIconURL: " + mIconUrl); ret.append("\nOrder: " + mOrder); ret.append("\nActive: " + mActive); ret.append("\nCreated: " + mCreated); ret.append("\nUpdated: " + mUpdated); ret.append("\nIdentityId: " + mIdentityId); ret.append("\nUserId: " + mUserId); ret.append("\nUserName: " + mUserName); ret.append("\nDisplayName: " + mDisplayName); ret.append("\nIdentityType: " + mIdentityType); if (mCountryList != null) { ret.append("\nCountry List: (" + mCountryList.size() + ") = ["); for (int i = 0; i < mCountryList.size(); i++) { ret.append(mCountryList.get(i)); if (i < mCountryList.size() - 1) ret.append(", "); } ret.append("]"); } if (mCapabilities != null) { ret.append("\nCapabilities (" + mCapabilities.size() + ")"); for (int i = 0; i < mCapabilities.size(); i++) { ret.append("\n" + mCapabilities.get(i).toString()); if (i < mCapabilities.size() - 1) { ret.append("\n\t---"); } } } return ret.toString(); } /** {@inheritDoc} */ @Override public int describeContents() { return 1; } /** * Enumeration containing items contained within Identity Parcel. */ private enum MemberData { PLUGIN_ID, NETWORK, NETWORK_URL, ICON_URL, AUTH_TYPE, ICON_MIME, ORDER, NAME; } /** * Read Identity item from Parcel. * * @param in Parcel containing Identity information. */ private void readFromParcel(Parcel in) { mPluginId = null; mNetwork = null; mNetworkUrl = null; mIconUrl = null; mAuthType = null; mIconMime = null; mOrder = null; mName = null; mCapabilities = null; boolean[] validDataList = new boolean[MemberData.values().length]; in.readBooleanArray(validDataList); if (validDataList[MemberData.PLUGIN_ID.ordinal()]) { mPluginId = in.readString(); } if (validDataList[MemberData.NETWORK.ordinal()]) { mNetwork = in.readString(); } if (validDataList[MemberData.NETWORK_URL.ordinal()]) { try { mNetworkUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.NETWORK_URL"); } } if (validDataList[MemberData.ICON_URL.ordinal()]) { try { mIconUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.ICON_URL"); } } if (validDataList[MemberData.AUTH_TYPE.ordinal()]) { mAuthType = in.readString(); } if (validDataList[MemberData.ICON_MIME.ordinal()]) { mIconMime = in.readString(); } if (validDataList[MemberData.ORDER.ordinal()]) { mOrder = in.readInt(); } if (validDataList[MemberData.NAME.ordinal()]) { mName = in.readString(); } int noOfCapabilities = in.readInt(); if (noOfCapabilities > 0) { mCapabilities = new ArrayList<IdentityCapability>(noOfCapabilities); for (int i = 0; i < noOfCapabilities; i++) { IdentityCapability cap = IdentityCapability.CREATOR.createFromParcel(in); mCapabilities.add(cap); } } } /** {@inheritDoc} */ @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 (mPluginId != null) { validDataList[MemberData.PLUGIN_ID.ordinal()] = true; dest.writeString(mPluginId); } if (mNetwork != null) { validDataList[MemberData.NETWORK.ordinal()] = true; dest.writeString(mNetwork); } if (mNetworkUrl != null) { validDataList[MemberData.NETWORK_URL.ordinal()] = true; dest.writeString(mNetworkUrl.toString()); } if (mIconUrl != null) { validDataList[MemberData.ICON_URL.ordinal()] = true; dest.writeString(mIconUrl.toString()); } if (mAuthType != null) { validDataList[MemberData.AUTH_TYPE.ordinal()] = true; dest.writeString(mAuthType); } if (mIconMime != null) { validDataList[MemberData.ICON_MIME.ordinal()] = true; dest.writeString(mIconMime); } if (mOrder != null) { validDataList[MemberData.ORDER.ordinal()] = true; dest.writeInt(mOrder); } if (mName != null) { validDataList[MemberData.NAME.ordinal()] = true; dest.writeString(mName); } if (mCapabilities != null) { dest.writeInt(mCapabilities.size()); for (IdentityCapability cap : mCapabilities) { cap.writeToParcel(dest, 0); } } else { dest.writeInt(0); } int currentPos = dest.dataPosition(); dest.setDataPosition(validDataPos); dest.writeBooleanArray(validDataList); // Real array. dest.setDataPosition(currentPos); } /** Interface to allow Identity to be written and restored from a Parcel. */ public static final Parcelable.Creator<Identity> CREATOR = new Parcelable.Creator<Identity>() { public Identity createFromParcel(Parcel in) { return new Identity(in); } public Identity[] newArray(int size) { return new Identity[size]; } }; } diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 968b3fe..f83c098 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,741 +1,810 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; 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; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; - private static final String KEY_DATA_CHATABLE_IDENTITIES = "chatable_data"; - /** * 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 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. * */ private void handlePushRequest(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: addUiFetchIdentities(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); addUiGetMyIdentities(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * - * Gets all third party identities and adds the mobile and pc identities + * 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 identities pc and mobile. If the retrieval failed the list will + * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } + /** + * + * 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>(); + + // checking each identity for its chat capability and adding it to the + // list if it does + for (int i = 0; i < mMyIdentityList.size(); 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; + } + } + } + + return chatableIdentities; + } + private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ // private void addUiGetAvailableIdentities() { // LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to fetch the current user's identities. * */ // private void addUiGetMyIdentities() { // LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * TODO: remove parameter as soon as branch ui-refresh is merged. * * @param data Bundled request data. * */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { - switch (mState) { - case IDLE: - LogUtils.logW("IDLE should never happend"); - break; - case FETCHING_IDENTITIES: - case GETTING_MY_IDENTITIES: - case GETTING_MY_CHATABLE_IDENTITIES: - handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); - break; - case SETTING_IDENTITY_CAPABILITY_STATUS: - handleSetIdentityCapabilityStatus(resp.mDataTypes); - break; - case VALIDATING_IDENTITY_CREDENTIALS: - handleValidateIdentityCredentials(resp.mDataTypes); - break; + switch (resp.mDataTypes.get(0).type()) { + 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: + handleSetIdentityCapabilityStatus(resp.mDataTypes); + break; + case BaseDataType.STATUS_MSG_DATA_TYPE: + handleValidateIdentityCredentials(resp.mDataTypes); + break; default: - LogUtils.logW("default should never happend"); + LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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: - addUiGetAvailableIdentities(); + sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: - // TODO padma + 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 handleServerGetAvailableIdentitiesResponse(List<BaseDataType> data) { - Bundle bu = null; + private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); + if (errorStatus == ServiceStatus.SUCCESS) { - mAvailableIdentityList.clear(); - for (BaseDataType item : data) { - if (item.type() == BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE) { - mAvailableIdentityList.add((Identity)item); - } else { - completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); - return; - } - } - bu = new Bundle(); - if (mState == State.GETTING_MY_IDENTITIES - || (mState == State.GETTING_MY_CHATABLE_IDENTITIES)) { - // store local copy of my identities - makeChatableIdentitiesCache(mAvailableIdentityList); - bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); - } - bu.putParcelableArrayList(KEY_DATA, mAvailableIdentityList); + synchronized (mAvailableIdentityList) { + mAvailableIdentityList.clear(); + + for (BaseDataType item : data) { + mAvailableIdentityList.add((Identity)item); + } + } } - LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse completw UI req"); - completeUiRequest(errorStatus, bu); - newState(State.IDLE); + + 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) { + // create mobile identity to support 360 chat + IdentityCapability iCapability = new IdentityCapability(); + iCapability.mCapability = IdentityCapability.CapabilityID.chat; + iCapability.mValue = new Boolean(true); + ArrayList<IdentityCapability> capabilities = + new ArrayList<IdentityCapability>(); + capabilities.add(iCapability); + + Identity mobileIdentity = new Identity(); + mobileIdentity.mNetwork = "mobile"; + mobileIdentity.mName = "Vodafone"; + mobileIdentity.mCapabilities = capabilities; + // end: create mobile identity to support 360 chat + + synchronized (mAvailableIdentityList) { + mMyIdentityList.clear(); + + for (BaseDataType item : data) { + mMyIdentityList.add((Identity)item); + } + mMyIdentityList.add(mobileIdentity); + } + } + + 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.type() == 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 handleSetIdentityCapabilityStatus(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.type() == 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); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } /** * * 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(); addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); } } /** * 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, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } } diff --git a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java index 9e1d42a..7d58677 100644 --- a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java +++ b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java @@ -1,495 +1,498 @@ /* * 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.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 data byte array containing Hessian encoded data * @param type Event type * @return List of BaseDataType items parsed from Hessian data * @throws IOException */ public List<BaseDataType> decodeHessianByteArray(byte[] data, Request.Type type, boolean isZipped) 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); } List<BaseDataType> mBaseDataTypeList = null; mMicroHessianInput.init(is); LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); try { mBaseDataTypeList = decodeResponse(is, type); } catch (IOException e) { LogUtils.logE("HessianDecoder.decodeHessianByteArray() " + "IOException during decodeResponse", e); } CloseUtils.close(bis); CloseUtils.close(is); return mBaseDataTypeList; } @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; } } /** * TODO: we cast every response to a Map, losing e.g. push event "c0" which * only contains a string - to fix * * @param is * @param type * @return * @throws IOException */ @SuppressWarnings("unchecked") private List<BaseDataType> decodeResponse(InputStream is, Request.Type type) throws IOException { boolean usesReplyTag = false; List<BaseDataType> mResultList = 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(); zybErr.errorType = mMicroHessianInput.readFault().errString(); mResultList.add(zybErr); return mResultList; } // 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(mResultList, is, tag); return mResultList; } // 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); decodeResponseByRequestType(mResultList, hash, type); } else { // if we have a common request 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); mResultList.add(auth.createFromHashtable(authHash)); } else if (map.containsKey(KEY_CONTACT_LIST)) { // contact list getContacts(mResultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); } 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) { mResultList.add(UserProfile.createFromHashtable(obj)); } } else if (map.containsKey(KEY_USER_PROFILE)) { Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map .get(KEY_USER_PROFILE); mResultList.add(UserProfile.createFromHashtable(userProfileHash)); } else if ((map.containsKey(KEY_IDENTITY_LIST)) || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { + int mType = 0; Vector<Hashtable<String, Object>> idcap = null; if (map.containsKey(KEY_IDENTITY_LIST)) { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); + mType = BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE; } else { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); + mType = BaseDataType.MY_IDENTITY_DATA_TYPE; } for (Hashtable<String, Object> obj : idcap) { - Identity id = new Identity(); + Identity id = new Identity(mType); mResultList.add(id.createFromHashtable(obj)); } } 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) { mResultList.add(ActivityItem.createFromHashtable(obj)); } } } if (usesReplyTag) { is.read(); // read the last 'z' } return mResultList; } 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); } private void decodeResponseByRequestType(List<BaseDataType> clist, Hashtable<String, Object> hash, Request.Type type) { switch (type) { case CONTACT_CHANGES_OR_UPDATES: // create ContactChanges ContactChanges contChanges = new ContactChanges(); contChanges = contChanges.createFromHashtable(hash); clist.add(contChanges); break; case ADD_CONTACT: case SIGN_UP: clist.add(Contact.createFromHashtable(hash)); break; case RETRIEVE_PUBLIC_KEY: // AA define new object type clist.add(PublicKeyDetails.createFromHashtable(hash)); break; case FRIENDSHIP_REQUEST: 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); break; case CONTACT_DETAIL_DELETE: ContactDetailDeletion cdel = new ContactDetailDeletion(); clist.add(cdel.createFromHashtable(hash)); break; case USER_INVITATION: // Not currently supported. break; case CONTACT_GROUP_RELATION_LIST: ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); groupRelationList.populateFromHashtable(hash); clist.add(groupRelationList); break; case CONTACT_GROUP_RELATIONS: ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); groupRelationsList.populateFromHashtable(hash); clist.add(groupRelationsList); break; case GROUP_LIST: ItemList zyblist = new ItemList(ItemList.Type.group_privacy); zyblist.populateFromHashtable(hash); clist.add(zyblist); break; case ITEM_LIST_OF_LONGS: ItemList listOfLongs = new ItemList(ItemList.Type.long_value); listOfLongs.populateFromHashtable(hash); clist.add(listOfLongs); break; case STATUS_LIST: ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); zybstatlist.populateFromHashtable(hash); clist.add(zybstatlist); 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); } break; case EXPECTING_STATUS_ONLY: StatusMsg statMsg = new StatusMsg(); clist.add(statMsg.createFromHashtable(hash)); break; case STATUS: StatusMsg s = new StatusMsg(); s.mStatus = true; clist.add(s); break; case PRESENCE_LIST: PresenceList mPresenceList = new PresenceList(); mPresenceList.createFromHashtable(hash); clist.add(mPresenceList); break; case PUSH_MSG: // parse content of RPG Push msg parsePushMessage(clist, hash); break; case CREATE_CONVERSATION: Conversation mConversation = new Conversation(); mConversation.createFromHashtable(hash); clist.add(mConversation); break; default: LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" + type.name() + "]"); } } 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
65a865ef146fbacae7d9901577843835a97cdedd
added new requests to IdentityEngine to replace the traditional ui requests
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 33f50df..968b3fe 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,715 +1,741 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; + private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ - private final ArrayList<Identity> mAvailableIdentityList = new ArrayList<Identity>(); + private ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ - private final ArrayList<Identity> mMyIdentityList = new ArrayList<Identity>(); + private ArrayList<Identity> mMyIdentityList; /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; private static final String KEY_DATA_CHATABLE_IDENTITIES = "chatable_data"; /** * 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 the user is currently signed up for. * - * @return A list of 3rd party identities the user is signed in to or null - * if there was something wrong retrieving the identities. + * @return A list of 3rd party identities the user is signed in to or an + * empty list if something went wrong retrieving the identities. * */ private void handlePushRequest(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: addUiFetchIdentities(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); addUiGetMyIdentities(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * * Gets all third party identities and adds the mobile and pc identities * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus - * the 360 identities pc and mobile. + * the 360 identities pc and mobile. If the retrieval failed the list will + * be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyIdentities() { + if ((mMyIdentityList.size() == 0) && ( + (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) + > MIN_REQUEST_INTERVAL)) { + sendGetAvailableIdentitiesRequest(); + } + return mAvailableIdentityList; } + private void sendGetMyIdentitiesRequest() { + Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); + } + + private void sendGetAvailableIdentitiesRequest() { + Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); + } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ - public void addUiGetAvailableIdentities() { - LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); - emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); - } +// private void addUiGetAvailableIdentities() { +// LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); +// emptyUiRequestQueue(); +// addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); +// } /** * Add request to fetch the current user's identities. * */ - public void addUiGetMyIdentities() { - LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); - emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); - } +// private void addUiGetMyIdentities() { +// LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); +// emptyUiRequestQueue(); +// addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); +// } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * TODO: remove parameter as soon as branch ui-refresh is merged. * * @param data Bundled request data. * */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { switch (mState) { case IDLE: LogUtils.logW("IDLE should never happend"); break; case FETCHING_IDENTITIES: case GETTING_MY_IDENTITIES: case GETTING_MY_CHATABLE_IDENTITIES: handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); break; case SETTING_IDENTITY_CAPABILITY_STATUS: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case VALIDATING_IDENTITY_CREDENTIALS: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("default should never happend"); break; } } } /** * 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: addUiGetAvailableIdentities(); break; case IDENTITY_CHANGE: // TODO padma 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 handleServerGetAvailableIdentitiesResponse(List<BaseDataType> data) { Bundle bu = null; LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); if (errorStatus == ServiceStatus.SUCCESS) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { if (item.type() == BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE) { mAvailableIdentityList.add((Identity)item); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mState == State.GETTING_MY_IDENTITIES || (mState == State.GETTING_MY_CHATABLE_IDENTITIES)) { // store local copy of my identities makeChatableIdentitiesCache(mAvailableIdentityList); bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); } bu.putParcelableArrayList(KEY_DATA, mAvailableIdentityList); } LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse completw UI req"); completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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.type() == 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 handleSetIdentityCapabilityStatus(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.type() == 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); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } /** * * 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(); addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); } } /** * 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, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } }
360/360-Engine-for-Android
bbe89c8eb2ebf81641ac6aebb6384f7138cce245
now using the method stubbed method that Rudy added.
diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index 589f2c8..4150c19 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,316 +1,313 @@ /* * 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.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 - // TODO: Need to construct "status" from identities and utility method - Hashtable<String, String> status = new Hashtable<String, String>(); - status.put("google", "online"); - status.put("microsoft", "online"); - status.put("mobile", "online"); - status.put("facebook.com", "online"); - status.put("hyves.nl", "online"); + // 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) { 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); } } 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 af86495..f9e52f5 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,784 +1,813 @@ /* * 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.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; 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 10 minutes. **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private long mNextRuntime = -1; 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; /** * * @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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (!canRun()) { mNextRuntime = -1; LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" + mNextRuntime); return mNextRuntime; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { 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 (mNextRuntime == -1) { LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!"); return 0; } else { return mNextRuntime; } } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + mNextRuntime + "]"); 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) { if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) { if (canRun()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setNextRuntime(); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20; } } } else { 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); } private void setNextRuntime() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again in [" + (CHECK_FREQUENCY / (1000 * 60)) + "] minutes"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY; } private void setRunNow() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW"); mNextRuntime = 0; } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setNextRuntime(); } else { setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } /*** * 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); } @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: setRunNow(); } } @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++; } } if (mUsers.size() > 0) { 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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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()) { 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 SET_MY_AVAILABILITY_FOR_COMMUNITY: Presence.setMyAvailabilityForCommunity(); 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); setNextRuntime(); } /** * 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()) { 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); + // Get presence list constructed from identities + Hashtable<String, String> presences = getPresencesForStatus(status); + if(presences == null) { + LogUtils.logW("setMyAvailability() Ignoring setMyAvailability request because there are no identities!"); + return; + } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), - presenceList); + presences); // 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, presences); } /** * 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) { 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().getMy360AndThirdPartyIdentities(); + + 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; + } }
360/360-Engine-for-Android
2676f2680c5881bca10eeccbf0aa2b710cbd077c
breaky breaky, identity refaky
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 305499a..e96b92c 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,715 +1,725 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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 { +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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ - private final ArrayList<Identity> mIdentityList = new ArrayList<Identity>(); + private final ArrayList<Identity> mAvailableIdentityList = new ArrayList<Identity>(); + + /** List array of Identities retrieved from Server. */ + private final ArrayList<Identity> mMyIdentityList = new ArrayList<Identity>(); /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** Definitions for expected data-types returned from Server. */ private static final String TYPE_IDENTITY = "Identity"; private static final String TYPE_STATUS_MSG = "StatusMsg"; public static final String KEY_DATA = "data"; private static final String KEY_DATA_CHATABLE_IDENTITIES = "chatable_data"; private static final String LOG_STATUS_MSG = TYPE_STATUS_MSG + ": "; - /** - * Generate Map containing boolean capability filters for supplied Bundle. - * - * @param filter Bundle containing filter. - * @return Map containing set of capabilities. - */ - private static Map<String, Object> prepareBoolFilter(Bundle filter) { - Map<String, Object> objectFilter = null; - if (filter != null && (filter.keySet().size() > 0)) { - objectFilter = new Hashtable<String, Object>(); - 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; - } - /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; } - + + /** - * 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() { - } - - /** - * Process a response received from Server. The response is handled - * according to the current IdentityEngine state. + * Gets all third party identities the user is currently signed up for. * - * @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) { - PushEvent evt = (PushEvent)resp.mDataTypes.get(0); - handlePushRequest(evt.mMessageType); - } else { - switch (mState) { - case IDLE: - LogUtils.logW("IDLE should never happend"); - break; - case FETCHING_IDENTITIES: - case GETTING_MY_IDENTITIES: - case GETTING_MY_CHATABLE_IDENTITIES: - handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); - break; - case SETTING_IDENTITY_CAPABILITY_STATUS: - handleSetIdentityCapabilityStatus(resp.mDataTypes); - break; - case VALIDATING_IDENTITY_CREDENTIALS: - handleValidateIdentityCredentials(resp.mDataTypes); - break; - default: - LogUtils.logW("default should never happend"); - break; - } - } - } - - /** - * Handle Status or Timeline Activity change Push message + * @return A list of 3rd party identities the user is signed in to or null + * if there was something wrong retrieving the identities. * - * @param evt Push message type (Status change or Timeline change). */ private void handlePushRequest(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: addUiFetchIdentities(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); addUiGetMyIdentities(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** - * 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 FETCH_IDENTITIES: - startGetAvailableIdentities(data); - break; - case GET_MY_IDENTITIES: - startGetMyIdentities(data); - break; - case GET_MY_CHATABLE_IDENTITIES: - startGetMyChatableIdentities(); - break; - case VALIDATE_IDENTITY_CREDENTIALS: - startValidateIdentityCredentials(data); - break; - case SET_IDENTITY_CAPABILITY_STATUS: - // changed the method called - // startSetIdentityCapabilityStatus(data); - startSetIdentityStatus(data); - break; - default: - completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); - break; - } - } - - /** - * Run function called via EngineManager. Should have a UI, Comms response - * or timeout event to handle. + * Gets all third party identities and adds the mobile and pc identities + * from 360 to them. + * + * @return A list of all 3rd party identities the user is signed in to plus + * the 360 identities pc and mobile. + * */ - @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(); - } + public ArrayList<Identity> getMy360AndThirdPartyIdentities() { + } - + + + + /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ - public void addUiFetchIdentities() { - LogUtils.logD("IdentityEngine.addUiFetchIdentities()"); + public void addUiGetAvailableIdentities() { + LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.FETCH_IDENTITIES, getIdentitiesFilter()); + addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); + } + + /** + * Add request to fetch the current user's identities. + * + */ + public void addUiGetMyIdentities() { + LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); + emptyUiRequestQueue(); + addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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); } /** - * Add request to fetch the current user's identities. - * - */ - public void addUiGetMyIdentities() { - LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); - emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); - } - - /** - * Change current IdentityEngine state. + * Issue any outstanding UI request. * - * @param newState new state. + * @param requestType Request to be issued. + * @param dara Data associated with the request. */ - private void newState(State newState) { - State oldState = mState; - synchronized (mMutex) { - if (newState == mState) { - return; - } - mState = newState; + @Override + protected void processUiRequest(ServiceUiRequest requestType, Object data) { + LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); + switch (requestType) { + case GET_AVAILABLE_IDENTITIES: + executeGetAvailableIdentitiesRequest(data); + break; + case GET_MY_IDENTITIES: + executeGetMyIdentitiesRequest(data); + break; + case VALIDATE_IDENTITY_CREDENTIALS: + executeValidateIdentityCredentialsRequest(data); + break; + case SET_IDENTITY_CAPABILITY_STATUS: + // changed the method called + // startSetIdentityCapabilityStatus(data); + executeSetIdentityStatusRequest(data); + break; + default: + completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); + break; } - LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } - + /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * TODO: remove parameter as soon as branch ui-refresh is merged. * * @param data Bundled request data. * */ - private void startGetMyIdentities(Object data) { + private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } - /** - * Issue request to retrieve 'My chat-able' Identities. The request is - * filtered to retrieve only identities with the chat capability enabled. - * (Request is not issued if there is currently no connectivity). - */ - private void startGetMyChatableIdentities() { - if (!isConnected()) { - return; - } - Bundle filter = new Bundle(); - ArrayList<String> l = new ArrayList<String>(); - l.add(IdentityCapability.CapabilityID.chat.name()); - filter.putStringArrayList("capability", l); - - newState(State.GETTING_MY_CHATABLE_IDENTITIES); - if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter(filter)))) { - completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); - } - } - - /** * 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 startSetIdentityStatus(Object data) { + private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_CAPABILITY_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 startValidateIdentityCredentials(Object 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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ - private void startGetAvailableIdentities(Object data) { + private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); - mIdentityList.clear(); + mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { + PushEvent evt = (PushEvent)resp.mDataTypes.get(0); + handlePushResponse(evt.mMessageType); + } else { + switch (mState) { + case IDLE: + LogUtils.logW("IDLE should never happend"); + break; + case FETCHING_IDENTITIES: + case GETTING_MY_IDENTITIES: + case GETTING_MY_CHATABLE_IDENTITIES: + handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); + break; + case SETTING_IDENTITY_CAPABILITY_STATUS: + handleSetIdentityCapabilityStatus(resp.mDataTypes); + break; + case VALIDATING_IDENTITY_CREDENTIALS: + handleValidateIdentityCredentials(resp.mDataTypes); + break; + default: + LogUtils.logW("default should never happend"); + break; + } + } + } + + /** + * 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: + addUiGetAvailableIdentities(); + break; + case IDENTITY_CHANGE: + // TODO padma + 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 handleServerGetAvailableIdentitiesResponse(List<BaseDataType> data) { Bundle bu = null; LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(TYPE_IDENTITY, data); if (errorStatus == ServiceStatus.SUCCESS) { - mIdentityList.clear(); + mAvailableIdentityList.clear(); for (BaseDataType item : data) { if (TYPE_IDENTITY.equals(item.name())) { - mIdentityList.add((Identity)item); + mAvailableIdentityList.add((Identity)item); LogUtils.logD("Identity: " + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mState == State.GETTING_MY_IDENTITIES || (mState == State.GETTING_MY_CHATABLE_IDENTITIES)) { // store local copy of my identities - makeChatableIdentitiesCache(mIdentityList); + makeChatableIdentitiesCache(mAvailableIdentityList); bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); } - bu.putParcelableArrayList(KEY_DATA, mIdentityList); + bu.putParcelableArrayList(KEY_DATA, mAvailableIdentityList); } LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse completw UI req"); completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } 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 handleSetIdentityCapabilityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } - - /** - * Add request to fetch the current user's 'chat-able' identities. This will - * automatically apply set of filters applied to GetMyIdentities API call to - * get Identities with chat capability. - * - * Note: Only called from tests. - */ - public void getMyChatableIdentities() { - LogUtils.logD("IdentityEngine.getMyChatableIdentities()"); - if (mMyChatableIdentityList != null) { - Bundle bu = new Bundle(); - bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); - completeUiRequest(ServiceStatus.SUCCESS, bu); - return; - } - - addUiRequestToQueue(ServiceUiRequest.GET_MY_CHATABLE_IDENTITIES, null); - } /** * * 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(); + addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); + } + } + + /** + * 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, Object> prepareBoolFilter(Bundle filter) { + Map<String, Object> objectFilter = null; + if (filter != null && (filter.keySet().size() > 0)) { + objectFilter = new Hashtable<String, Object>(); + 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; + } + } diff --git a/src/com/vodafone360/people/service/ServiceUiRequest.java b/src/com/vodafone360/people/service/ServiceUiRequest.java index 529d203..caf24d7 100644 --- a/src/com/vodafone360/people/service/ServiceUiRequest.java +++ b/src/com/vodafone360/people/service/ServiceUiRequest.java @@ -1,267 +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 */ - FETCH_IDENTITIES, + 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, /** * Request to set the presence availability status for a single community */ SET_MY_AVAILABILITY_FOR_COMMUNITY, /** 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, /* * 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 0dbc95b..4181983 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,333 +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.interfaces; import android.os.Bundle; import android.os.Handler; 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.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(); /*** * Begins the process of retrieving Third party Accounts that the user is * already registered with 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 fetchMyIdentities(Bundle data); + //void fetchMyIdentities(Bundle data); /*** * 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); + //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 availability state for a single network. * @param presence Network-presence to set */ void setAvailability(NetworkPresence presence); /*** * 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 c80638b..4da73ae 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,427 +1,427 @@ /* * 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.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#fetchAvailableIdentities(Bundle) */ - @Override +/* @Override public void fetchAvailableIdentities(Bundle data) { - EngineManager.getInstance().getIdentityEngine().addUiFetchIdentities(); - } + EngineManager.getInstance().getIdentityEngine().addUiGetAvailableIdentities(); + }*/ /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchMyIdentities(Bundle) */ - @Override + /*@Override public void fetchMyIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(); - } + }*/ /*** * @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); } /*** * @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
72dc6967ead0b41172039d3b976c1d4cc58e2528
Simplified code a little, now just has old behaviour with minor cleanup.
diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index f28ee66..589f2c8 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,325 +1,316 @@ /* * 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.ContactSummary.OnlineStatus; 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 - // TODO: this hard code needs change, must filter the identities - // info by VCARD.IMADRESS + // TODO: Need to construct "status" from identities and utility method Hashtable<String, String> status = new Hashtable<String, String>(); status.put("google", "online"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("facebook.com", "online"); status.put("hyves.nl", "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) { 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); } } 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); } } - - /** - * @param input - * @return - */ - public static boolean notNullOrBlank(String input) { - return (input != null) && input.length() > 0; - } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 754f7b0..af86495 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,847 +1,784 @@ /* * 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.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.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; 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, - IContactSyncObserver, ITcpConnectionListener { + ITcpConnectionListener { /** Check every 10 minutes. **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private long mNextRuntime = -1; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private List<TimelineSummaryItem> mFailedMessagesList; // (to, network) - - private boolean mContObsAdded; /** 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; /** * * @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>(); - addAsContactSyncObserver(); } @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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { - - if (!mContObsAdded) { - addAsContactSyncObserver(); - } - if (!canRun()) { mNextRuntime = -1; LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" + mNextRuntime); return mNextRuntime; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { 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 (mNextRuntime == -1) { LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!"); return 0; } else { return mNextRuntime; } } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + mNextRuntime + "]"); 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) { if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) { if (canRun()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setNextRuntime(); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20; } } } else { 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); } private void setNextRuntime() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again in [" + (CHECK_FREQUENCY / (1000 * 60)) + "] minutes"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY; } private void setRunNow() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW"); mNextRuntime = 0; } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setNextRuntime(); } else { setPresenceOffline(); - mContObsAdded = false; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } /*** * 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); } @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: setRunNow(); } } @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++; } } if (mUsers.size() > 0) { 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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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()) { 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: - if (data != null) { - Presence.setMyAvailability(((OnlineStatus)data).toString()); - completeUiRequest(ServiceStatus.SUCCESS, null); - setNextRuntime(); - } + Presence.setMyAvailability((Hashtable<String, String>)data); break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: - if (data != null) { - Presence.setMyAvailabilityForCommunity(); - completeUiRequest(ServiceStatus.SUCCESS, null); - setNextRuntime(); - } + Presence.setMyAvailabilityForCommunity(); + break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); - completeUiRequest(ServiceStatus.SUCCESS, null); - setNextRuntime(); break; - case CREATE_CONVERSATION: - if (data != null) { - List<String> tos = ((ChatMessage)data).getTos(); - LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " - + tos); - Chat.startChat(tos); - // Request to update the UI - completeUiRequest(ServiceStatus.SUCCESS, null); - // Request to update the UI - setNextRuntime(); - } + List<String> tos = ((ChatMessage)data).getTos(); + LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + + tos); + Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: - if (data != null) { - 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); - // Request to update the UI - completeUiRequest(ServiceStatus.SUCCESS, null); - // Request to update the UI - setNextRuntime(); - } + 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); + setNextRuntime(); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } - - private void initSetMyAvailabilityRequest(User myself) { - if (myself == 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 ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && + if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !canRun()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); - for (NetworkPresence presence : myself.getPayload()) { + for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values - myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); + me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); - updateMyPresenceInDatabase(myself); + 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 = new Hashtable<String, String>(); - // 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); } } } - - /** - * 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. - */ - private void addAsContactSyncObserver() { - if (EngineManager.getInstance() != null - && EngineManager.getInstance().getContactSyncEngine() != null) { - EngineManager.getInstance().getContactSyncEngine().addEventCallback(this); - mContObsAdded = true; - LogUtils.logD("ActivityEngine contactSync observer added."); - } else { - LogUtils.logE("ActivityEngine can't add to contactSync observers."); - } - } - - @Override - public void onContactSyncStateChange(Mode mode, State oldState, State newState) { - LogUtils.logD("PresenceEngine onContactSyncStateChange called."); - } - - @Override - public void onProgressEvent(State currentState, int percent) { - if (percent == 100) { - switch (currentState) { - case FETCHING_SERVER_CONTACTS: - LogUtils - .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_CONTACTS is done"); - // mDownloadServerContactsComplete = true; - // break; - // case SYNCING_SERVER_ME_PROFILE: - // LogUtils - // .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_ME_PROFILE is done"); - // mDownloadMeProfileComplete = true; - // break; - default: - // nothing to do now - break; - } - } - } - - @Override - public void onSyncComplete(ServiceStatus status) { - LogUtils.logD("PresenceEngine onSyncComplete called."); - } @Override public void onConnectionStateChanged(int state) { 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()); } } diff --git a/src/com/vodafone360/people/service/io/api/Presence.java b/src/com/vodafone360/people/service/io/api/Presence.java index 7f3bccc..d9a71ac 100644 --- a/src/com/vodafone360/people/service/io/api/Presence.java +++ b/src/com/vodafone360/people/service/io/api/Presence.java @@ -1,102 +1,115 @@ /* * 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.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; + } + 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(); } public static void setMyAvailabilityForCommunity() { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.setMyAvailabilityForCommunity() No session, so return"); return; } } } diff --git a/src/com/vodafone360/people/utils/HardcodedUtils.java b/src/com/vodafone360/people/utils/HardcodedUtils.java index 4f3fe72..c76e198 100644 --- a/src/com/vodafone360/people/utils/HardcodedUtils.java +++ b/src/com/vodafone360/people/utils/HardcodedUtils.java @@ -1,65 +1,65 @@ /* * 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.Hashtable; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.NetworkPresence; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; /** * @author timschwerdtner * Collection of hardcoded and duplicated code as a first step for refactoring. */ public class HardcodedUtils { -// /** -// * To be used with IPeopleService.setAvailability until identity handling -// * has been refactored. -// * @param Desired availability state -// * @return A hashtable for the set availability call -// */ -// public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) { -// Hashtable<String, String> availability = new Hashtable<String, String>(); -// -// LogUtils.logD("Setting Availability to: " + onlineStatus.toString()); -// // TODO: REMOVE HARDCODE setting everything possible to currentStatus -// availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString()); -// -// return availability; -// } + /** + * To be used with IPeopleService.setAvailability until identity handling + * has been refactored. + * @param Desired availability state + * @return A hashtable for the set availability call + */ + public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) { + Hashtable<String, String> availability = new Hashtable<String, String>(); + + LogUtils.logD("Setting Availability to: " + onlineStatus.toString()); + // TODO: REMOVE HARDCODE setting everything possible to currentStatus + availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString()); + + return availability; + } /** * The static list of supported TPC accounts. */ public static final int[] THIRD_PARTY_CHAT_ACCOUNTS = new int[]{SocialNetwork.FACEBOOK_COM.ordinal(), SocialNetwork.GOOGLE.ordinal(), SocialNetwork.HYVES_NL.ordinal(), SocialNetwork.MICROSOFT.ordinal()}; }
360/360-Engine-for-Android
a8c4b37d5cc34747f68832c13f38d9d47d128c63
New availability method now used NetworkPresence as the argument
diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index 74d077e..f28ee66 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,325 +1,325 @@ /* * 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.ContactSummary.OnlineStatus; 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 // TODO: this hard code needs change, must filter the identities // info by VCARD.IMADRESS Hashtable<String, String> status = new Hashtable<String, String>(); status.put("google", "online"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("facebook.com", "online"); status.put("hyves.nl", "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) { 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); } } return !ignoredNetworks.isEmpty(); } protected static boolean updateMyPresence(User user, DatabaseHelper dbHelper) { boolean contactsChanged = false; - SQLiteDatabase writableDb = dbHelper.getWritableDatabase(); - if (PresenceTable.updateUser(user, null, writableDb) != PresenceTable.USER_NOTADDED) { + 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); } } /** * @param input * @return */ public static boolean notNullOrBlank(String input) { return (input != null) && input.length() > 0; } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 4b898e7..754f7b0 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,822 +1,847 @@ /* * 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.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.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; 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.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, IContactSyncObserver, ITcpConnectionListener { /** Check every 10 minutes. **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private long mNextRuntime = -1; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private List<TimelineSummaryItem> mFailedMessagesList; // (to, network) private boolean mContObsAdded; /** 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; /** * * @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>(); addAsContactSyncObserver(); } @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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (!mContObsAdded) { addAsContactSyncObserver(); } if (!canRun()) { mNextRuntime = -1; LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" + mNextRuntime); return mNextRuntime; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { 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 (mNextRuntime == -1) { LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!"); return 0; } else { return mNextRuntime; } } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + mNextRuntime + "]"); 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) { if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) { if (canRun()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setNextRuntime(); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20; } } } else { 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); } private void setNextRuntime() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again in [" + (CHECK_FREQUENCY / (1000 * 60)) + "] minutes"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY; } private void setRunNow() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW"); mNextRuntime = 0; } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setNextRuntime(); } else { setPresenceOffline(); mContObsAdded = false; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } /*** * 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); } @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: setRunNow(); } } @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++; } } if (mUsers.size() > 0) { 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 + "]"); - UiAgent uiAgent = mEventCallback.getUiAgent(); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { - uiAgent.updatePresence(myself.getLocalContactId()); + 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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { Presence.setMyAvailability(((OnlineStatus)data).toString()); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: if (data != null) { Presence.setMyAvailabilityForCommunity(); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); break; case CREATE_CONVERSATION: if (data != null) { List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; case SEND_CHAT_MESSAGE: if (data != null) { 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); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); } } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } private void initSetMyAvailabilityRequest(User myself) { if (myself == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !canRun()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** - * Changes the state of the engine. Also displays the login notification if - * necessary. + * Changes the user's availability and therefore the state of the engine. + * Also displays the login notification if necessary. * - * @param accounts + * @param status Availability to set for all identities we have. */ - public void setMyAvailability(OnlineStatus onlinestatus) { - if (onlinestatus == null) { + 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:"+onlinestatus.toString()); + 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> userPresence = new Hashtable<String, String>(); + Hashtable<String, String> presenceList = new Hashtable<String, String>(); // TODO: Fill up hashtable with identities and online statuses - User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), - userPresence); - Hashtable<String, String> availability = new Hashtable<String, String>(); - for (NetworkPresence presence : myself.getPayload()) { - availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), - OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); - } + User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), + presenceList); + // set the DB values for myself - myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); - updateMyPresenceInDatabase(myself); + me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); + updateMyPresenceInDatabase(me); // set the engine to run now - addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, userPresence); + addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } - public void setMyAvailability(String network, String availability) { - + /** + * 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); } } } /** * 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. */ private void addAsContactSyncObserver() { if (EngineManager.getInstance() != null && EngineManager.getInstance().getContactSyncEngine() != null) { EngineManager.getInstance().getContactSyncEngine().addEventCallback(this); mContObsAdded = true; LogUtils.logD("ActivityEngine contactSync observer added."); } else { LogUtils.logE("ActivityEngine can't add to contactSync observers."); } } @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { LogUtils.logD("PresenceEngine onContactSyncStateChange called."); } @Override public void onProgressEvent(State currentState, int percent) { if (percent == 100) { switch (currentState) { case FETCHING_SERVER_CONTACTS: LogUtils .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_CONTACTS is done"); // mDownloadServerContactsComplete = true; // break; // case SYNCING_SERVER_ME_PROFILE: // LogUtils // .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_ME_PROFILE is done"); // mDownloadMeProfileComplete = true; // break; default: // nothing to do now break; } } } @Override public void onSyncComplete(ServiceStatus status) { LogUtils.logD("PresenceEngine onSyncComplete called."); } @Override public void onConnectionStateChanged(int state) { 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()); } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index 67a4a99..0dbc95b 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,345 +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.interfaces; -import java.util.Hashtable; - import android.os.Bundle; import android.os.Handler; 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.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(); /*** * Begins the process of retrieving Third party Accounts that the user is * already registered with 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 fetchMyIdentities(Bundle data); /*** * 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); - -// /*** -// * Alter the current Social Network availability state and send it to the -// * server. -// * -// * @param myself is the wrapper for the own presence state, can be retrieved -// * from PresenceTable.getUserByLocalContactId(long -// * meProfileLocalContactId). -// */ -// void setAvailability(Hashtable<String, String> myself); /** * Change current global (all identities) availability state. - * @param onlinestatus Availability to set for all identities we have. + * @param status Availability to set for all identities we have. */ - void setAvailability(OnlineStatus onlinestatus); + void setAvailability(OnlineStatus status); /** * Change current availability state for a single network. - * @param network - * @param availability + * @param presence Network-presence to set */ - void setAvailability(String network, String availability); + void setAvailability(NetworkPresence presence); /*** * 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 3674f0e..c80638b 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,425 +1,427 @@ /* * 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.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#fetchAvailableIdentities(Bundle) */ @Override public void fetchAvailableIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiFetchIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchMyIdentities(Bundle) */ @Override public void fetchMyIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(); } /*** * @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(String) + * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(OnlineStatus) */ @Override - public void setAvailability(OnlineStatus onlinestatus) { - EngineManager.getInstance().getPresenceEngine().setMyAvailability(onlinestatus); + public void setAvailability(OnlineStatus status) { + EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** - * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(String, String) + * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(NetworkPresence) */ @Override - public void setAvailability(String network, String availability) { - EngineManager.getInstance().getPresenceEngine().setMyAvailability(network, availability); + public void setAvailability(NetworkPresence presence) { + EngineManager.getInstance().getPresenceEngine().setMyAvailability(presence); } /*** * @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
9fa8f7ed3b7b8321215d47465c1a84bb15f0ecc8
Minor changes that I missed.
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index f610e24..4b898e7 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -49,786 +49,774 @@ import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; 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.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.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, IContactSyncObserver, ITcpConnectionListener { /** Check every 10 minutes. **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private long mNextRuntime = -1; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private List<TimelineSummaryItem> mFailedMessagesList; // (to, network) private boolean mContObsAdded; /** 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; /** * * @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>(); addAsContactSyncObserver(); } @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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (!mContObsAdded) { addAsContactSyncObserver(); } if (!canRun()) { mNextRuntime = -1; LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" + mNextRuntime); return mNextRuntime; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { 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 (mNextRuntime == -1) { LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!"); return 0; } else { return mNextRuntime; } } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + mNextRuntime + "]"); 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) { if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) { if (canRun()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setNextRuntime(); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20; } } } else { 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); } private void setNextRuntime() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again in [" + (CHECK_FREQUENCY / (1000 * 60)) + "] minutes"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY; } private void setRunNow() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW"); mNextRuntime = 0; } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setNextRuntime(); } else { setPresenceOffline(); mContObsAdded = false; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } /*** * 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); } @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: setRunNow(); } } @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++; } } if (mUsers.size() > 0) { 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 + "]"); UiAgent uiAgent = mEventCallback.getUiAgent(); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { uiAgent.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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { - Presence.setMyAvailability((String)data); + Presence.setMyAvailability(((OnlineStatus)data).toString()); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: if (data != null) { Presence.setMyAvailabilityForCommunity(); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); break; case CREATE_CONVERSATION: if (data != null) { List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; case SEND_CHAT_MESSAGE: if (data != null) { 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); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); } } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } private void initSetMyAvailabilityRequest(User myself) { if (myself == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !canRun()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } -// /** -// * Changes the state of the engine. Also displays the login notification if -// * necessary. -// * -// * @param accounts -// */ -// public void setMyAvailability(Hashtable<String, String> myselfPresence) { -// if (myselfPresence == null) { -// LogUtils.logE("PresenceEngine setMyAvailability:" -// + " Can't send the setAvailability request due to DB reading errors"); -// return; -// } -// -// LogUtils.logV("PresenceEngine setMyAvailability() called with:" + myselfPresence); -// if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { -// LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); -// return; -// } -// -// User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), -// myselfPresence); -// -// Hashtable<String, String> availability = new Hashtable<String, String>(); -// for (NetworkPresence presence : myself.getPayload()) { -// availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), -// OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); -// } -// // set the DB values for myself -// myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); -// updateMyPresenceInDatabase(myself); -// -// // set the engine to run now -// -// addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); -// } - /** + * Changes the state of the engine. Also displays the login notification if + * necessary. * - * @param availability + * @param accounts */ - public void setMyAvailability(String availability) { - if (TextUtils.isEmpty(availability)) { + public void setMyAvailability(OnlineStatus onlinestatus) { + if (onlinestatus == null) { LogUtils.logE("PresenceEngine setMyAvailability:" - + " Can't my availability using empty availability"); + + " Can't send the setAvailability request due to DB reading errors"); return; } - LogUtils.logV("PresenceEngine setMyAvailability() called with:" + availability); + LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+onlinestatus.toString()); + if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { + LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); + return; + } + + // Get presences + Hashtable<String, String> userPresence = new Hashtable<String, String>(); + + // TODO: Fill up hashtable with identities and online statuses + User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), + userPresence); + + Hashtable<String, String> availability = new Hashtable<String, String>(); + for (NetworkPresence presence : myself.getPayload()) { + availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), + OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); + } + // set the DB values for myself + myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); + updateMyPresenceInDatabase(myself); + + // set the engine to run now - addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); + addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, userPresence); } - + public void setMyAvailability(String network, String availability) { } 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); } } } /** * 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. */ private void addAsContactSyncObserver() { if (EngineManager.getInstance() != null && EngineManager.getInstance().getContactSyncEngine() != null) { EngineManager.getInstance().getContactSyncEngine().addEventCallback(this); mContObsAdded = true; LogUtils.logD("ActivityEngine contactSync observer added."); } else { LogUtils.logE("ActivityEngine can't add to contactSync observers."); } } @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { LogUtils.logD("PresenceEngine onContactSyncStateChange called."); } @Override public void onProgressEvent(State currentState, int percent) { if (percent == 100) { switch (currentState) { case FETCHING_SERVER_CONTACTS: LogUtils .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_CONTACTS is done"); // mDownloadServerContactsComplete = true; // break; // case SYNCING_SERVER_ME_PROFILE: // LogUtils // .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_ME_PROFILE is done"); // mDownloadMeProfileComplete = true; // break; default: // nothing to do now break; } } } @Override public void onSyncComplete(ServiceStatus status) { LogUtils.logD("PresenceEngine onSyncComplete called."); } @Override public void onConnectionStateChanged(int state) { 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()); } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index 6fd9379..67a4a99 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,344 +1,345 @@ /* * 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.Hashtable; import android.os.Bundle; import android.os.Handler; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; +import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; 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(); /*** * Begins the process of retrieving Third party Accounts that the user is * already registered with 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 fetchMyIdentities(Bundle data); /*** * 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); // /*** // * Alter the current Social Network availability state and send it to the // * server. // * // * @param myself is the wrapper for the own presence state, can be retrieved // * from PresenceTable.getUserByLocalContactId(long // * meProfileLocalContactId). // */ // void setAvailability(Hashtable<String, String> myself); /** * Change current global (all identities) availability state. - * @param availability Availability to set for all identities we have. + * @param onlinestatus Availability to set for all identities we have. */ - void setAvailability(String availability); + void setAvailability(OnlineStatus onlinestatus); /** * Change current availability state for a single network. * @param network * @param availability */ void setAvailability(String network, String availability); /*** * 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 f3e4033..3674f0e 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,424 +1,425 @@ /* * 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.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.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#fetchAvailableIdentities(Bundle) */ @Override public void fetchAvailableIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiFetchIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchMyIdentities(Bundle) */ @Override public void fetchMyIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(); } /*** * @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(String) */ @Override - public void setAvailability(String availability) { - EngineManager.getInstance().getPresenceEngine().setMyAvailability(availability); + public void setAvailability(OnlineStatus onlinestatus) { + EngineManager.getInstance().getPresenceEngine().setMyAvailability(onlinestatus); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(String, String) */ @Override public void setAvailability(String network, String availability) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(network, availability); } /*** * @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 diff --git a/src/com/vodafone360/people/service/io/api/Presence.java b/src/com/vodafone360/people/service/io/api/Presence.java index 6d7fc80..7f3bccc 100644 --- a/src/com/vodafone360/people/service/io/api/Presence.java +++ b/src/com/vodafone360/people/service/io/api/Presence.java @@ -1,100 +1,102 @@ /* * 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.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(); } /** * API to set my availability * * @param engineId ID of presence engine. - * @param availability Availability to set + * @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 apropriate 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(); } public static void setMyAvailabilityForCommunity() { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.setMyAvailabilityForCommunity() No session, so return"); return; } } }
360/360-Engine-for-Android
a46bbc8eac054225294da95e37ed066454de215a
Removed . from README
diff --git a/README b/README index 0c39d43..9defdfe 100644 --- a/README +++ b/README @@ -1 +1 @@ -For detailed documentation please visit http://360.github.com/360-Engine-for-Android. +For detailed documentation please visit http://360.github.com/360-Engine-for-Android
360/360-Engine-for-Android
266e34205529f5416a04b5f2a897b12075bb6e71
Added . to README
diff --git a/README b/README index 9defdfe..0c39d43 100644 --- a/README +++ b/README @@ -1 +1 @@ -For detailed documentation please visit http://360.github.com/360-Engine-for-Android +For detailed documentation please visit http://360.github.com/360-Engine-for-Android.
360/360-Engine-for-Android
d5a38550e8b3cee019a2d4839becce55ea5b9cb6
- changed ui accessors in IdentityEngine - added different types to Identity to be able to distinguish between GetAvailableIdentities and GetMyIdentities - HessianDecoder now distinguishes between GetAvailableIdentities and GetMyIdentities, too
diff --git a/src/com/vodafone360/people/datatypes/Identity.java b/src/com/vodafone360/people/datatypes/Identity.java index 8d288b2..28d8446 100644 --- a/src/com/vodafone360/people/datatypes/Identity.java +++ b/src/com/vodafone360/people/datatypes/Identity.java @@ -1,605 +1,609 @@ /* * 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.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Vector; import android.os.Parcel; import android.os.Parcelable; import com.vodafone360.people.utils.LogUtils; /** * BaseDataType encapsulating an Identity issued to or retrieved from server */ public class Identity extends BaseDataType implements Parcelable { /** * Tags associated with Identity item. */ private enum Tags { IDENTITY_MAIN_TAG("availableidentity"), IDENTITY_CAPABILITY_LIST("identitycapabilitylist"), PLUGIN_ID("pluginid"), NETWORK_URL("networkurl"), AUTH_TYPE("authtype"), ICON_MIME("iconmime"), ICON2_MIME("icon2mime"), ORDER("order"), NAME("name"), ICON_URL("iconurl"), ICON2_URL("icon2url"), NETWORK("network"), // Properties below are only present after // GetMyIdentities. ACTIVE("active"), CREATED("created"), IDENTITY_ID("identityid"), UPDATED("updated"), IDENTITY_TYPE("identitytype"), USER_ID("userid"), USER_NAME("username"), DISPLAY_NAME("displayname"), COUNTRY_LIST("countrylist"); private final String tag; /** * Construct Tags item from supplied String * * @param s String value for Tags item. */ private Tags(String s) { tag = s; } /** * String value for 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 in Tags items. * @return Tags item for specified String, NULL otherwise. */ private static Tags findTag(String tag) { for (Tags tags : Tags.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } return null; } } public String mPluginId = null; public String mNetwork = null; public URL mNetworkUrl = null; public URL mIconUrl = null; public URL mIcon2Url = null; public String mAuthType; public String mIconMime = null; public Integer mOrder = null; public String mName = null; public List<IdentityCapability> mCapabilities = null; /** Properties below are only present after GetMyIdentities. */ public Boolean mActive = null; public Long mCreated = null; public Long mUpdated = null; public String mIdentityId = null; public Integer mUserId = null; public String mUserName = null; public String mDisplayName = null; public List<String> mCountryList = null; public String mIdentityType = null; + + private int mType; /** * Comparator class used to compare Identities retrieved from server to * remove duplicates from list passed to People client UI. */ public static class IdentityComparator implements Comparator<Identity> { @Override public int compare(Identity object1, Identity object2) { return object1.mOrder.compareTo(object2.mOrder); } } /** * Test whether current Identity is identical to supplied Identity. * * @param id Identity to compare against. * @return true if Identities match, false otherwise. */ public boolean isSameAs(Identity id) { boolean isSame = true; if (!areStringValuesSame(mPluginId, id.mPluginId) || !areStringValuesSame(mNetwork, id.mNetwork) || !areStringValuesSame(mIdentityId, id.mIdentityId) || !areStringValuesSame(mDisplayName, id.mDisplayName)) { isSame = false; } if (mNetworkUrl != null && id.mNetworkUrl != null) { if (!mNetworkUrl.sameFile(id.mNetworkUrl)) { isSame = false; } } else if (mNetworkUrl == null && id.mNetworkUrl == null) { // Do nothing. } else { isSame = false; } if (mIconUrl != null && id.mIconUrl != null) { if (!mIconUrl.sameFile(id.mIconUrl)) { isSame = false; } } else if (mIconUrl == null && id.mIconUrl == null) { // Do nothing. } else { isSame = false; } return isSame; } /** * String values comparison * * @param s1 First String to test. * @param s2 Second String to test. * @return true if Strings match (or both are null), false otherwise. */ private boolean areStringValuesSame(String s1, String s2) { boolean isSame = true; if (s1 == null && s2 == null) { // Do nothing. } else if (s1 != null && s2 != null) { if (s1.compareTo(s2) != 0) { isSame = false; } } else { isSame = false; } return isSame; } /** * Default constructor. */ public Identity() { // Do nothing. } + + public Identity(int type) { + mType = type; + } /** * Create Identity from Parcel. * * @param in Parcel containing Identity. */ private Identity(Parcel in) { readFromParcel(in); } /** {@inheritDoc} */ @Override public int type() { - // TODO: Return appropriate type if its - // an available identity instead of my identity - return MY_IDENTITY_DATA_TYPE; + return mType; } /** * Populate Identity from supplied Hashtable. * * @param hash Hashtable containing identity details. * @return Identity instance. */ public Identity createFromHashtable(Hashtable<String, Object> hash) { Enumeration<String> e = hash.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); Object value = hash.get(key); Tags tag = Tags.findTag(key); if (tag != null) setValue(tag, value); } 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 val) { switch (tag) { case AUTH_TYPE: mAuthType = (String)val; break; case ICON_MIME: mIconMime = (String)val; break; case ICON2_MIME: // TODO: Remove TAG value? // mIcon2Mime = (String)val; break; case ICON_URL: try { mIconUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIconUrl = null; } break; case ICON2_URL: try { mIcon2Url = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong icon url: '" + val + "'"); mIcon2Url = null; } break; case IDENTITY_CAPABILITY_LIST: /** Create id capability list. */ @SuppressWarnings("unchecked") Vector<Hashtable<String, Object>> v = (Vector<Hashtable<String, Object>>)val; if (mCapabilities == null) { mCapabilities = new ArrayList<IdentityCapability>(); } for (Hashtable<String, Object> obj : v) { IdentityCapability cap = new IdentityCapability(); cap.createFromHashtable(obj); mCapabilities.add(cap); } break; case IDENTITY_MAIN_TAG: // Not currently handled. break; case NAME: mName = (String)val; break; case NETWORK: mNetwork = (String)val; break; case NETWORK_URL: try { mNetworkUrl = new URL((String)val); } catch (MalformedURLException e) { LogUtils.logE("Wrong network url: '" + val + "'"); mNetworkUrl = null; } break; case ORDER: mOrder = (Integer)val; break; case PLUGIN_ID: mPluginId = (String)val; break; case ACTIVE: mActive = (Boolean)val; break; case CREATED: mCreated = (Long)val; break; case DISPLAY_NAME: mDisplayName = (String)val; break; case IDENTITY_ID: mIdentityId = (String)val; break; case IDENTITY_TYPE: mIdentityType = (String)val; break; case UPDATED: mUpdated = (Long)val; break; case USER_ID: mUserId = ((Long)val).intValue(); break; case USER_NAME: mUserName = (String)val; break; case COUNTRY_LIST: if (mCountryList == null) { mCountryList = new ArrayList<String>(); } break; default: // Do nothing. break; } } /** {@inheritDoc} */ @Override public String toString() { StringBuffer ret = new StringBuffer(); ret.append("Name: " + mName); ret.append("\nPluginID: " + mPluginId); ret.append("\nNetwork: " + mNetwork); ret.append("\nNetworkURL: " + mNetworkUrl); ret.append("\nAuthType: " + mAuthType); ret.append("\nIcon mime: " + mIconMime); ret.append("\nIconURL: " + mIconUrl); ret.append("\nOrder: " + mOrder); ret.append("\nActive: " + mActive); ret.append("\nCreated: " + mCreated); ret.append("\nUpdated: " + mUpdated); ret.append("\nIdentityId: " + mIdentityId); ret.append("\nUserId: " + mUserId); ret.append("\nUserName: " + mUserName); ret.append("\nDisplayName: " + mDisplayName); ret.append("\nIdentityType: " + mIdentityType); if (mCountryList != null) { ret.append("\nCountry List: (" + mCountryList.size() + ") = ["); for (int i = 0; i < mCountryList.size(); i++) { ret.append(mCountryList.get(i)); if (i < mCountryList.size() - 1) ret.append(", "); } ret.append("]"); } if (mCapabilities != null) { ret.append("\nCapabilities (" + mCapabilities.size() + ")"); for (int i = 0; i < mCapabilities.size(); i++) { ret.append("\n" + mCapabilities.get(i).toString()); if (i < mCapabilities.size() - 1) { ret.append("\n\t---"); } } } return ret.toString(); } /** {@inheritDoc} */ @Override public int describeContents() { return 1; } /** * Enumeration containing items contained within Identity Parcel. */ private enum MemberData { PLUGIN_ID, NETWORK, NETWORK_URL, ICON_URL, AUTH_TYPE, ICON_MIME, ORDER, NAME; } /** * Read Identity item from Parcel. * * @param in Parcel containing Identity information. */ private void readFromParcel(Parcel in) { mPluginId = null; mNetwork = null; mNetworkUrl = null; mIconUrl = null; mAuthType = null; mIconMime = null; mOrder = null; mName = null; mCapabilities = null; boolean[] validDataList = new boolean[MemberData.values().length]; in.readBooleanArray(validDataList); if (validDataList[MemberData.PLUGIN_ID.ordinal()]) { mPluginId = in.readString(); } if (validDataList[MemberData.NETWORK.ordinal()]) { mNetwork = in.readString(); } if (validDataList[MemberData.NETWORK_URL.ordinal()]) { try { mNetworkUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.NETWORK_URL"); } } if (validDataList[MemberData.ICON_URL.ordinal()]) { try { mIconUrl = new URL(in.readString()); } catch (MalformedURLException e) { LogUtils.logW("Identity.readFromParcel() " + "MalformedURLException on MemberData.ICON_URL"); } } if (validDataList[MemberData.AUTH_TYPE.ordinal()]) { mAuthType = in.readString(); } if (validDataList[MemberData.ICON_MIME.ordinal()]) { mIconMime = in.readString(); } if (validDataList[MemberData.ORDER.ordinal()]) { mOrder = in.readInt(); } if (validDataList[MemberData.NAME.ordinal()]) { mName = in.readString(); } int noOfCapabilities = in.readInt(); if (noOfCapabilities > 0) { mCapabilities = new ArrayList<IdentityCapability>(noOfCapabilities); for (int i = 0; i < noOfCapabilities; i++) { IdentityCapability cap = IdentityCapability.CREATOR.createFromParcel(in); mCapabilities.add(cap); } } } /** {@inheritDoc} */ @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 (mPluginId != null) { validDataList[MemberData.PLUGIN_ID.ordinal()] = true; dest.writeString(mPluginId); } if (mNetwork != null) { validDataList[MemberData.NETWORK.ordinal()] = true; dest.writeString(mNetwork); } if (mNetworkUrl != null) { validDataList[MemberData.NETWORK_URL.ordinal()] = true; dest.writeString(mNetworkUrl.toString()); } if (mIconUrl != null) { validDataList[MemberData.ICON_URL.ordinal()] = true; dest.writeString(mIconUrl.toString()); } if (mAuthType != null) { validDataList[MemberData.AUTH_TYPE.ordinal()] = true; dest.writeString(mAuthType); } if (mIconMime != null) { validDataList[MemberData.ICON_MIME.ordinal()] = true; dest.writeString(mIconMime); } if (mOrder != null) { validDataList[MemberData.ORDER.ordinal()] = true; dest.writeInt(mOrder); } if (mName != null) { validDataList[MemberData.NAME.ordinal()] = true; dest.writeString(mName); } if (mCapabilities != null) { dest.writeInt(mCapabilities.size()); for (IdentityCapability cap : mCapabilities) { cap.writeToParcel(dest, 0); } } else { dest.writeInt(0); } int currentPos = dest.dataPosition(); dest.setDataPosition(validDataPos); dest.writeBooleanArray(validDataList); // Real array. dest.setDataPosition(currentPos); } /** Interface to allow Identity to be written and restored from a Parcel. */ public static final Parcelable.Creator<Identity> CREATOR = new Parcelable.Creator<Identity>() { public Identity createFromParcel(Parcel in) { return new Identity(in); } public Identity[] newArray(int size) { return new Identity[size]; } }; } diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index a66de7f..d9bdb67 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,737 +1,804 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; 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; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); public static final String KEY_DATA = "data"; - private static final String KEY_DATA_CHATABLE_IDENTITIES = "chatable_data"; - /** * 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 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; } /** * - * Gets all third party identities and adds the mobile and pc identities + * 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 identities pc and mobile. If the retrieval failed the list will + * the 360 identity mobile. If the retrieval failed the list will * be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyIdentities() { if ((mMyIdentityList.size() == 0) && ( (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) > MIN_REQUEST_INTERVAL)) { sendGetAvailableIdentitiesRequest(); } return mAvailableIdentityList; } + /** + * + * 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>(); + + // checking each identity for its chat capability and adding it to the + // list if it does + for (int i = 0; i < mMyIdentityList.size(); 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; + } + } + } + + return chatableIdentities; + } + private void sendGetMyIdentitiesRequest() { Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); } private void sendGetAvailableIdentitiesRequest() { Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ // private void addUiGetAvailableIdentities() { // LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to fetch the current user's identities. * */ // private void addUiGetMyIdentities() { // LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); // emptyUiRequestQueue(); // addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); // } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * TODO: remove parameter as soon as branch ui-refresh is merged. * * @param data Bundled request data. * */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { - switch (mState) { - case IDLE: - LogUtils.logW("IDLE should never happend"); - break; - case FETCHING_IDENTITIES: - case GETTING_MY_IDENTITIES: - case GETTING_MY_CHATABLE_IDENTITIES: - handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); - break; - case SETTING_IDENTITY_CAPABILITY_STATUS: - handleSetIdentityCapabilityStatus(resp.mDataTypes); - break; - case VALIDATING_IDENTITY_CREDENTIALS: - handleValidateIdentityCredentials(resp.mDataTypes); - break; + switch (resp.mDataTypes.get(0).type()) { + 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: + handleSetIdentityCapabilityStatus(resp.mDataTypes); + break; + case BaseDataType.STATUS_MSG_DATA_TYPE: + handleValidateIdentityCredentials(resp.mDataTypes); + break; default: - LogUtils.logW("default should never happend"); + LogUtils.logW("DEFAULT should never happened."); break; } } } /** * 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: - addUiGetAvailableIdentities(); + sendGetAvailableIdentitiesRequest(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); - addUiGetMyIdentities(); + 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 handleServerGetAvailableIdentitiesResponse(List<BaseDataType> data) { - Bundle bu = null; + private void handleGetAvailableIdentitiesResponse(List<BaseDataType> data) { LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE, data); + if (errorStatus == ServiceStatus.SUCCESS) { - mAvailableIdentityList.clear(); - for (BaseDataType item : data) { - if (item.type() == BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE) { - mAvailableIdentityList.add((Identity)item); - } else { - completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); - return; - } - } - bu = new Bundle(); - if (mState == State.GETTING_MY_IDENTITIES - || (mState == State.GETTING_MY_CHATABLE_IDENTITIES)) { - // store local copy of my identities - makeChatableIdentitiesCache(mAvailableIdentityList); - bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); - } - bu.putParcelableArrayList(KEY_DATA, mAvailableIdentityList); + synchronized (mAvailableIdentityList) { + mAvailableIdentityList.clear(); + + for (BaseDataType item : data) { + mAvailableIdentityList.add((Identity)item); + } + } } - LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse completw UI req"); - completeUiRequest(errorStatus, bu); - newState(State.IDLE); + + 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) { + // create mobile identity to support 360 chat + IdentityCapability iCapability = new IdentityCapability(); + iCapability.mCapability = IdentityCapability.CapabilityID.chat; + iCapability.mValue = new Boolean(true); + ArrayList<IdentityCapability> capabilities = + new ArrayList<IdentityCapability>(); + capabilities.add(iCapability); + + Identity mobileIdentity = new Identity(); + mobileIdentity.mNetwork = "mobile"; + mobileIdentity.mName = "Vodafone"; + mobileIdentity.mCapabilities = capabilities; + // end: create mobile identity to support 360 chat + + synchronized (mAvailableIdentityList) { + mMyIdentityList.clear(); + + for (BaseDataType item : data) { + mMyIdentityList.add((Identity)item); + } + mMyIdentityList.add(mobileIdentity); + } + } + + 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.type() == 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 handleSetIdentityCapabilityStatus(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.type() == 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); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } /** * * 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(); addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); } } /** * 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, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } } diff --git a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java index 9e1d42a..7d58677 100644 --- a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java +++ b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java @@ -1,495 +1,498 @@ /* * 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.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 data byte array containing Hessian encoded data * @param type Event type * @return List of BaseDataType items parsed from Hessian data * @throws IOException */ public List<BaseDataType> decodeHessianByteArray(byte[] data, Request.Type type, boolean isZipped) 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); } List<BaseDataType> mBaseDataTypeList = null; mMicroHessianInput.init(is); LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); try { mBaseDataTypeList = decodeResponse(is, type); } catch (IOException e) { LogUtils.logE("HessianDecoder.decodeHessianByteArray() " + "IOException during decodeResponse", e); } CloseUtils.close(bis); CloseUtils.close(is); return mBaseDataTypeList; } @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; } } /** * TODO: we cast every response to a Map, losing e.g. push event "c0" which * only contains a string - to fix * * @param is * @param type * @return * @throws IOException */ @SuppressWarnings("unchecked") private List<BaseDataType> decodeResponse(InputStream is, Request.Type type) throws IOException { boolean usesReplyTag = false; List<BaseDataType> mResultList = 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(); zybErr.errorType = mMicroHessianInput.readFault().errString(); mResultList.add(zybErr); return mResultList; } // 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(mResultList, is, tag); return mResultList; } // 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); decodeResponseByRequestType(mResultList, hash, type); } else { // if we have a common request 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); mResultList.add(auth.createFromHashtable(authHash)); } else if (map.containsKey(KEY_CONTACT_LIST)) { // contact list getContacts(mResultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); } 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) { mResultList.add(UserProfile.createFromHashtable(obj)); } } else if (map.containsKey(KEY_USER_PROFILE)) { Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map .get(KEY_USER_PROFILE); mResultList.add(UserProfile.createFromHashtable(userProfileHash)); } else if ((map.containsKey(KEY_IDENTITY_LIST)) || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { + int mType = 0; Vector<Hashtable<String, Object>> idcap = null; if (map.containsKey(KEY_IDENTITY_LIST)) { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); + mType = BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE; } else { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); + mType = BaseDataType.MY_IDENTITY_DATA_TYPE; } for (Hashtable<String, Object> obj : idcap) { - Identity id = new Identity(); + Identity id = new Identity(mType); mResultList.add(id.createFromHashtable(obj)); } } 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) { mResultList.add(ActivityItem.createFromHashtable(obj)); } } } if (usesReplyTag) { is.read(); // read the last 'z' } return mResultList; } 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); } private void decodeResponseByRequestType(List<BaseDataType> clist, Hashtable<String, Object> hash, Request.Type type) { switch (type) { case CONTACT_CHANGES_OR_UPDATES: // create ContactChanges ContactChanges contChanges = new ContactChanges(); contChanges = contChanges.createFromHashtable(hash); clist.add(contChanges); break; case ADD_CONTACT: case SIGN_UP: clist.add(Contact.createFromHashtable(hash)); break; case RETRIEVE_PUBLIC_KEY: // AA define new object type clist.add(PublicKeyDetails.createFromHashtable(hash)); break; case FRIENDSHIP_REQUEST: 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); break; case CONTACT_DETAIL_DELETE: ContactDetailDeletion cdel = new ContactDetailDeletion(); clist.add(cdel.createFromHashtable(hash)); break; case USER_INVITATION: // Not currently supported. break; case CONTACT_GROUP_RELATION_LIST: ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); groupRelationList.populateFromHashtable(hash); clist.add(groupRelationList); break; case CONTACT_GROUP_RELATIONS: ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); groupRelationsList.populateFromHashtable(hash); clist.add(groupRelationsList); break; case GROUP_LIST: ItemList zyblist = new ItemList(ItemList.Type.group_privacy); zyblist.populateFromHashtable(hash); clist.add(zyblist); break; case ITEM_LIST_OF_LONGS: ItemList listOfLongs = new ItemList(ItemList.Type.long_value); listOfLongs.populateFromHashtable(hash); clist.add(listOfLongs); break; case STATUS_LIST: ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); zybstatlist.populateFromHashtable(hash); clist.add(zybstatlist); 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); } break; case EXPECTING_STATUS_ONLY: StatusMsg statMsg = new StatusMsg(); clist.add(statMsg.createFromHashtable(hash)); break; case STATUS: StatusMsg s = new StatusMsg(); s.mStatus = true; clist.add(s); break; case PRESENCE_LIST: PresenceList mPresenceList = new PresenceList(); mPresenceList.createFromHashtable(hash); clist.add(mPresenceList); break; case PUSH_MSG: // parse content of RPG Push msg parsePushMessage(clist, hash); break; case CREATE_CONVERSATION: Conversation mConversation = new Conversation(); mConversation.createFromHashtable(hash); clist.add(mConversation); break; default: LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" + type.name() + "]"); } } 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
3b578603322ca5e7db37784b73f5138cab291dd5
Review comments for PAND-1483
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 5f4f026..6991a95 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -286,517 +286,521 @@ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, 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: setRunNow(); } } @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++; } } if (mUsers.size() > 0) { 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 + "]"); UiAgent uiAgent = mEventCallback.getUiAgent(); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { uiAgent.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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { Presence.setMyAvailability((Hashtable<String, String>)data); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); break; case CREATE_CONVERSATION: if (data != null) { List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; case SEND_CHAT_MESSAGE: if (data != null) { 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); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); } } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } private void initSetMyAvailabilityRequest(User myself) { if (myself == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !canRun()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the state of the engine. Also displays the login notification if * necessary. * * @param accounts */ public void setMyAvailability(Hashtable<String, String> myselfPresence) { if (myselfPresence == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with:" + myselfPresence); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), myselfPresence); Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values for myself myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } 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); } } } /** * 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. */ private void addAsContactSyncObserver() { if (EngineManager.getInstance() != null && EngineManager.getInstance().getContactSyncEngine() != null) { EngineManager.getInstance().getContactSyncEngine().addEventCallback(this); mContObsAdded = true; LogUtils.logD("ActivityEngine contactSync observer added."); } else { LogUtils.logE("ActivityEngine can't add to contactSync observers."); } } @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { LogUtils.logD("PresenceEngine onContactSyncStateChange called."); } @Override public void onProgressEvent(State currentState, int percent) { if (percent == 100) { switch (currentState) { case FETCHING_SERVER_CONTACTS: LogUtils .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_CONTACTS is done"); // mDownloadServerContactsComplete = true; // break; // case SYNCING_SERVER_ME_PROFILE: // LogUtils // .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_ME_PROFILE is done"); // mDownloadMeProfileComplete = true; // break; default: // nothing to do now break; } } } @Override public void onSyncComplete(ServiceStatus status) { LogUtils.logD("PresenceEngine onSyncComplete called."); } @Override public void onConnectionStateChanged(int state) { switch (state) { case STATE_CONNECTED: getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } - public void setMyAvailability() { + /** + * 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()); } }
360/360-Engine-for-Android
25d124412704e300d8d0a2168d944f38ee5bae15
added new requests to IdentityEngine to replace the traditional ui requests
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 4a8f506..4fad12e 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,715 +1,747 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> 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; + private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ - private final ArrayList<Identity> mAvailableIdentityList = new ArrayList<Identity>(); + private ArrayList<Identity> mAvailableIdentityList; /** List array of Identities retrieved from Server. */ - private final ArrayList<Identity> mMyIdentityList = new ArrayList<Identity>(); + private ArrayList<Identity> mMyIdentityList; /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** Definitions for expected data-types returned from Server. */ private static final String TYPE_IDENTITY = "Identity"; private static final String TYPE_STATUS_MSG = "StatusMsg"; public static final String KEY_DATA = "data"; private static final String KEY_DATA_CHATABLE_IDENTITIES = "chatable_data"; private static final String LOG_STATUS_MSG = TYPE_STATUS_MSG + ": "; /** * 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 the user is currently signed up for. * - * @return A list of 3rd party identities the user is signed in to or null - * if there was something wrong retrieving the identities. + * @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; } - + /** * * Gets all third party identities and adds the mobile and pc identities * from 360 to them. * * @return A list of all 3rd party identities the user is signed in to plus - * the 360 identities pc and mobile. + * the 360 identities pc and mobile. If the retrieval failed the list will + * be empty. * */ public ArrayList<Identity> getMy360AndThirdPartyIdentities() { + if ((mMyIdentityList.size() == 0) && ( + (System.currentTimeMillis() - mLastAvailableIdentitiesRequestTimestamp) + > MIN_REQUEST_INTERVAL)) { + sendGetAvailableIdentitiesRequest(); + } + return mAvailableIdentityList; } + private void sendGetMyIdentitiesRequest() { + Identities.getMyIdentities(this, prepareStringFilter(getIdentitiesFilter())); + } + + private void sendGetAvailableIdentitiesRequest() { + Identities.getAvailableIdentities(this, prepareStringFilter(getIdentitiesFilter())); + } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ - public void addUiGetAvailableIdentities() { - LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); - emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); - } +// private void addUiGetAvailableIdentities() { +// LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); +// emptyUiRequestQueue(); +// addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); +// } /** * Add request to fetch the current user's identities. * */ - public void addUiGetMyIdentities() { - LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); - emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); - } +// private void addUiGetMyIdentities() { +// LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); +// emptyUiRequestQueue(); +// addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); +// } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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 GET_AVAILABLE_IDENTITIES: executeGetAvailableIdentitiesRequest(data); break; case GET_MY_IDENTITIES: executeGetMyIdentitiesRequest(data); break; case VALIDATE_IDENTITY_CREDENTIALS: executeValidateIdentityCredentialsRequest(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); executeSetIdentityStatusRequest(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * TODO: remove parameter as soon as branch ui-refresh is merged. * * @param data Bundled request data. * */ private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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_CAPABILITY_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); } } /** * Sends a getAvailableIdentities request to the backend. * * TODO: remove the parameter as soon as we have merged with the ui-refresh * branch. * * @param data Bundled request data. */ private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushResponse(evt.mMessageType); } else { switch (mState) { case IDLE: LogUtils.logW("IDLE should never happend"); break; case FETCHING_IDENTITIES: case GETTING_MY_IDENTITIES: case GETTING_MY_CHATABLE_IDENTITIES: handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); break; case SETTING_IDENTITY_CAPABILITY_STATUS: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case VALIDATING_IDENTITY_CREDENTIALS: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("default should never happend"); break; } } } /** * 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: addUiGetAvailableIdentities(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); addUiGetMyIdentities(); 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 handleServerGetAvailableIdentitiesResponse(List<BaseDataType> data) { Bundle bu = null; LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(TYPE_IDENTITY, data); if (errorStatus == ServiceStatus.SUCCESS) { mAvailableIdentityList.clear(); for (BaseDataType item : data) { if (TYPE_IDENTITY.equals(item.name())) { mAvailableIdentityList.add((Identity)item); LogUtils.logD("Identity: " + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mState == State.GETTING_MY_IDENTITIES || (mState == State.GETTING_MY_CHATABLE_IDENTITIES)) { // store local copy of my identities makeChatableIdentitiesCache(mAvailableIdentityList); bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); } bu.putParcelableArrayList(KEY_DATA, mAvailableIdentityList); } LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse completw UI req"); completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } 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 handleSetIdentityCapabilityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } /** * * 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(); addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); } } /** * 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, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } }
360/360-Engine-for-Android
34ed0f7c5da6e71a2c6c93debf2820b364e669c4
now using the method stubbed method that Rudy added.
diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index 589f2c8..4150c19 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,316 +1,313 @@ /* * 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.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 - // TODO: Need to construct "status" from identities and utility method - Hashtable<String, String> status = new Hashtable<String, String>(); - status.put("google", "online"); - status.put("microsoft", "online"); - status.put("mobile", "online"); - status.put("facebook.com", "online"); - status.put("hyves.nl", "online"); + // 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) { 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); } } 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 c0d7330..c8da831 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,780 +1,809 @@ /* * 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.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; 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 10 minutes. **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private long mNextRuntime = -1; 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; /** * * @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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (!canRun()) { mNextRuntime = -1; LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" + mNextRuntime); return mNextRuntime; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { 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 (mNextRuntime == -1) { LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!"); return 0; } else { return mNextRuntime; } } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + mNextRuntime + "]"); 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) { if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) { if (canRun()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setNextRuntime(); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20; } } } else { 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); } private void setNextRuntime() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again in [" + (CHECK_FREQUENCY / (1000 * 60)) + "] minutes"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY; } private void setRunNow() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW"); mNextRuntime = 0; } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setNextRuntime(); } else { setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } /*** * 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); } @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: setRunNow(); } } @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++; } } if (mUsers.size() > 0) { 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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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()) { 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 SET_MY_AVAILABILITY_FOR_COMMUNITY: Presence.setMyAvailabilityForCommunity(); 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); setNextRuntime(); } /** * 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()) { 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); + // Get presence list constructed from identities + Hashtable<String, String> presences = getPresencesForStatus(status); + if(presences == null) { + LogUtils.logW("setMyAvailability() Ignoring setMyAvailability request because there are no identities!"); + return; + } User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), - presenceList); + presences); // 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, presences); } /** * 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) { switch (state) { case STATE_CONNECTED: getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } public 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().getMy360AndThirdPartyIdentities(); + + 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; + } }
360/360-Engine-for-Android
ff49e93e42fed10194911925974c570488c237a8
breaky breaky, identity refaky
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 8b52b79..7248cdf 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,699 +1,699 @@ /* * 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.IdentityCapability.CapabilityID; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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 { +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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ - private final ArrayList<Identity> mIdentityList = new ArrayList<Identity>(); + private final ArrayList<Identity> mAvailableIdentityList = new ArrayList<Identity>(); + + /** List array of Identities retrieved from Server. */ + private final ArrayList<Identity> mMyIdentityList = new ArrayList<Identity>(); /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** Definitions for expected data-types returned from Server. */ private static final String TYPE_IDENTITY = "Identity"; private static final String TYPE_STATUS_MSG = "StatusMsg"; public static final String KEY_DATA = "data"; private static final String KEY_DATA_CHATABLE_IDENTITIES = "chatable_data"; private static final String LOG_STATUS_MSG = TYPE_STATUS_MSG + ": "; - /** - * Generate Map containing boolean capability filters for supplied Bundle. - * - * @param filter Bundle containing filter. - * @return Map containing set of capabilities. - */ - private static Map<String, Object> prepareBoolFilter(Bundle filter) { - Map<String, Object> objectFilter = null; - if (filter != null && (filter.keySet().size() > 0)) { - objectFilter = new Hashtable<String, Object>(); - 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; - } - /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; } - + + /** - * 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() { - } - - /** - * Process a response received from Server. The response is handled - * according to the current IdentityEngine state. + * Gets all third party identities the user is currently signed up for. * - * @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) { - PushEvent evt = (PushEvent)resp.mDataTypes.get(0); - handlePushRequest(evt.mMessageType); - } else { - switch (mState) { - case IDLE: - LogUtils.logW("IDLE should never happend"); - break; - case FETCHING_IDENTITIES: - case GETTING_MY_IDENTITIES: - case GETTING_MY_CHATABLE_IDENTITIES: - handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); - break; - case SETTING_IDENTITY_CAPABILITY_STATUS: - handleSetIdentityCapabilityStatus(resp.mDataTypes); - break; - case VALIDATING_IDENTITY_CREDENTIALS: - handleValidateIdentityCredentials(resp.mDataTypes); - break; - default: - LogUtils.logW("default should never happend"); - break; - } - } - } - - /** - * Handle Status or Timeline Activity change Push message + * @return A list of 3rd party identities the user is signed in to or null + * if there was something wrong retrieving the identities. * - * @param evt Push message type (Status change or Timeline change). */ - private void handlePushRequest(PushMessageTypes evt) { - LogUtils.logD("IdentityEngine handlePushRequest"); - switch (evt) { - case IDENTITY_NETWORK_CHANGE: - addUiFetchIdentities(); - break; - case IDENTITY_CHANGE: - // TODO padma - break; - default: - // do nothing - } + public ArrayList<Identity> getMyThirdPartyIdentities() { + return mMyIdentityList; } /** - * Issue any outstanding UI request. * - * @param requestType Request to be issued. - * @param dara Data associated with the request. + * Gets all third party identities and adds the mobile and pc identities + * from 360 to them. + * + * @return A list of all 3rd party identities the user is signed in to plus + * the 360 identities pc and mobile. + * */ - @Override - protected void processUiRequest(ServiceUiRequest requestType, Object data) { - LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); - switch (requestType) { - case FETCH_IDENTITIES: - startGetAvailableIdentities(data); - break; - case GET_MY_IDENTITIES: - startGetMyIdentities(data); - break; - case GET_MY_CHATABLE_IDENTITIES: - startGetMyChatableIdentities(); - break; - case VALIDATE_IDENTITY_CREDENTIALS: - startValidateIdentityCredentials(data); - break; - case SET_IDENTITY_CAPABILITY_STATUS: - // changed the method called - // startSetIdentityCapabilityStatus(data); - startSetIdentityStatus(data); - break; - default: - completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); - break; - } + public ArrayList<Identity> getMy360AndThirdPartyIdentities() { + } - - /** - * 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(); - } - } - + + + + /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ - public void addUiFetchIdentities() { - LogUtils.logD("IdentityEngine.addUiFetchIdentities()"); + public void addUiGetAvailableIdentities() { + LogUtils.logD("IdentityEngine.addUiGetAvailableIdentities()"); emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.FETCH_IDENTITIES, getIdentitiesFilter()); + addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); + } + + /** + * Add request to fetch the current user's identities. + * + */ + public void addUiGetMyIdentities() { + LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); + emptyUiRequestQueue(); + addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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); } /** - * Add request to fetch the current user's identities. - * - */ - public void addUiGetMyIdentities() { - LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); - emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); - } - - /** - * Change current IdentityEngine state. + * Issue any outstanding UI request. * - * @param newState new state. + * @param requestType Request to be issued. + * @param dara Data associated with the request. */ - private void newState(State newState) { - State oldState = mState; - synchronized (mMutex) { - if (newState == mState) { - return; - } - mState = newState; + @Override + protected void processUiRequest(ServiceUiRequest requestType, Object data) { + LogUtils.logD("IdentityEngine.processUiRequest() - reqID = " + requestType); + switch (requestType) { + case GET_AVAILABLE_IDENTITIES: + executeGetAvailableIdentitiesRequest(data); + break; + case GET_MY_IDENTITIES: + executeGetMyIdentitiesRequest(data); + break; + case VALIDATE_IDENTITY_CREDENTIALS: + executeValidateIdentityCredentialsRequest(data); + break; + case SET_IDENTITY_CAPABILITY_STATUS: + // changed the method called + // startSetIdentityCapabilityStatus(data); + executeSetIdentityStatusRequest(data); + break; + default: + completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); + break; } - LogUtils.logV("IdentityEngine.newState: " + oldState + " -> " + mState); } - + /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ - private void startGetMyIdentities(Object data) { + private void executeGetMyIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } - /** - * Issue request to retrieve 'My chat-able' Identities. The request is - * filtered to retrieve only identities with the chat capability enabled. - * (Request is not issued if there is currently no connectivity). - */ - private void startGetMyChatableIdentities() { - if (!isConnected()) { - return; - } - Bundle filter = new Bundle(); - ArrayList<String> l = new ArrayList<String>(); - l.add(IdentityCapability.CapabilityID.chat.name()); - filter.putStringArrayList("capability", l); - - newState(State.GETTING_MY_CHATABLE_IDENTITIES); - if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter(filter)))) { - completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); - } - } - - /** * 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 startSetIdentityStatus(Object data) { + private void executeSetIdentityStatusRequest(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_CAPABILITY_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 startValidateIdentityCredentials(Object 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 retrieve available Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ - private void startGetAvailableIdentities(Object data) { + private void executeGetAvailableIdentitiesRequest(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); - mIdentityList.clear(); + mAvailableIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { 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) { + PushEvent evt = (PushEvent)resp.mDataTypes.get(0); + handlePushResponse(evt.mMessageType); + } else { + switch (mState) { + case IDLE: + LogUtils.logW("IDLE should never happend"); + break; + case FETCHING_IDENTITIES: + case GETTING_MY_IDENTITIES: + case GETTING_MY_CHATABLE_IDENTITIES: + handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); + break; + case SETTING_IDENTITY_CAPABILITY_STATUS: + handleSetIdentityCapabilityStatus(resp.mDataTypes); + break; + case VALIDATING_IDENTITY_CREDENTIALS: + handleValidateIdentityCredentials(resp.mDataTypes); + break; + default: + LogUtils.logW("default should never happend"); + break; + } + } + } + + /** + * 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: + addUiGetAvailableIdentities(); + break; + case IDENTITY_CHANGE: + // TODO padma + 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 handleServerGetAvailableIdentitiesResponse(List<BaseDataType> data) { Bundle bu = null; LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(TYPE_IDENTITY, data); if (errorStatus == ServiceStatus.SUCCESS) { - mIdentityList.clear(); + mAvailableIdentityList.clear(); for (BaseDataType item : data) { if (TYPE_IDENTITY.equals(item.name())) { - mIdentityList.add((Identity)item); + mAvailableIdentityList.add((Identity)item); LogUtils.logD("Identity: " + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mState == State.GETTING_MY_IDENTITIES || (mState == State.GETTING_MY_CHATABLE_IDENTITIES)) { // store local copy of my identities - makeChatableIdentitiesCache(mIdentityList); + makeChatableIdentitiesCache(mAvailableIdentityList); bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); } - bu.putParcelableArrayList(KEY_DATA, mIdentityList); + bu.putParcelableArrayList(KEY_DATA, mAvailableIdentityList); } LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse completw UI req"); completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } 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 handleSetIdentityCapabilityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } - - /** - * Add request to fetch the current user's 'chat-able' identities. This will - * automatically apply set of filters applied to GetMyIdentities API call to - * get Identities with chat capability. - * - * Note: Only called from tests. - */ - public void getMyChatableIdentities() { - LogUtils.logD("IdentityEngine.getMyChatableIdentities()"); - if (mMyChatableIdentityList != null) { - Bundle bu = new Bundle(); - bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); - completeUiRequest(ServiceStatus.SUCCESS, bu); - return; - } - - addUiRequestToQueue(ServiceUiRequest.GET_MY_CHATABLE_IDENTITIES, null); - } 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(); + addUiRequestToQueue(ServiceUiRequest.GET_AVAILABLE_IDENTITIES, getIdentitiesFilter()); + } + } + + /** + * 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, Object> prepareBoolFilter(Bundle filter) { + Map<String, Object> objectFilter = null; + if (filter != null && (filter.keySet().size() > 0)) { + objectFilter = new Hashtable<String, Object>(); + 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; + } + } diff --git a/src/com/vodafone360/people/service/ServiceUiRequest.java b/src/com/vodafone360/people/service/ServiceUiRequest.java index b35bae8..3221220 100644 --- a/src/com/vodafone360/people/service/ServiceUiRequest.java +++ b/src/com/vodafone360/people/service/ServiceUiRequest.java @@ -1,263 +1,263 @@ /* * 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 */ - FETCH_IDENTITIES, + 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, /* * 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 a4afa34..a8a7a87 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.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.interfaces; import java.util.Hashtable; import android.os.Bundle; import android.os.Handler; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; 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(); /*** * Begins the process of retrieving Third party Accounts that the user is * already registered with 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 fetchMyIdentities(Bundle data); + //void fetchMyIdentities(Bundle data); /*** * 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); + //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); /*** * Alter the current Social Network availability state and send it to the * server. * * @param myself is the wrapper for the own presence state, can be retrieved * from PresenceTable.getUserByLocalContactId(long * meProfileLocalContactId). */ void setAvailability(Hashtable<String, String> myself); /*** * 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 1c935c9..1807754 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,415 +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.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.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback; 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#fetchAvailableIdentities(Bundle) */ - @Override +/* @Override public void fetchAvailableIdentities(Bundle data) { - EngineManager.getInstance().getIdentityEngine().addUiFetchIdentities(); - } + EngineManager.getInstance().getIdentityEngine().addUiGetAvailableIdentities(); + }*/ /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchMyIdentities(Bundle) */ - @Override + /*@Override public void fetchMyIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(); - } + }*/ /*** * @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(Hashtable) */ @Override public void setAvailability(Hashtable<String, String> myself) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(myself); } /*** * @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
459e3e007f54871dab9e0e6a34fdde45d438ded6
Simplified code a little, now just has old behaviour with minor cleanup.
diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index f28ee66..589f2c8 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,325 +1,316 @@ /* * 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.ContactSummary.OnlineStatus; 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 - // TODO: this hard code needs change, must filter the identities - // info by VCARD.IMADRESS + // TODO: Need to construct "status" from identities and utility method Hashtable<String, String> status = new Hashtable<String, String>(); status.put("google", "online"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("facebook.com", "online"); status.put("hyves.nl", "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) { 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); } } 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); } } - - /** - * @param input - * @return - */ - public static boolean notNullOrBlank(String input) { - return (input != null) && input.length() > 0; - } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 33f461e..c0d7330 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,843 +1,780 @@ /* * 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.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.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; 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, - IContactSyncObserver, ITcpConnectionListener { + ITcpConnectionListener { /** Check every 10 minutes. **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private long mNextRuntime = -1; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private List<TimelineSummaryItem> mFailedMessagesList; // (to, network) - - private boolean mContObsAdded; /** 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; /** * * @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>(); - addAsContactSyncObserver(); } @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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { - - if (!mContObsAdded) { - addAsContactSyncObserver(); - } - if (!canRun()) { mNextRuntime = -1; LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" + mNextRuntime); return mNextRuntime; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { 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 (mNextRuntime == -1) { LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!"); return 0; } else { return mNextRuntime; } } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + mNextRuntime + "]"); 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) { if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) { if (canRun()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setNextRuntime(); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20; } } } else { 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); } private void setNextRuntime() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again in [" + (CHECK_FREQUENCY / (1000 * 60)) + "] minutes"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY; } private void setRunNow() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW"); mNextRuntime = 0; } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setNextRuntime(); } else { setPresenceOffline(); - mContObsAdded = false; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } /*** * 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); } @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: setRunNow(); } } @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++; } } if (mUsers.size() > 0) { 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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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()) { 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: - if (data != null) { - Presence.setMyAvailability(((OnlineStatus)data).toString()); - completeUiRequest(ServiceStatus.SUCCESS, null); - setNextRuntime(); - } + Presence.setMyAvailability((Hashtable<String, String>)data); break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: - if (data != null) { - Presence.setMyAvailabilityForCommunity(); - completeUiRequest(ServiceStatus.SUCCESS, null); - setNextRuntime(); - } + Presence.setMyAvailabilityForCommunity(); + break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); - completeUiRequest(ServiceStatus.SUCCESS, null); - setNextRuntime(); break; - case CREATE_CONVERSATION: - if (data != null) { - List<String> tos = ((ChatMessage)data).getTos(); - LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " - + tos); - Chat.startChat(tos); - // Request to update the UI - completeUiRequest(ServiceStatus.SUCCESS, null); - // Request to update the UI - setNextRuntime(); - } + List<String> tos = ((ChatMessage)data).getTos(); + LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + + tos); + Chat.startChat(tos); break; case SEND_CHAT_MESSAGE: - if (data != null) { - 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); - // Request to update the UI - completeUiRequest(ServiceStatus.SUCCESS, null); - // Request to update the UI - setNextRuntime(); - } + 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); + setNextRuntime(); } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } - - private void initSetMyAvailabilityRequest(User myself) { - if (myself == 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 ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && + if ((me.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !canRun()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); - for (NetworkPresence presence : myself.getPayload()) { + for (NetworkPresence presence : me.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values - myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); + me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); - updateMyPresenceInDatabase(myself); + 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 = new Hashtable<String, String>(); - // 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); } } } - - /** - * 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. - */ - private void addAsContactSyncObserver() { - if (EngineManager.getInstance() != null - && EngineManager.getInstance().getContactSyncEngine() != null) { - EngineManager.getInstance().getContactSyncEngine().addEventCallback(this); - mContObsAdded = true; - LogUtils.logD("ActivityEngine contactSync observer added."); - } else { - LogUtils.logE("ActivityEngine can't add to contactSync observers."); - } - } - - @Override - public void onContactSyncStateChange(Mode mode, State oldState, State newState) { - LogUtils.logD("PresenceEngine onContactSyncStateChange called."); - } - - @Override - public void onProgressEvent(State currentState, int percent) { - if (percent == 100) { - switch (currentState) { - case FETCHING_SERVER_CONTACTS: - LogUtils - .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_CONTACTS is done"); - // mDownloadServerContactsComplete = true; - // break; - // case SYNCING_SERVER_ME_PROFILE: - // LogUtils - // .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_ME_PROFILE is done"); - // mDownloadMeProfileComplete = true; - // break; - default: - // nothing to do now - break; - } - } - } - - @Override - public void onSyncComplete(ServiceStatus status) { - LogUtils.logD("PresenceEngine onSyncComplete called."); - } @Override public void onConnectionStateChanged(int state) { switch (state) { case STATE_CONNECTED: getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } public void setMyAvailability() { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); } } diff --git a/src/com/vodafone360/people/service/io/api/Presence.java b/src/com/vodafone360/people/service/io/api/Presence.java index 7f3bccc..d9a71ac 100644 --- a/src/com/vodafone360/people/service/io/api/Presence.java +++ b/src/com/vodafone360/people/service/io/api/Presence.java @@ -1,102 +1,115 @@ /* * 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.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; + } + 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(); } public static void setMyAvailabilityForCommunity() { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.setMyAvailabilityForCommunity() No session, so return"); return; } } } diff --git a/src/com/vodafone360/people/utils/HardcodedUtils.java b/src/com/vodafone360/people/utils/HardcodedUtils.java index 4f3fe72..c76e198 100644 --- a/src/com/vodafone360/people/utils/HardcodedUtils.java +++ b/src/com/vodafone360/people/utils/HardcodedUtils.java @@ -1,65 +1,65 @@ /* * 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.Hashtable; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.NetworkPresence; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; /** * @author timschwerdtner * Collection of hardcoded and duplicated code as a first step for refactoring. */ public class HardcodedUtils { -// /** -// * To be used with IPeopleService.setAvailability until identity handling -// * has been refactored. -// * @param Desired availability state -// * @return A hashtable for the set availability call -// */ -// public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) { -// Hashtable<String, String> availability = new Hashtable<String, String>(); -// -// LogUtils.logD("Setting Availability to: " + onlineStatus.toString()); -// // TODO: REMOVE HARDCODE setting everything possible to currentStatus -// availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString()); -// availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString()); -// -// return availability; -// } + /** + * To be used with IPeopleService.setAvailability until identity handling + * has been refactored. + * @param Desired availability state + * @return A hashtable for the set availability call + */ + public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) { + Hashtable<String, String> availability = new Hashtable<String, String>(); + + LogUtils.logD("Setting Availability to: " + onlineStatus.toString()); + // TODO: REMOVE HARDCODE setting everything possible to currentStatus + availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString()); + + return availability; + } /** * The static list of supported TPC accounts. */ public static final int[] THIRD_PARTY_CHAT_ACCOUNTS = new int[]{SocialNetwork.FACEBOOK_COM.ordinal(), SocialNetwork.GOOGLE.ordinal(), SocialNetwork.HYVES_NL.ordinal(), SocialNetwork.MICROSOFT.ordinal()}; }
360/360-Engine-for-Android
d5480d7f1dbc3e6d2ef39daaf1e393b49493a34d
PAND-1689 EVO Crash
diff --git a/src/com/vodafone360/people/service/transport/ConnectionManager.java b/src/com/vodafone360/people/service/transport/ConnectionManager.java index 36730ee..a83e6b3 100644 --- a/src/com/vodafone360/people/service/transport/ConnectionManager.java +++ b/src/com/vodafone360/people/service/transport/ConnectionManager.java @@ -1,244 +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) { - Toast toast = Toast.makeText(mService.getApplicationContext(), - R.string.ContactProfile_no_connection, Toast.LENGTH_LONG); - toast.show(); + showToast(R.string.ContactProfile_no_connection); } - + mConnectionState = state; - for (ITcpConnectionListener listener: mListeners) { + 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. + * 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. + * 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
724bd8e7b886ee0adf4fd69ac662ae699de545f7
New availability method now used NetworkPresence as the argument
diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index 74d077e..f28ee66 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,325 +1,325 @@ /* * 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.ContactSummary.OnlineStatus; 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 // TODO: this hard code needs change, must filter the identities // info by VCARD.IMADRESS Hashtable<String, String> status = new Hashtable<String, String>(); status.put("google", "online"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("facebook.com", "online"); status.put("hyves.nl", "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) { 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); } } return !ignoredNetworks.isEmpty(); } protected static boolean updateMyPresence(User user, DatabaseHelper dbHelper) { boolean contactsChanged = false; - SQLiteDatabase writableDb = dbHelper.getWritableDatabase(); - if (PresenceTable.updateUser(user, null, writableDb) != PresenceTable.USER_NOTADDED) { + 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); } } /** * @param input * @return */ public static boolean notNullOrBlank(String input) { return (input != null) && input.length() > 0; } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 0634f84..33f461e 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,818 +1,843 @@ /* * 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.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.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; 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.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, IContactSyncObserver, ITcpConnectionListener { /** Check every 10 minutes. **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private long mNextRuntime = -1; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private List<TimelineSummaryItem> mFailedMessagesList; // (to, network) private boolean mContObsAdded; /** 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; /** * * @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>(); addAsContactSyncObserver(); } @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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (!mContObsAdded) { addAsContactSyncObserver(); } if (!canRun()) { mNextRuntime = -1; LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" + mNextRuntime); return mNextRuntime; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { 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 (mNextRuntime == -1) { LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!"); return 0; } else { return mNextRuntime; } } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + mNextRuntime + "]"); 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) { if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) { if (canRun()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setNextRuntime(); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20; } } } else { 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); } private void setNextRuntime() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again in [" + (CHECK_FREQUENCY / (1000 * 60)) + "] minutes"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY; } private void setRunNow() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW"); mNextRuntime = 0; } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setNextRuntime(); } else { setPresenceOffline(); mContObsAdded = false; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } /*** * 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); } @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: setRunNow(); } } @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++; } } if (mUsers.size() > 0) { 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 + "]"); - UiAgent uiAgent = mEventCallback.getUiAgent(); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { - uiAgent.updatePresence(myself.getLocalContactId()); + 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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { Presence.setMyAvailability(((OnlineStatus)data).toString()); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: if (data != null) { Presence.setMyAvailabilityForCommunity(); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); break; case CREATE_CONVERSATION: if (data != null) { List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; case SEND_CHAT_MESSAGE: if (data != null) { 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); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); } } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } private void initSetMyAvailabilityRequest(User myself) { if (myself == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !canRun()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** - * Changes the state of the engine. Also displays the login notification if - * necessary. + * Changes the user's availability and therefore the state of the engine. + * Also displays the login notification if necessary. * - * @param accounts + * @param status Availability to set for all identities we have. */ - public void setMyAvailability(OnlineStatus onlinestatus) { - if (onlinestatus == null) { + 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:"+onlinestatus.toString()); + 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> userPresence = new Hashtable<String, String>(); + Hashtable<String, String> presenceList = new Hashtable<String, String>(); // TODO: Fill up hashtable with identities and online statuses - User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), - userPresence); - Hashtable<String, String> availability = new Hashtable<String, String>(); - for (NetworkPresence presence : myself.getPayload()) { - availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), - OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); - } + User me = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), + presenceList); + // set the DB values for myself - myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); - updateMyPresenceInDatabase(myself); + me.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); + updateMyPresenceInDatabase(me); // set the engine to run now - addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, userPresence); + addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, presenceList); } - public void setMyAvailability(String network, String availability) { - + /** + * 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); } } } /** * 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. */ private void addAsContactSyncObserver() { if (EngineManager.getInstance() != null && EngineManager.getInstance().getContactSyncEngine() != null) { EngineManager.getInstance().getContactSyncEngine().addEventCallback(this); mContObsAdded = true; LogUtils.logD("ActivityEngine contactSync observer added."); } else { LogUtils.logE("ActivityEngine can't add to contactSync observers."); } } @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { LogUtils.logD("PresenceEngine onContactSyncStateChange called."); } @Override public void onProgressEvent(State currentState, int percent) { if (percent == 100) { switch (currentState) { case FETCHING_SERVER_CONTACTS: LogUtils .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_CONTACTS is done"); // mDownloadServerContactsComplete = true; // break; // case SYNCING_SERVER_ME_PROFILE: // LogUtils // .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_ME_PROFILE is done"); // mDownloadMeProfileComplete = true; // break; default: // nothing to do now break; } } } @Override public void onSyncComplete(ServiceStatus status) { LogUtils.logD("PresenceEngine onSyncComplete called."); } @Override public void onConnectionStateChanged(int state) { switch (state) { case STATE_CONNECTED: getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } public void setMyAvailability() { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index 67a4a99..0dbc95b 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,345 +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.interfaces; -import java.util.Hashtable; - import android.os.Bundle; import android.os.Handler; 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.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(); /*** * Begins the process of retrieving Third party Accounts that the user is * already registered with 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 fetchMyIdentities(Bundle data); /*** * 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); - -// /*** -// * Alter the current Social Network availability state and send it to the -// * server. -// * -// * @param myself is the wrapper for the own presence state, can be retrieved -// * from PresenceTable.getUserByLocalContactId(long -// * meProfileLocalContactId). -// */ -// void setAvailability(Hashtable<String, String> myself); /** * Change current global (all identities) availability state. - * @param onlinestatus Availability to set for all identities we have. + * @param status Availability to set for all identities we have. */ - void setAvailability(OnlineStatus onlinestatus); + void setAvailability(OnlineStatus status); /** * Change current availability state for a single network. - * @param network - * @param availability + * @param presence Network-presence to set */ - void setAvailability(String network, String availability); + void setAvailability(NetworkPresence presence); /*** * 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 3674f0e..c80638b 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,425 +1,427 @@ /* * 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.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#fetchAvailableIdentities(Bundle) */ @Override public void fetchAvailableIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiFetchIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchMyIdentities(Bundle) */ @Override public void fetchMyIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(); } /*** * @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(String) + * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(OnlineStatus) */ @Override - public void setAvailability(OnlineStatus onlinestatus) { - EngineManager.getInstance().getPresenceEngine().setMyAvailability(onlinestatus); + public void setAvailability(OnlineStatus status) { + EngineManager.getInstance().getPresenceEngine().setMyAvailability(status); } /*** - * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(String, String) + * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(NetworkPresence) */ @Override - public void setAvailability(String network, String availability) { - EngineManager.getInstance().getPresenceEngine().setMyAvailability(network, availability); + public void setAvailability(NetworkPresence presence) { + EngineManager.getInstance().getPresenceEngine().setMyAvailability(presence); } /*** * @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
6eb99b8775f0166ac7d60d76f426785ab0ee15e1
Minor changes that I missed.
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 7dfa503..0634f84 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -49,782 +49,770 @@ import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.EngineManager.EngineId; 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.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.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, IContactSyncObserver, ITcpConnectionListener { /** Check every 10 minutes. **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private long mNextRuntime = -1; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private List<TimelineSummaryItem> mFailedMessagesList; // (to, network) private boolean mContObsAdded; /** 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; /** * * @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>(); addAsContactSyncObserver(); } @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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (!mContObsAdded) { addAsContactSyncObserver(); } if (!canRun()) { mNextRuntime = -1; LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" + mNextRuntime); return mNextRuntime; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { 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 (mNextRuntime == -1) { LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!"); return 0; } else { return mNextRuntime; } } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + mNextRuntime + "]"); 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) { if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) { if (canRun()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setNextRuntime(); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20; } } } else { 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); } private void setNextRuntime() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again in [" + (CHECK_FREQUENCY / (1000 * 60)) + "] minutes"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY; } private void setRunNow() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW"); mNextRuntime = 0; } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setNextRuntime(); } else { setPresenceOffline(); mContObsAdded = false; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } /*** * 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); } @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: setRunNow(); } } @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++; } } if (mUsers.size() > 0) { 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 + "]"); UiAgent uiAgent = mEventCallback.getUiAgent(); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { uiAgent.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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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.name()); } } 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()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { - Presence.setMyAvailability((String)data); + Presence.setMyAvailability(((OnlineStatus)data).toString()); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } break; case SET_MY_AVAILABILITY_FOR_COMMUNITY: if (data != null) { Presence.setMyAvailabilityForCommunity(); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); break; case CREATE_CONVERSATION: if (data != null) { List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; case SEND_CHAT_MESSAGE: if (data != null) { 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); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); } } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } private void initSetMyAvailabilityRequest(User myself) { if (myself == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !canRun()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } -// /** -// * Changes the state of the engine. Also displays the login notification if -// * necessary. -// * -// * @param accounts -// */ -// public void setMyAvailability(Hashtable<String, String> myselfPresence) { -// if (myselfPresence == null) { -// LogUtils.logE("PresenceEngine setMyAvailability:" -// + " Can't send the setAvailability request due to DB reading errors"); -// return; -// } -// -// LogUtils.logV("PresenceEngine setMyAvailability() called with:" + myselfPresence); -// if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { -// LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); -// return; -// } -// -// User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), -// myselfPresence); -// -// Hashtable<String, String> availability = new Hashtable<String, String>(); -// for (NetworkPresence presence : myself.getPayload()) { -// availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), -// OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); -// } -// // set the DB values for myself -// myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); -// updateMyPresenceInDatabase(myself); -// -// // set the engine to run now -// -// addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); -// } - /** + * Changes the state of the engine. Also displays the login notification if + * necessary. * - * @param availability + * @param accounts */ - public void setMyAvailability(String availability) { - if (TextUtils.isEmpty(availability)) { + public void setMyAvailability(OnlineStatus onlinestatus) { + if (onlinestatus == null) { LogUtils.logE("PresenceEngine setMyAvailability:" - + " Can't my availability using empty availability"); + + " Can't send the setAvailability request due to DB reading errors"); return; } - LogUtils.logV("PresenceEngine setMyAvailability() called with:" + availability); + LogUtils.logV("PresenceEngine setMyAvailability() called with status:"+onlinestatus.toString()); + if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { + LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); + return; + } + + // Get presences + Hashtable<String, String> userPresence = new Hashtable<String, String>(); + + // TODO: Fill up hashtable with identities and online statuses + User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), + userPresence); + + Hashtable<String, String> availability = new Hashtable<String, String>(); + for (NetworkPresence presence : myself.getPayload()) { + availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), + OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); + } + // set the DB values for myself + myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); + updateMyPresenceInDatabase(myself); + + // set the engine to run now - addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); + addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, userPresence); } - + public void setMyAvailability(String network, String availability) { } 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); } } } /** * 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. */ private void addAsContactSyncObserver() { if (EngineManager.getInstance() != null && EngineManager.getInstance().getContactSyncEngine() != null) { EngineManager.getInstance().getContactSyncEngine().addEventCallback(this); mContObsAdded = true; LogUtils.logD("ActivityEngine contactSync observer added."); } else { LogUtils.logE("ActivityEngine can't add to contactSync observers."); } } @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { LogUtils.logD("PresenceEngine onContactSyncStateChange called."); } @Override public void onProgressEvent(State currentState, int percent) { if (percent == 100) { switch (currentState) { case FETCHING_SERVER_CONTACTS: LogUtils .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_CONTACTS is done"); // mDownloadServerContactsComplete = true; // break; // case SYNCING_SERVER_ME_PROFILE: // LogUtils // .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_ME_PROFILE is done"); // mDownloadMeProfileComplete = true; // break; default: // nothing to do now break; } } } @Override public void onSyncComplete(ServiceStatus status) { LogUtils.logD("PresenceEngine onSyncComplete called."); } @Override public void onConnectionStateChanged(int state) { switch (state) { case STATE_CONNECTED: getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } public void setMyAvailability() { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleService.java b/src/com/vodafone360/people/service/interfaces/IPeopleService.java index 6fd9379..67a4a99 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleService.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleService.java @@ -1,344 +1,345 @@ /* * 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.Hashtable; import android.os.Bundle; import android.os.Handler; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; +import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; 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(); /*** * Begins the process of retrieving Third party Accounts that the user is * already registered with 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 fetchMyIdentities(Bundle data); /*** * 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); // /*** // * Alter the current Social Network availability state and send it to the // * server. // * // * @param myself is the wrapper for the own presence state, can be retrieved // * from PresenceTable.getUserByLocalContactId(long // * meProfileLocalContactId). // */ // void setAvailability(Hashtable<String, String> myself); /** * Change current global (all identities) availability state. - * @param availability Availability to set for all identities we have. + * @param onlinestatus Availability to set for all identities we have. */ - void setAvailability(String availability); + void setAvailability(OnlineStatus onlinestatus); /** * Change current availability state for a single network. * @param network * @param availability */ void setAvailability(String network, String availability); /*** * 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 f3e4033..3674f0e 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,424 +1,425 @@ /* * 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.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.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#fetchAvailableIdentities(Bundle) */ @Override public void fetchAvailableIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiFetchIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchMyIdentities(Bundle) */ @Override public void fetchMyIdentities(Bundle data) { EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(); } /*** * @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(String) */ @Override - public void setAvailability(String availability) { - EngineManager.getInstance().getPresenceEngine().setMyAvailability(availability); + public void setAvailability(OnlineStatus onlinestatus) { + EngineManager.getInstance().getPresenceEngine().setMyAvailability(onlinestatus); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#setAvailability(String, String) */ @Override public void setAvailability(String network, String availability) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(network, availability); } /*** * @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 diff --git a/src/com/vodafone360/people/service/io/api/Presence.java b/src/com/vodafone360/people/service/io/api/Presence.java index 6d7fc80..7f3bccc 100644 --- a/src/com/vodafone360/people/service/io/api/Presence.java +++ b/src/com/vodafone360/people/service/io/api/Presence.java @@ -1,100 +1,102 @@ /* * 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.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(); } /** * API to set my availability * * @param engineId ID of presence engine. - * @param availability Availability to set + * @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 apropriate 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(); } public static void setMyAvailabilityForCommunity() { if (LoginEngine.getSession() == null) { LogUtils.logE("Presence.setMyAvailabilityForCommunity() No session, so return"); return; } } }
360/360-Engine-for-Android
700710ea5539979ae3db0a06cbd26ff9bddcc862
Changes following code review.
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index a7052a7..dbd3562 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,958 +1,961 @@ /* * 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 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.LogUtils; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.VersionUtils; import dalvik.system.PathClassLoader; 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.Event; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Website; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.text.TextUtils; import android.util.SparseArray; /** * 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 }; /** * 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 } /** * @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; } /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override public Account[] getAccountsByType(String type) { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts2xApi = accountMan.getAccountsByType(type); 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; } 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); 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); } - // update the myContacts Ids - // this is currently done here as it should be performed one time only - // and just before the first time sync - fetchMyContactsGroupRowIds(); + 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); 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); 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) || 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. *
360/360-Engine-for-Android
3a1af7784c5a90ab2632e580f3667d7122b1f811
Added a new metadata field in ContactDetail Structure
diff --git a/src/com/vodafone360/people/datatypes/ContactDetail.java b/src/com/vodafone360/people/datatypes/ContactDetail.java index b00fc46..3a95164 100644 --- a/src/com/vodafone360/people/datatypes/ContactDetail.java +++ b/src/com/vodafone360/people/datatypes/ContactDetail.java @@ -1,855 +1,862 @@ /* * 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) { 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 + 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; } } /** * 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} */ @Override public String name() { return "ContactDetail"; } /** * 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); setValue(tag, value); } 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); } String ret = "\tContact detail:" + "\n\t\tLocal Detail ID: " + localDetailID + "\n\t\tLocal Contact ID: " + localContactID + "\n\t\tKey: " + key + "\n\t\tKey type: " + keyType + "\n\t\tValue: " + value + "\n\t\tDeleted: " + deleted + "\n\t\tOrder: " + order + "\n\t\tLocation: " + location + "\n\t\tAlt: " + alt + "\n\t\tContact ID: " + serverContactId + "\n\t\tNative Contact ID: " + nativeContactId + "\n\t\tNative Detail ID: " + nativeDetailId + "\n\t\tNative Val 1: " + nativeVal1 + "\n\t\tNative Val 2: " + nativeVal2 + "\n\t\tNative Val 3: " + nativeVal3 + "\n\t\tPhoto Mime Type: " + photo_mime_type + "\n\t\tPhoto URL: " + photo_url + "\n\t\tUpdated: " + updated + " Date: " + time.toGMTString() + "\n\t\tUnique ID: " + unique_id + "\n\t\tserverContactId: " + serverContactId + "\n\t\tsyncNativeContactId: " + syncNativeContactId; if (location != null) { ret += "\n\t\tLocation: " + location.toString(); } if (photo != null) { ret += "\n\t\tPhoto BYTE[] is present"; } ret += "\n\t\tPhoto MIME type: " + photo_mime_type; ret += "\n\t\tPhoto URL: " + photo_url; return ret; } /** * 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()]) {
360/360-Engine-for-Android
f83919633301cf3c10e292262df2fdd7c978b648
Removed . from README
diff --git a/README b/README index 0c39d43..9defdfe 100644 --- a/README +++ b/README @@ -1 +1 @@ -For detailed documentation please visit http://360.github.com/360-Engine-for-Android. +For detailed documentation please visit http://360.github.com/360-Engine-for-Android
360/360-Engine-for-Android
e85f4c9e28226e30ac5db84aa7c66ca399e1b968
Added . to README
diff --git a/README b/README index 9defdfe..0c39d43 100644 --- a/README +++ b/README @@ -1 +1 @@ -For detailed documentation please visit http://360.github.com/360-Engine-for-Android +For detailed documentation please visit http://360.github.com/360-Engine-for-Android.
360/360-Engine-for-Android
0270df40159bc1453ffb6291df836cbb3aaee08c
changes for mikis code review
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index a23259d..305499a 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,702 +1,715 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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 { /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mIdentityList = new ArrayList<Identity>(); /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** Definitions for expected data-types returned from Server. */ private static final String TYPE_IDENTITY = "Identity"; private static final String TYPE_STATUS_MSG = "StatusMsg"; public static final String KEY_DATA = "data"; private static final String KEY_DATA_CHATABLE_IDENTITIES = "chatable_data"; private static final String LOG_STATUS_MSG = TYPE_STATUS_MSG + ": "; /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; } /** * 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() { } /** * 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushRequest(evt.mMessageType); } else { switch (mState) { case IDLE: LogUtils.logW("IDLE should never happend"); break; case FETCHING_IDENTITIES: case GETTING_MY_IDENTITIES: case GETTING_MY_CHATABLE_IDENTITIES: handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); break; case SETTING_IDENTITY_CAPABILITY_STATUS: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case VALIDATING_IDENTITY_CREDENTIALS: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("default should never happend"); break; } } } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushRequest(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: addUiFetchIdentities(); break; case IDENTITY_CHANGE: EngineManager.getInstance().getPresenceEngine().setMyAvailability(); addUiGetMyIdentities(); mEventCallback.kickWorkerThread(); break; default: // do nothing } } /** * 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 FETCH_IDENTITIES: startGetAvailableIdentities(data); break; case GET_MY_IDENTITIES: startGetMyIdentities(data); break; case GET_MY_CHATABLE_IDENTITIES: startGetMyChatableIdentities(); break; case VALIDATE_IDENTITY_CREDENTIALS: startValidateIdentityCredentials(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); startSetIdentityStatus(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * 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(); } } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ public void addUiFetchIdentities() { LogUtils.logD("IdentityEngine.addUiFetchIdentities()"); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.FETCH_IDENTITIES, getIdentitiesFilter()); } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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); } /** * Add request to fetch the current user's identities. * */ public void addUiGetMyIdentities() { LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); } /** * 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); } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * + * TODO: remove parameter as soon as branch ui-refresh is merged. + * * @param data Bundled request data. + * */ private void startGetMyIdentities(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to retrieve 'My chat-able' Identities. The request is * filtered to retrieve only identities with the chat capability enabled. * (Request is not issued if there is currently no connectivity). */ private void startGetMyChatableIdentities() { if (!isConnected()) { return; } Bundle filter = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); filter.putStringArrayList("capability", l); newState(State.GETTING_MY_CHATABLE_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter(filter)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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 startSetIdentityStatus(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_CAPABILITY_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 startValidateIdentityCredentials(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 retrieve available Identities. (Request is not issued if - * there is currently no connectivity). + * Sends a getAvailableIdentities request to the backend. + * + * TODO: remove the parameter as soon as we have merged with the ui-refresh + * branch. * * @param data Bundled request data. */ private void startGetAvailableIdentities(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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 handleServerGetAvailableIdentitiesResponse(List<BaseDataType> data) { Bundle bu = null; LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(TYPE_IDENTITY, data); if (errorStatus == ServiceStatus.SUCCESS) { mIdentityList.clear(); for (BaseDataType item : data) { if (TYPE_IDENTITY.equals(item.name())) { mIdentityList.add((Identity)item); LogUtils.logD("Identity: " + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mState == State.GETTING_MY_IDENTITIES || (mState == State.GETTING_MY_CHATABLE_IDENTITIES)) { // store local copy of my identities makeChatableIdentitiesCache(mIdentityList); bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); } bu.putParcelableArrayList(KEY_DATA, mIdentityList); } LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse completw UI req"); completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } 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 handleSetIdentityCapabilityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } /** * Add request to fetch the current user's 'chat-able' identities. This will * automatically apply set of filters applied to GetMyIdentities API call to * get Identities with chat capability. * * Note: Only called from tests. */ public void getMyChatableIdentities() { LogUtils.logD("IdentityEngine.getMyChatableIdentities()"); if (mMyChatableIdentityList != null) { Bundle bu = new Bundle(); bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); completeUiRequest(ServiceStatus.SUCCESS, bu); return; } addUiRequestToQueue(ServiceUiRequest.GET_MY_CHATABLE_IDENTITIES, null); } + /** + * + * 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; } }
360/360-Engine-for-Android
ba7e42cbc41251c13af71772b21b90b71d14a484
PAND-1483: Implement IC(Identities Change) for Identities Engine
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 8b52b79..a23259d 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,699 +1,702 @@ /* * 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.IdentityCapability.CapabilityID; 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.service.ServiceUiRequest; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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 { /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mIdentityList = new ArrayList<Identity>(); /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** Definitions for expected data-types returned from Server. */ private static final String TYPE_IDENTITY = "Identity"; private static final String TYPE_STATUS_MSG = "StatusMsg"; public static final String KEY_DATA = "data"; private static final String KEY_DATA_CHATABLE_IDENTITIES = "chatable_data"; private static final String LOG_STATUS_MSG = TYPE_STATUS_MSG + ": "; /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; } /** * 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() { } /** * 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) { PushEvent evt = (PushEvent)resp.mDataTypes.get(0); handlePushRequest(evt.mMessageType); } else { switch (mState) { case IDLE: LogUtils.logW("IDLE should never happend"); break; case FETCHING_IDENTITIES: case GETTING_MY_IDENTITIES: case GETTING_MY_CHATABLE_IDENTITIES: handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); break; case SETTING_IDENTITY_CAPABILITY_STATUS: handleSetIdentityCapabilityStatus(resp.mDataTypes); break; case VALIDATING_IDENTITY_CREDENTIALS: handleValidateIdentityCredentials(resp.mDataTypes); break; default: LogUtils.logW("default should never happend"); break; } } } /** * Handle Status or Timeline Activity change Push message * * @param evt Push message type (Status change or Timeline change). */ private void handlePushRequest(PushMessageTypes evt) { LogUtils.logD("IdentityEngine handlePushRequest"); switch (evt) { case IDENTITY_NETWORK_CHANGE: addUiFetchIdentities(); break; case IDENTITY_CHANGE: - // TODO padma - break; + EngineManager.getInstance().getPresenceEngine().setMyAvailability(); + addUiGetMyIdentities(); + mEventCallback.kickWorkerThread(); + break; default: // do nothing } } /** * 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 FETCH_IDENTITIES: startGetAvailableIdentities(data); break; case GET_MY_IDENTITIES: startGetMyIdentities(data); break; case GET_MY_CHATABLE_IDENTITIES: startGetMyChatableIdentities(); break; case VALIDATE_IDENTITY_CREDENTIALS: startValidateIdentityCredentials(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); startSetIdentityStatus(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * 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(); } } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * */ public void addUiFetchIdentities() { LogUtils.logD("IdentityEngine.addUiFetchIdentities()"); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.FETCH_IDENTITIES, getIdentitiesFilter()); } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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); } /** * Add request to fetch the current user's identities. * */ public void addUiGetMyIdentities() { LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); emptyUiRequestQueue(); addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); } /** * 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); } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ private void startGetMyIdentities(Object data) { if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to retrieve 'My chat-able' Identities. The request is * filtered to retrieve only identities with the chat capability enabled. * (Request is not issued if there is currently no connectivity). */ private void startGetMyChatableIdentities() { if (!isConnected()) { return; } Bundle filter = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); filter.putStringArrayList("capability", l); newState(State.GETTING_MY_CHATABLE_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter(filter)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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 startSetIdentityStatus(Object data) { if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_CAPABILITY_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 startValidateIdentityCredentials(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 retrieve available Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ private void startGetAvailableIdentities(Object data) { if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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 handleServerGetAvailableIdentitiesResponse(List<BaseDataType> data) { Bundle bu = null; LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(TYPE_IDENTITY, data); if (errorStatus == ServiceStatus.SUCCESS) { mIdentityList.clear(); for (BaseDataType item : data) { if (TYPE_IDENTITY.equals(item.name())) { mIdentityList.add((Identity)item); LogUtils.logD("Identity: " + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mState == State.GETTING_MY_IDENTITIES || (mState == State.GETTING_MY_CHATABLE_IDENTITIES)) { // store local copy of my identities makeChatableIdentitiesCache(mIdentityList); bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); } bu.putParcelableArrayList(KEY_DATA, mIdentityList); } LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse completw UI req"); completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } 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 handleSetIdentityCapabilityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } /** * Add request to fetch the current user's 'chat-able' identities. This will * automatically apply set of filters applied to GetMyIdentities API call to * get Identities with chat capability. * * Note: Only called from tests. */ public void getMyChatableIdentities() { LogUtils.logD("IdentityEngine.getMyChatableIdentities()"); if (mMyChatableIdentityList != null) { Bundle bu = new Bundle(); bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); completeUiRequest(ServiceStatus.SUCCESS, bu); return; } addUiRequestToQueue(ServiceUiRequest.GET_MY_CHATABLE_IDENTITIES, null); } 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; } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 1c28acf..5f4f026 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -5,798 +5,798 @@ * 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.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.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; 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.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, IContactSyncObserver, ITcpConnectionListener { /** Check every 10 minutes. **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private long mNextRuntime = -1; private DatabaseHelper mDbHelper; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private List<TimelineSummaryItem> mFailedMessagesList; // (to, network) private boolean mContObsAdded; /** 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; /** * * @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>(); addAsContactSyncObserver(); } @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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (!mContObsAdded) { addAsContactSyncObserver(); } if (!canRun()) { mNextRuntime = -1; LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" + mNextRuntime); return mNextRuntime; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { 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 (mNextRuntime == -1) { LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!"); return 0; } else { return mNextRuntime; } } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + mNextRuntime + "]"); 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) { if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) { if (canRun()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setNextRuntime(); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20; } } } else { 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); } private void setNextRuntime() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again in [" + (CHECK_FREQUENCY / (1000 * 60)) + "] minutes"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY; } private void setRunNow() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW"); mNextRuntime = 0; } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setNextRuntime(); } else { setPresenceOffline(); mContObsAdded = false; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } /*** * 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); } @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: setRunNow(); } } @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++; } } if (mUsers.size() > 0) { 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 + "]"); UiAgent uiAgent = mEventCallback.getUiAgent(); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { uiAgent.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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } 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; - case IDENTITY_CHANGE: - // identity has been added or removed, reset availability - initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); - break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.name()); } } 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()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { Presence.setMyAvailability((Hashtable<String, String>)data); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); break; case CREATE_CONVERSATION: if (data != null) { List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; case SEND_CHAT_MESSAGE: if (data != null) { 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); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); } } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } private void initSetMyAvailabilityRequest(User myself) { if (myself == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !canRun()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the state of the engine. Also displays the login notification if * necessary. * * @param accounts */ public void setMyAvailability(Hashtable<String, String> myselfPresence) { if (myselfPresence == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with:" + myselfPresence); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), myselfPresence); Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values for myself myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } 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); } } } /** * 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. */ private void addAsContactSyncObserver() { if (EngineManager.getInstance() != null && EngineManager.getInstance().getContactSyncEngine() != null) { EngineManager.getInstance().getContactSyncEngine().addEventCallback(this); mContObsAdded = true; LogUtils.logD("ActivityEngine contactSync observer added."); } else { LogUtils.logE("ActivityEngine can't add to contactSync observers."); } } @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { LogUtils.logD("PresenceEngine onContactSyncStateChange called."); } @Override public void onProgressEvent(State currentState, int percent) { if (percent == 100) { switch (currentState) { case FETCHING_SERVER_CONTACTS: LogUtils .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_CONTACTS is done"); // mDownloadServerContactsComplete = true; // break; // case SYNCING_SERVER_ME_PROFILE: // LogUtils // .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_ME_PROFILE is done"); // mDownloadMeProfileComplete = true; // break; default: // nothing to do now break; } } } @Override public void onSyncComplete(ServiceStatus status) { LogUtils.logD("PresenceEngine onSyncComplete called."); } @Override public void onConnectionStateChanged(int state) { switch (state) { case STATE_CONNECTED: getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } + public void setMyAvailability() { + initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); + } + } diff --git a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java index 1cbfa7f..9e1d42a 100644 --- a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java +++ b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java @@ -1,494 +1,495 @@ /* * 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.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 data byte array containing Hessian encoded data * @param type Event type * @return List of BaseDataType items parsed from Hessian data * @throws IOException */ public List<BaseDataType> decodeHessianByteArray(byte[] data, Request.Type type, boolean isZipped) 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); } List<BaseDataType> mBaseDataTypeList = null; mMicroHessianInput.init(is); LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); try { mBaseDataTypeList = decodeResponse(is, type); } catch (IOException e) { LogUtils.logE("HessianDecoder.decodeHessianByteArray() " + "IOException during decodeResponse", e); } CloseUtils.close(bis); CloseUtils.close(is); return mBaseDataTypeList; } @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; } } /** * TODO: we cast every response to a Map, losing e.g. push event "c0" which * only contains a string - to fix * * @param is * @param type * @return * @throws IOException */ @SuppressWarnings("unchecked") private List<BaseDataType> decodeResponse(InputStream is, Request.Type type) throws IOException { boolean usesReplyTag = false; List<BaseDataType> mResultList = 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(); zybErr.errorType = mMicroHessianInput.readFault().errString(); mResultList.add(zybErr); return mResultList; } // 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(mResultList, is, tag); return mResultList; } // 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); decodeResponseByRequestType(mResultList, hash, type); } else { // if we have a common request 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); mResultList.add(auth.createFromHashtable(authHash)); } else if (map.containsKey(KEY_CONTACT_LIST)) { // contact list getContacts(mResultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); } 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) { mResultList.add(UserProfile.createFromHashtable(obj)); } } else if (map.containsKey(KEY_USER_PROFILE)) { Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map .get(KEY_USER_PROFILE); mResultList.add(UserProfile.createFromHashtable(userProfileHash)); } else if ((map.containsKey(KEY_IDENTITY_LIST)) || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { Vector<Hashtable<String, Object>> idcap = null; if (map.containsKey(KEY_IDENTITY_LIST)) { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); } else { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); } for (Hashtable<String, Object> obj : idcap) { Identity id = new Identity(); mResultList.add(id.createFromHashtable(obj)); } } 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) { mResultList.add(ActivityItem.createFromHashtable(obj)); } } } if (usesReplyTag) { is.read(); // read the last 'z' } return mResultList; } 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); } private void decodeResponseByRequestType(List<BaseDataType> clist, Hashtable<String, Object> hash, Request.Type type) { switch (type) { case CONTACT_CHANGES_OR_UPDATES: // create ContactChanges ContactChanges contChanges = new ContactChanges(); contChanges = contChanges.createFromHashtable(hash); clist.add(contChanges); break; case ADD_CONTACT: case SIGN_UP: clist.add(Contact.createFromHashtable(hash)); break; case RETRIEVE_PUBLIC_KEY: // AA define new object type clist.add(PublicKeyDetails.createFromHashtable(hash)); break; case FRIENDSHIP_REQUEST: 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); break; case CONTACT_DETAIL_DELETE: ContactDetailDeletion cdel = new ContactDetailDeletion(); clist.add(cdel.createFromHashtable(hash)); break; case USER_INVITATION: // Not currently supported. break; case CONTACT_GROUP_RELATION_LIST: ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); groupRelationList.populateFromHashtable(hash); clist.add(groupRelationList); break; case CONTACT_GROUP_RELATIONS: ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); groupRelationsList.populateFromHashtable(hash); clist.add(groupRelationsList); break; case GROUP_LIST: ItemList zyblist = new ItemList(ItemList.Type.group_privacy); zyblist.populateFromHashtable(hash); clist.add(zyblist); break; case ITEM_LIST_OF_LONGS: ItemList listOfLongs = new ItemList(ItemList.Type.long_value); listOfLongs.populateFromHashtable(hash); clist.add(listOfLongs); break; case STATUS_LIST: ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); zybstatlist.populateFromHashtable(hash); clist.add(zybstatlist); 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); } break; case EXPECTING_STATUS_ONLY: StatusMsg statMsg = new StatusMsg(); clist.add(statMsg.createFromHashtable(hash)); break; case STATUS: StatusMsg s = new StatusMsg(); s.mStatus = true; clist.add(s); break; case PRESENCE_LIST: PresenceList mPresenceList = new PresenceList(); mPresenceList.createFromHashtable(hash); clist.add(mPresenceList); break; case PUSH_MSG: // parse content of RPG Push msg parsePushMessage(clist, hash); break; case CREATE_CONVERSATION: Conversation mConversation = new Conversation(); mConversation.createFromHashtable(hash); clist.add(mConversation); break; default: LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" + type.name() + "]"); } } 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.PRESENCE_ENGINE; + 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
48a7b488107813afed5992fcf1b2184c4344cac3
altered gitignore a bit and fixed and Engine Test for the Identities Engine.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8ea3ee8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +config.properties +tests/bin/* +bin +gen +
360/360-Engine-for-Android
f9258568882327c07b1c419b3d6ab26f998cdec9
altered gitignore a bit and fixed and Engine Test for the Identities Engine.
diff --git a/.gitignore b/.gitignore deleted file mode 100644 index bace426..0000000 --- a/.gitignore +++ /dev/null @@ -1 +0,0 @@ -config.properties diff --git a/tests/src/com/vodafone360/people/tests/engine/IdentityEngineTest.java b/tests/src/com/vodafone360/people/tests/engine/IdentityEngineTest.java index 3fb754c..5b9521b 100644 --- a/tests/src/com/vodafone360/people/tests/engine/IdentityEngineTest.java +++ b/tests/src/com/vodafone360/people/tests/engine/IdentityEngineTest.java @@ -1,356 +1,352 @@ /* * 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.net.URL; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import com.vodafone360.people.datatypes.BaseDataType; import com.vodafone360.people.datatypes.Identity; import com.vodafone360.people.datatypes.IdentityCapability; import com.vodafone360.people.datatypes.ServerError; import com.vodafone360.people.datatypes.StatusMsg; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.engine.identities.IdentityEngine; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.io.ResponseQueue; public class IdentityEngineTest extends InstrumentationTestCase implements IEngineTestFrameworkObserver { /** * States for test harness */ enum IdentityTestState { IDLE, FETCH_IDENTITIES, GET_MY_IDENTITIES, FETCH_IDENTITIES_FAIL, FETCH_IDENTITIES_POPULATED, GET_CHATABLE_IDENTITIES, SET_IDENTITY_CAPABILTY, VALIDATE_ID_CREDENTIALS_SUCCESS, VALIDATE_ID_CREDENTIALS_FAIL, GET_NEXT_RUNTIME } EngineTestFramework mEngineTester = null; IdentityEngine mEng = null; IdentityTestState mState = IdentityTestState.IDLE; @Override protected void setUp() throws Exception { super.setUp(); mEngineTester = new EngineTestFramework(this); mEng = new IdentityEngine(mEngineTester); mEngineTester.setEngine(mEng); mState = IdentityTestState.IDLE; } @Override protected void tearDown() throws Exception { // stop our dummy thread? mEngineTester.stopEventThread(); mEngineTester = null; mEng = null; // call at the end!!! super.tearDown(); } @Suppress // Takes too long @MediumTest public void testFetchIdentities() { mState = IdentityTestState.FETCH_IDENTITIES; - Bundle fbund = new Bundle(); NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.addUiFetchIdentities(fbund); + mEng.addUiFetchIdentities(); // mEng.run(); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); 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 @Suppress // Takes too long. public void testAddUiGetMyIdentities() { mState = IdentityTestState.GET_MY_IDENTITIES; - Bundle getBund = new Bundle(); NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.addUiGetMyIdentities(getBund); + mEng.addUiGetMyIdentities(); // mEng.run(); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); Object data = mEngineTester.data(); assertNull(null); try { ArrayList<Identity> identityList = ((Bundle)data).getParcelableArrayList("data"); assertEquals(identityList.size(), 1); } catch (Exception e) { throw (new RuntimeException("Expected identity list with 1 item")); } } @MediumTest @Suppress // Takes to long public void testFetchIdentitiesFail() { mState = IdentityTestState.FETCH_IDENTITIES_FAIL; - Bundle fbund = new Bundle(); NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.addUiFetchIdentities(fbund); + mEng.addUiFetchIdentities(); // mEng.run(); ServiceStatus status = mEngineTester.waitForEvent(); assertFalse(ServiceStatus.SUCCESS == status); Object data = mEngineTester.data(); assertNull(data); } @MediumTest @Suppress // Breaks tests. public void testFetchIdentitiesPopulated() { mState = IdentityTestState.FETCH_IDENTITIES_POPULATED; - Bundle fbund = new Bundle(); NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); - mEng.addUiFetchIdentities(fbund); + mEng.addUiFetchIdentities(); // mEng.run(); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); Object data = mEngineTester.data(); assertTrue(data != null); } @MediumTest @Suppress // Breaks tests. 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); // AA mEng.addUiSetIdentityCapabilityStatus(network, identityId, fbund); mEng.addUiSetIdentityStatus(network, identityId, true); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); 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 @Suppress // Breaks tests. 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(); assertEquals(ServiceStatus.SUCCESS, status); Object data = mEngineTester.data(); assertTrue(data != null); } @MediumTest @Suppress // Breaks tests. public void testGetMyChatableIdentities() { mState = IdentityTestState.GET_CHATABLE_IDENTITIES; NetworkAgent.setAgentState(NetworkAgent.AgentState.CONNECTED); mEng.getMyChatableIdentities(); ServiceStatus status = mEngineTester.waitForEvent(); assertEquals(ServiceStatus.SUCCESS, status); Object data = mEngineTester.data(); assertTrue(data != null); } @MediumTest @Suppress // Breaks tests. 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(); assertFalse(ServiceStatus.SUCCESS == status); 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 GET_MY_IDENTITIES: Log.d("TAG", "IdentityEngineTest.reportBackToEngine Get ids"); Identity myId = new Identity(); data.add(myId); 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; case GET_CHATABLE_IDENTITIES: case FETCH_IDENTITIES_POPULATED: Identity id2 = new Identity(); id2.mActive = true; id2.mAuthType = "auth"; List<String> clist = new ArrayList<String>(); clist.add("uk"); clist.add("fr"); id2.mCountryList = clist; id2.mCreated = new Long(0); id2.mDisplayName = "Facebook"; // id2.mIcon2Mime = "jpeg"; id2.mIconMime = "jpeg"; try { id2.mIcon2Url = new URL("url2"); id2.mIconUrl = new URL("url"); id2.mNetworkUrl = new URL("network"); } catch (Exception e) { } id2.mIdentityId = "fb"; id2.mIdentityType = "type"; id2.mName = "Facebook"; id2.mNetwork = "Facebook"; id2.mOrder = 0; id2.mPluginId = ""; id2.mUpdated = new Long(0); id2.mUserId = 23; id2.mUserName = "user"; data.add(id2); List<IdentityCapability> capList = new ArrayList<IdentityCapability>(); IdentityCapability idcap = new IdentityCapability(); idcap.mCapability = IdentityCapability.CapabilityID.sync_contacts; idcap.mDescription = "sync cont"; idcap.mName = "sync cont"; idcap.mValue = true; capList.add(idcap); id2.mCapabilities = capList; data.add(id2); respQueue.addToResponseQueue(reqId, data, engine); Log.d("TAG", "IdentityEngineTest.reportBackToEngine add to Q"); mEng.onCommsInMessage(); break; default: } } @Override public void onEngineException(Exception exp) { // TODO Auto-generated method stub } }
360/360-Engine-for-Android
d7e26b01d937f4dc2a34ab36e68a52067764157a
PAND-1609: now fetching myContacts Ids just after creating the 360 people account instead
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index 088b78d..a7052a7 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,953 +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.engine.contactsync; import java.util.ArrayList; import java.util.HashMap; import java.util.List; 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.LogUtils; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.VersionUtils; import dalvik.system.PathClassLoader; 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.Event; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Website; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.text.TextUtils; import android.util.SparseArray; /** * 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 }; /** * 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() { - fetchMyContactsGroupRowIds(); + // perform here any one time initialization } /** * @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; } /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override public Account[] getAccountsByType(String type) { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts2xApi = accountMan.getAccountsByType(type); 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; } 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); 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); } + + // update the myContacts Ids + // this is currently done here as it should be performed one time only + // and just before the first time sync + fetchMyContactsGroupRowIds(); + return isAdded; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE); 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); 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) || 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
360/360-Engine-for-Android
60118dee7e71b2013bca814156e603dd887fd60d
now fetching myContacts Ids just after creating the 360 people account instead of doing it at install time
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index 088b78d..a7052a7 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,953 +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.engine.contactsync; import java.util.ArrayList; import java.util.HashMap; import java.util.List; 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.LogUtils; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.VersionUtils; import dalvik.system.PathClassLoader; 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.Event; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Website; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.text.TextUtils; import android.util.SparseArray; /** * 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 }; /** * 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() { - fetchMyContactsGroupRowIds(); + // perform here any one time initialization } /** * @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; } /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override public Account[] getAccountsByType(String type) { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts2xApi = accountMan.getAccountsByType(type); 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; } 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); 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); } + + // update the myContacts Ids + // this is currently done here as it should be performed one time only + // and just before the first time sync + fetchMyContactsGroupRowIds(); + return isAdded; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE); 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); 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) || 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
360/360-Engine-for-Android
5c15611575ca4e93c4c62cc0c16bde2730ee4bd7
[PAND-1484] Implement INC (identity network change) push messages
diff --git a/src/com/vodafone360/people/engine/identities/IdentityEngine.java b/src/com/vodafone360/people/engine/identities/IdentityEngine.java index 17a5644..8b52b79 100644 --- a/src/com/vodafone360/people/engine/identities/IdentityEngine.java +++ b/src/com/vodafone360/people/engine/identities/IdentityEngine.java @@ -1,672 +1,699 @@ /* * 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.IdentityCapability.CapabilityID; import com.vodafone360.people.engine.BaseEngine; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.service.ServiceUiRequest; -import com.vodafone360.people.service.agent.NetworkAgent; import com.vodafone360.people.service.io.ResponseQueue.Response; 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; /** * 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 { /** * 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_CAPABILITY_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 class IdentityCapabilityStatusRequest { // private String mNetwork; // private String mIdentityId; // private Map<String, Object> mStatus = null; // // /** // * Supply filter containing required capabilities. // * @param filter Bundle containing capabilities filter. // */ // public void setCapabilityStatus(Bundle filter){ // mStatus = prepareBoolFilter(filter); // } // } /** * 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 { private boolean mDryRun; private String mNetwork; private String mUserName; private String mPassword; private Map<String, Object> mStatus = null; /** * Supply filter containing required capabilities. * * @param filter Bundle containing capabilities filter. */ public void setCapabilityStatus(Bundle filter) { mStatus = prepareBoolFilter(filter); } } private State mState = State.IDLE; /** List array of Identities retrieved from Server. */ private final ArrayList<Identity> mIdentityList = new ArrayList<Identity>(); /** List array of Identities supporting chat retrieved from Server. */ private ArrayList<String> mMyChatableIdentityList = null; private final ArrayList<StatusMsg> mStatusList = new ArrayList<StatusMsg>(); /** Definitions for expected data-types returned from Server. */ private static final String TYPE_IDENTITY = "Identity"; private static final String TYPE_STATUS_MSG = "StatusMsg"; public static final String KEY_DATA = "data"; private static final String KEY_DATA_CHATABLE_IDENTITIES = "chatable_data"; private static final String LOG_STATUS_MSG = TYPE_STATUS_MSG + ": "; /** * Generate Map containing boolean capability filters for supplied Bundle. * * @param filter Bundle containing filter. * @return Map containing set of capabilities. */ private static Map<String, Object> prepareBoolFilter(Bundle filter) { Map<String, Object> objectFilter = null; if (filter != null && (filter.keySet().size() > 0)) { objectFilter = new Hashtable<String, Object>(); 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; } /** * Constructor * * @param eventCallback IEngineEventCallback allowing engine to report back. */ public IdentityEngine(IEngineEventCallback eventCallback) { super(eventCallback); mEngineId = EngineId.IDENTITIES_ENGINE; } /** * 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() { } /** * 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); - switch (mState) { - case IDLE: - LogUtils.logW("IDLE should never happend"); - break; - case FETCHING_IDENTITIES: - case GETTING_MY_IDENTITIES: - case GETTING_MY_CHATABLE_IDENTITIES: - handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); - break; - case SETTING_IDENTITY_CAPABILITY_STATUS: - handleSetIdentityCapabilityStatus(resp.mDataTypes); - break; - case VALIDATING_IDENTITY_CREDENTIALS: - handleValidateIdentityCredentials(resp.mDataTypes); + + if (resp.mReqId == 0 && resp.mDataTypes.size() > 0) { + PushEvent evt = (PushEvent)resp.mDataTypes.get(0); + handlePushRequest(evt.mMessageType); + } else { + switch (mState) { + case IDLE: + LogUtils.logW("IDLE should never happend"); + break; + case FETCHING_IDENTITIES: + case GETTING_MY_IDENTITIES: + case GETTING_MY_CHATABLE_IDENTITIES: + handleServerGetAvailableIdentitiesResponse(resp.mDataTypes); + break; + case SETTING_IDENTITY_CAPABILITY_STATUS: + handleSetIdentityCapabilityStatus(resp.mDataTypes); + break; + case VALIDATING_IDENTITY_CREDENTIALS: + handleValidateIdentityCredentials(resp.mDataTypes); + break; + default: + LogUtils.logW("default should never happend"); + break; + } + } + } + + /** + * Handle Status or Timeline Activity change Push message + * + * @param evt Push message type (Status change or Timeline change). + */ + private void handlePushRequest(PushMessageTypes evt) { + LogUtils.logD("IdentityEngine handlePushRequest"); + switch (evt) { + case IDENTITY_NETWORK_CHANGE: + addUiFetchIdentities(); break; + case IDENTITY_CHANGE: + // TODO padma + break; default: - LogUtils.logW("default should never happend"); - break; + // do nothing } - } - + /** * 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 FETCH_IDENTITIES: - startFetchIdentities(data); + startGetAvailableIdentities(data); break; case GET_MY_IDENTITIES: startGetMyIdentities(data); break; case GET_MY_CHATABLE_IDENTITIES: startGetMyChatableIdentities(); break; case VALIDATE_IDENTITY_CREDENTIALS: startValidateIdentityCredentials(data); break; case SET_IDENTITY_CAPABILITY_STATUS: // changed the method called // startSetIdentityCapabilityStatus(data); startSetIdentityStatus(data); break; default: completeUiRequest(ServiceStatus.ERROR_NOT_FOUND, null); break; } } /** * 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(); } } /** * Add request to fetch available identities. The request is added to the UI * request and processed when the engine is ready. * - * @param filter Bundle containing parameters for fetch identities request. - * This contains the set of filters applied to GetIdentities API - * call. */ - public void addUiFetchIdentities(Bundle filter) { + public void addUiFetchIdentities() { LogUtils.logD("IdentityEngine.addUiFetchIdentities()"); emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.FETCH_IDENTITIES, filter); + addUiRequestToQueue(ServiceUiRequest.FETCH_IDENTITIES, getIdentitiesFilter()); } /** * Add request to set the capabilities we wish to support for the specified * identity (such as support sync of contacts, receipt of status updates, * chat etc.) * * @param network Name of the identity, * @param identityId Id of identity. * @param identityStatus Bundle containing the capability information for * this identity. */ 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); } /** * Add request to fetch the current user's identities. - * - * @param filter Bundle containing parameters for fetch identities request. - * This contains the set of filters applied to GetMyIdentities - * API call. + * */ - public void addUiGetMyIdentities(Bundle filter) { + public void addUiGetMyIdentities() { LogUtils.logD("IdentityEngine.addUiGetMyIdentities()"); emptyUiRequestQueue(); - addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, filter); + addUiRequestToQueue(ServiceUiRequest.GET_MY_IDENTITIES, getIdentitiesFilter()); } /** * 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); } /** * Issue request to retrieve 'My' Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ private void startGetMyIdentities(Object data) { - if (!checkConnectivity()) { + if (!isConnected()) { return; } newState(State.GETTING_MY_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * Issue request to retrieve 'My chat-able' Identities. The request is * filtered to retrieve only identities with the chat capability enabled. * (Request is not issued if there is currently no connectivity). */ private void startGetMyChatableIdentities() { - if (!checkConnectivity()) { + if (!isConnected()) { return; } Bundle filter = new Bundle(); ArrayList<String> l = new ArrayList<String>(); l.add(IdentityCapability.CapabilityID.chat.name()); filter.putStringArrayList("capability", l); newState(State.GETTING_MY_CHATABLE_IDENTITIES); if (!setReqId(Identities.getMyIdentities(this, prepareStringFilter(filter)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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 startSetIdentityStatus(Object data) { - if (!checkConnectivity()) { + if (!isConnected()) { return; } newState(State.SETTING_IDENTITY_CAPABILITY_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 startValidateIdentityCredentials(Object data) { - if (!checkConnectivity()) { + 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 retrieve available Identities. (Request is not issued if * there is currently no connectivity). * * @param data Bundled request data. */ - private void startFetchIdentities(Object data) { - if (!checkConnectivity()) { + private void startGetAvailableIdentities(Object data) { + if (!isConnected()) { return; } newState(State.FETCHING_IDENTITIES); mIdentityList.clear(); if (!setReqId(Identities.getAvailableIdentities(this, prepareStringFilter((Bundle)data)))) { completeUiRequest(ServiceStatus.ERROR_BAD_SERVER_PARAMETER); } } /** * 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 handleServerGetAvailableIdentitiesResponse(List<BaseDataType> data) { Bundle bu = null; LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse"); ServiceStatus errorStatus = getResponseStatus(TYPE_IDENTITY, data); if (errorStatus == ServiceStatus.SUCCESS) { mIdentityList.clear(); for (BaseDataType item : data) { if (TYPE_IDENTITY.equals(item.name())) { mIdentityList.add((Identity)item); LogUtils.logD("Identity: " + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); if (mState == State.GETTING_MY_IDENTITIES || (mState == State.GETTING_MY_CHATABLE_IDENTITIES)) { // store local copy of my identities makeChatableIdentitiesCache(mIdentityList); bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); } bu.putParcelableArrayList(KEY_DATA, mIdentityList); } LogUtils.logD("IdentityEngine: handleServerGetAvailableIdentitiesResponse completw UI req"); completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** * 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(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } 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 handleSetIdentityCapabilityStatus(List<BaseDataType> data) { Bundle bu = null; ServiceStatus errorStatus = getResponseStatus(TYPE_STATUS_MSG, data); if (errorStatus == ServiceStatus.SUCCESS) { mStatusList.clear(); for (BaseDataType item : data) { if (TYPE_STATUS_MSG.equals(item.name())) { mStatusList.add((StatusMsg)item); LogUtils.logD(LOG_STATUS_MSG + item.name()); } else { completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE); return; } } bu = new Bundle(); bu.putParcelableArrayList(KEY_DATA, mStatusList); } completeUiRequest(errorStatus, bu); newState(State.IDLE); } /** - * Get Connectivity status from NetworkAgent. + * Get Connectivity status from the connection manager. + * + * @return true True if the connection is active, false otherwise. * - * @return true if NetworkAgent reports we have connectivity, false - * otherwise (complete outstanding request with ERROR_COMMS). */ - private boolean checkConnectivity() { - if (NetworkAgent.getAgentState() != NetworkAgent.AgentState.CONNECTED) { - completeUiRequest(ServiceStatus.ERROR_COMMS, null); - return false; - } - return true; + private boolean isConnected() { + int connState = ConnectionManager.getInstance().getConnectionState(); + return (connState == ITcpConnectionListener.STATE_CONNECTED); } /** * Create cache of 'chat-able' identities. * * @param list List array of retrieved Identities. */ private void makeChatableIdentitiesCache(List<Identity> list) { if (mMyChatableIdentityList == null) { mMyChatableIdentityList = new ArrayList<String>(); } else { mMyChatableIdentityList.clear(); } for (Identity id : list) { if (id.mActive && id.mCapabilities != null) { for (IdentityCapability ic : id.mCapabilities) { if (ic.mCapability == CapabilityID.chat && ic.mValue) { mMyChatableIdentityList.add(id.mNetwork); } } } } } /** * Add request to fetch the current user's 'chat-able' identities. This will * automatically apply set of filters applied to GetMyIdentities API call to * get Identities with chat capability. * * Note: Only called from tests. */ public void getMyChatableIdentities() { LogUtils.logD("IdentityEngine.getMyChatableIdentities()"); if (mMyChatableIdentityList != null) { Bundle bu = new Bundle(); bu.putStringArrayList(KEY_DATA_CHATABLE_IDENTITIES, mMyChatableIdentityList); completeUiRequest(ServiceStatus.SUCCESS, bu); return; } addUiRequestToQueue(ServiceUiRequest.GET_MY_CHATABLE_IDENTITIES, null); } + + 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; + } } diff --git a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java index 3b1af07..1c935c9 100644 --- a/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java +++ b/src/com/vodafone360/people/service/interfaces/IPeopleServiceImpl.java @@ -1,415 +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.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.LoginDetails; import com.vodafone360.people.datatypes.RegistrationDetails; import com.vodafone360.people.engine.EngineManager; import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback; 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#fetchAvailableIdentities(Bundle) */ @Override public void fetchAvailableIdentities(Bundle data) { - EngineManager.getInstance().getIdentityEngine().addUiFetchIdentities(data); + EngineManager.getInstance().getIdentityEngine().addUiFetchIdentities(); } /*** * @see com.vodafone360.people.service.interfaces.IPeopleService#fetchMyIdentities(Bundle) */ @Override public void fetchMyIdentities(Bundle data) { - EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(data); + EngineManager.getInstance().getIdentityEngine().addUiGetMyIdentities(); } /*** * @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(Hashtable) */ @Override public void setAvailability(Hashtable<String, String> myself) { EngineManager.getInstance().getPresenceEngine().setMyAvailability(myself); } /*** * @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 diff --git a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java index 8dd78f2..1cbfa7f 100644 --- a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java +++ b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java @@ -1,493 +1,494 @@ /* * 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.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 data byte array containing Hessian encoded data * @param type Event type * @return List of BaseDataType items parsed from Hessian data * @throws IOException */ public List<BaseDataType> decodeHessianByteArray(byte[] data, Request.Type type, boolean isZipped) 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); } List<BaseDataType> mBaseDataTypeList = null; mMicroHessianInput.init(is); LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); try { mBaseDataTypeList = decodeResponse(is, type); } catch (IOException e) { LogUtils.logE("HessianDecoder.decodeHessianByteArray() " + "IOException during decodeResponse", e); } CloseUtils.close(bis); CloseUtils.close(is); return mBaseDataTypeList; } @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; } } /** * TODO: we cast every response to a Map, losing e.g. push event "c0" which * only contains a string - to fix * * @param is * @param type * @return * @throws IOException */ @SuppressWarnings("unchecked") private List<BaseDataType> decodeResponse(InputStream is, Request.Type type) throws IOException { boolean usesReplyTag = false; List<BaseDataType> mResultList = 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(); zybErr.errorType = mMicroHessianInput.readFault().errString(); mResultList.add(zybErr); return mResultList; } // 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(mResultList, is, tag); return mResultList; } // 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); decodeResponseByRequestType(mResultList, hash, type); } else { // if we have a common request 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); mResultList.add(auth.createFromHashtable(authHash)); } else if (map.containsKey(KEY_CONTACT_LIST)) { // contact list getContacts(mResultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); } 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) { mResultList.add(UserProfile.createFromHashtable(obj)); } } else if (map.containsKey(KEY_USER_PROFILE)) { Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map .get(KEY_USER_PROFILE); mResultList.add(UserProfile.createFromHashtable(userProfileHash)); } else if ((map.containsKey(KEY_IDENTITY_LIST)) || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { Vector<Hashtable<String, Object>> idcap = null; if (map.containsKey(KEY_IDENTITY_LIST)) { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); } else { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); } for (Hashtable<String, Object> obj : idcap) { Identity id = new Identity(); mResultList.add(id.createFromHashtable(obj)); } } 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) { mResultList.add(ActivityItem.createFromHashtable(obj)); } } } if (usesReplyTag) { is.read(); // read the last 'z' } return mResultList; } 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); } private void decodeResponseByRequestType(List<BaseDataType> clist, Hashtable<String, Object> hash, Request.Type type) { switch (type) { case CONTACT_CHANGES_OR_UPDATES: // create ContactChanges ContactChanges contChanges = new ContactChanges(); contChanges = contChanges.createFromHashtable(hash); clist.add(contChanges); break; case ADD_CONTACT: case SIGN_UP: clist.add(Contact.createFromHashtable(hash)); break; case RETRIEVE_PUBLIC_KEY: // AA define new object type clist.add(PublicKeyDetails.createFromHashtable(hash)); break; case FRIENDSHIP_REQUEST: 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); break; case CONTACT_DETAIL_DELETE: ContactDetailDeletion cdel = new ContactDetailDeletion(); clist.add(cdel.createFromHashtable(hash)); break; case USER_INVITATION: // Not currently supported. break; case CONTACT_GROUP_RELATION_LIST: ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); groupRelationList.populateFromHashtable(hash); clist.add(groupRelationList); break; case CONTACT_GROUP_RELATIONS: ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); groupRelationsList.populateFromHashtable(hash); clist.add(groupRelationsList); break; case GROUP_LIST: ItemList zyblist = new ItemList(ItemList.Type.group_privacy); zyblist.populateFromHashtable(hash); clist.add(zyblist); break; case ITEM_LIST_OF_LONGS: ItemList listOfLongs = new ItemList(ItemList.Type.long_value); listOfLongs.populateFromHashtable(hash); clist.add(listOfLongs); break; case STATUS_LIST: ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); zybstatlist.populateFromHashtable(hash); clist.add(zybstatlist); 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); } break; case EXPECTING_STATUS_ONLY: StatusMsg statMsg = new StatusMsg(); clist.add(statMsg.createFromHashtable(hash)); break; case STATUS: StatusMsg s = new StatusMsg(); s.mStatus = true; clist.add(s); break; case PRESENCE_LIST: PresenceList mPresenceList = new PresenceList(); mPresenceList.createFromHashtable(hash); clist.add(mPresenceList); break; case PUSH_MSG: // parse content of RPG Push msg parsePushMessage(clist, hash); break; case CREATE_CONVERSATION: Conversation mConversation = new Conversation(); mConversation.createFromHashtable(hash); clist.add(mConversation); break; default: LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" + type.name() + "]"); } } 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: case IDENTITY_CHANGE: engineId = EngineId.PRESENCE_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; - case IDENTITY_NETWORK_CHANGE: - break; default: } list.add(PushEvent.createPushEvent(msg, engineId)); } } }
360/360-Engine-for-Android
28f3244579a2946ca868e3fa19f7e1cbe186b783
First set of changes required to attach the UI-Refresh project to the Git Engine project code base.
diff --git a/src/com/vodafone360/people/ApplicationCache.java b/src/com/vodafone360/people/ApplicationCache.java index a62892d..12ba59b 100644 --- a/src/com/vodafone360/people/ApplicationCache.java +++ b/src/com/vodafone360/people/ApplicationCache.java @@ -1,529 +1,642 @@ /* * 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; + /** * 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; } /** * 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; + } } diff --git a/src/com/vodafone360/people/database/tables/GroupsTable.java b/src/com/vodafone360/people/database/tables/GroupsTable.java index 031414a..2e3008a 100644 --- a/src/com/vodafone360/people/database/tables/GroupsTable.java +++ b/src/com/vodafone360/people/database/tables/GroupsTable.java @@ -1,440 +1,469 @@ /* * 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.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; 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 com.vodafone360.people.R; import com.vodafone360.people.Settings; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.datatypes.GroupItem; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.CloseUtils; import com.vodafone360.people.utils.LogUtils; /** * Contains all the functionality related to the Groups database table. The * groups table stores the information about each group from the server. This * class is never instantiated hence all methods must be static. * * @version %I%, %G% */ public abstract class GroupsTable { /** * The name of the table as it appears in the database. */ private static final String TABLE_NAME = "ZybGroups"; /** * Special ID for the ALL group */ public static final long GROUP_ALL = -1000; /** * Special ID for the ONLINE contacts group (to be added later) */ protected static final long GROUP_ONLINE = -1001; /** * Special ID for the phonebook contacts group */ protected static final long GROUP_PHONEBOOK = -1002; /** * Special ID for the connected friends group */ protected static final long GROUP_CONNECTED_FRIENDS = 2; /** * An enumeration of all the field names in the database. */ public static enum Field { LOCALGROUPID("LocalGroupId"), SERVERGROUPID("ServerGroupId"), GROUPTYPE("GroupType"), ISREADONLY("IsReadOnly"), REQUIRESLOCALISATION("RequiresLocalisation"), ISSYSTEMGROUP("IsSystemGroup"), ISSMARTGROUP("IsSmartGroup"), USERID("UserId"), NAME("Name"), IMAGEMIMETYPE("ImageMimeType"), IMAGEBYTES("ImageBytes"), COLOR("Color"); /** * The 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(String field) { mField = field; } /** * @return the name of the field as it appears in the database. */ public String toString() { return mField; } } /** * Creates Groups Table and populate it with system groups. * * @param context A context for reading strings from the resources * @param writeableDb A writable SQLite database * @throws SQLException If an SQL compilation error occurs */ public static void create(Context context, SQLiteDatabase writableDb) throws SQLException { DatabaseHelper.trace(true, "GroupsTable.create()"); writableDb.execSQL("CREATE TABLE " + TABLE_NAME + " (" + Field.LOCALGROUPID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.SERVERGROUPID + " LONG, " + Field.GROUPTYPE + " INTEGER, " + Field.ISREADONLY + " BOOLEAN, " + Field.REQUIRESLOCALISATION + " BOOLEAN, " + Field.ISSYSTEMGROUP + " BOOLEAN, " + Field.ISSMARTGROUP + " BOOLEAN, " + Field.USERID + " LONG, " + Field.NAME + " TEXT, " + Field.IMAGEMIMETYPE + " TEXT, " + Field.IMAGEBYTES + " BINARY, " + Field.COLOR + " TEXT);"); populateSystemGroups(context, writableDb); } /** * Fetches the list of table fields that can be injected into an SQL query * statement. The {@link #getQueryData(Cursor)} method can be used to obtain * the data from the query. * * @return The query string * @see #getQueryData(Cursor). */ private static String getFullQueryList() { return Field.LOCALGROUPID + ", " + Field.SERVERGROUPID + ", " + Field.GROUPTYPE + ", " + Field.ISREADONLY + ", " + Field.REQUIRESLOCALISATION + ", " + Field.ISSYSTEMGROUP + ", " + Field.ISSMARTGROUP + ", " + Field.USERID + ", " + Field.NAME + ", " + Field.IMAGEMIMETYPE + ", " + Field.IMAGEBYTES + ", " + Field.COLOR; } /** * Returns a full SQL query statement to fetch a set of groups from the * table. The {@link #getQueryData(Cursor)} method can be used to obtain the * data from the query. * * @param whereClause An SQL where clause (without the "WHERE"). Cannot be * null. * @return The query string * @see #getQueryData(Cursor). */ private static String getQueryStringSql(String whereClause) { String whereString = ""; if (whereClause != null) { whereString = " WHERE " + whereClause; } return "SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + whereString; } /** * Column indices which match the query string returned by * {@link #getFullQueryList()}. */ private static final int LOCALGROUPID = 0; private static final int SERVERGROUPID = 1; private static final int GROUPTYPE = 2; private static final int ISREADONLY = 3; private static final int REQUIRESLOCALISATION = 4; private static final int ISSYSTEMGROUP = 5; private static final int ISSMARTGROUP = 6; private static final int USERID = 7; private static final int NAME = 8; private static final int IMAGEMIMETYPE = 9; private static final int IMAGEBYTES = 10; private static final int COLOR = 11; /** * Fetches the group data from the current record of the given cursor. * * @param c Cursor returned by one of the {@link #getFullQueryList()} based * query methods. * @return Filled in GroupItem object */ public static GroupItem getQueryData(Cursor c) { GroupItem group = new GroupItem(); if (!c.isNull(LOCALGROUPID)) { group.mLocalGroupId = c.getLong(LOCALGROUPID); } if (!c.isNull(SERVERGROUPID)) { group.mId = c.getLong(SERVERGROUPID); } if (!c.isNull(GROUPTYPE)) { group.mGroupType = c.getInt(GROUPTYPE); } if (!c.isNull(ISREADONLY)) { group.mIsReadOnly = (c.getShort(ISREADONLY) == 0 ? false : true); } if (!c.isNull(REQUIRESLOCALISATION)) { group.mRequiresLocalisation = (c.getShort(REQUIRESLOCALISATION) == 0 ? false : true); } if (!c.isNull(ISSYSTEMGROUP)) { group.mIsSystemGroup = (c.getShort(ISSYSTEMGROUP) == 0 ? false : true); } if (!c.isNull(ISSMARTGROUP)) { group.mIsSmartGroup = (c.getShort(ISSMARTGROUP) == 0 ? false : true); } if (!c.isNull(USERID)) { group.mUserId = c.getLong(USERID); } if (!c.isNull(NAME)) { group.mName = c.getString(NAME); } if (!c.isNull(IMAGEMIMETYPE)) { group.mImageMimeType = c.getString(IMAGEMIMETYPE); } if (!c.isNull(IMAGEBYTES)) { group.mImageBytes = ByteBuffer.wrap(c.getBlob(IMAGEBYTES)); } if (!c.isNull(COLOR)) { group.mColor = c.getString(COLOR); } return group; } /** * Returns a ContentValues object that can be used to insert or modify a * group in the table. * * @param group The source GroupItem object * @return The ContentValues object containing the data. * @note NULL fields in the given group will not be included in the * ContentValues */ private static ContentValues fillUpdateData(GroupItem group) { ContentValues contactDetailValues = new ContentValues(); if (group.mLocalGroupId != null) { contactDetailValues.put(Field.LOCALGROUPID.toString(), group.mLocalGroupId); } if (group.mId != null) { contactDetailValues.put(Field.SERVERGROUPID.toString(), group.mId); } if (group.mGroupType != null) { contactDetailValues.put(Field.GROUPTYPE.toString(), group.mGroupType); } if (group.mIsReadOnly != null) { contactDetailValues.put(Field.ISREADONLY.toString(), group.mIsReadOnly); } if (group.mRequiresLocalisation != null) { contactDetailValues.put(Field.REQUIRESLOCALISATION.toString(), group.mRequiresLocalisation); } if (group.mIsSystemGroup != null) { contactDetailValues.put(Field.ISSYSTEMGROUP.toString(), group.mIsSystemGroup); } if (group.mIsSmartGroup != null) { contactDetailValues.put(Field.ISSMARTGROUP.toString(), group.mIsSmartGroup); } if (group.mUserId != null) { contactDetailValues.put(Field.USERID.toString(), group.mUserId); } if (group.mName != null) { contactDetailValues.put(Field.NAME.toString(), group.mName); } if (group.mImageMimeType != null) { contactDetailValues.put(Field.IMAGEMIMETYPE.toString(), group.mImageMimeType); } if (group.mImageBytes != null) { contactDetailValues.put(Field.IMAGEBYTES.toString(), group.mImageBytes.array()); } if (group.mColor != null) { contactDetailValues.put(Field.COLOR.toString(), group.mColor); } return contactDetailValues; } /** * Fetches a list of all the available groups. * * @param groupList A list that will be populated with the result. * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error */ public static ServiceStatus fetchGroupList(ArrayList<GroupItem> groupList, SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "GroupsTable.fetchGroupList()"); groupList.clear(); Cursor c = null; try { String query = "SELECT " + getFullQueryList() + " FROM " + TABLE_NAME; c = readableDb.rawQuery(query, null); while (c.moveToNext()) { groupList.add(getQueryData(c)); } } catch (SQLiteException e) { LogUtils.logE("GroupsTable.fetchGroupList() Exception - Unable to fetch group list", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(c); c = null; } return ServiceStatus.SUCCESS; } /** * Adds list of groups to the table * * @param groupList The list to add * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus addGroupList(List<GroupItem> groupList, SQLiteDatabase writableDb) { try { writableDb.beginTransaction(); for (GroupItem mGroupItem : groupList) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(true, "GroupsTable.addGroupList() mName[" + mGroupItem.mName + "]"); } mGroupItem.mLocalGroupId = writableDb.insertOrThrow(TABLE_NAME, null, fillUpdateData(mGroupItem)); if (mGroupItem.mLocalGroupId < 0) { LogUtils.logE("GroupsTable.addGroupList() Unable to add group - mName[" + mGroupItem.mName + ""); writableDb.endTransaction(); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } writableDb.setTransactionSuccessful(); } catch (SQLException e) { LogUtils.logE("GroupsTable.addGroupList() SQLException - Unable to add group", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if (writableDb != null) { writableDb.endTransaction(); } } return ServiceStatus.SUCCESS; } /** * Removes all groups from the table. The * {@link #populateSystemGroups(Context, SQLiteDatabase)} function should be * called afterwards to ensure the system groups are restored. * * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteAllGroups(SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "GroupsTable.deleteAllGroups()"); try { if (writableDb.delete(TABLE_NAME, null, null) < 0) { LogUtils.logE("GroupsTable.deleteAllGroups() Unable to delete all groups"); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } catch (SQLException e) { LogUtils.logE( "GroupsTable.deleteAllGroups() SQLException - Unable to delete all groups", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } return ServiceStatus.SUCCESS; } /** * Fetches a cursor that can be used for browsing the groups. The * {@link #getQueryData(Cursor)} method can be used to fetch the data of a * particular record in the cursor. * * @param readableDb Readable SQLite database * @return The cursor, or null if an error occurs */ public static Cursor getGroupCursor(SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "GroupsTable.getGroupCursor()"); try { return readableDb.rawQuery(getQueryStringSql("NAME != 'Private'"), null); } catch (SQLiteException e) { LogUtils.logE("GroupsTable.getGroupCursor() Exception - Unable to fetch group cursor", e); return null; } } + /** + * Fetches a cursor that can be used for browsing the groups exluding the + * Connected friends item. The {@link #getQueryData(Cursor)} method can be + * used to fetch the data of a particular record in the cursor. + * + * @param readableDb Readable SQLite database + * @return The cursor, or null if an error occurs + */ + public static Cursor getGroupCursorExcludeConnectedFriends( + final SQLiteDatabase readableDb) { + DatabaseHelper.trace(false, + "GroupsTable.getGroupCursorExcludeConnectedFriends()"); + try { + return readableDb.rawQuery( + getQueryStringSql("NAME != 'Private' AND " + + Field.SERVERGROUPID + " != " + + GROUP_CONNECTED_FRIENDS), + null); + + } catch (SQLiteException e) { + LogUtils + .logE( + "GroupsTable.getGroupCursorExcludeConnectedFriends()" + + " Exception - Unable to fetch group" + + " cursor", e); + return null; + } + } + /** * Populates the table if system groups that are specified in the resources. * * @param context The context for reading the app resources * @param writableDb Writable SQLite database for updating the table * @return SUCCESS or a suitable error code */ public static ServiceStatus populateSystemGroups(Context context, SQLiteDatabase writableDb) { final List<GroupItem> groupList = new ArrayList<GroupItem>(); GroupItem all = new GroupItem(); all.mName = context.getString(R.string.ContactListActivity_group_all); all.mIsReadOnly = true; all.mId = GROUP_ALL; groupList.add(all); GroupItem online = new GroupItem(); online.mName = context.getString(R.string.ContactListActivity_group_online); online.mIsReadOnly = true; online.mId = GROUP_ONLINE; groupList.add(online); GroupItem phonebook = new GroupItem(); phonebook.mName = context.getString(R.string.ContactListActivity_group_phonebook); phonebook.mIsReadOnly = true; phonebook.mId = GROUP_PHONEBOOK; groupList.add(phonebook); return addGroupList(groupList, writableDb); } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index 401f190..bd92260 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,318 +1,325 @@ /* * 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.ContactSummary.OnlineStatus; 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 // TODO: this hard code needs change, must filter the identities // info by VCARD.IMADRESS Hashtable<String, String> status = new Hashtable<String, String>(); status.put("google", "online"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("facebook.com", "online"); status.put("hyves.nl", "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 users 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 modifications. */ protected static boolean updateDatabase(List<User> users, long idListeningTo, DatabaseHelper dbHelper) { boolean presenceChanged = false; boolean deleteNetworks = false; // the list of networks presence information for me we ignore - the networks where 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) { 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); } } return !ignoredNetworks.isEmpty(); } protected static boolean updateMyPresence(User user, DatabaseHelper dbHelper) { boolean contactsChanged = false; SQLiteDatabase writableDb = dbHelper.getWritableDatabase(); if (PresenceTable.updateUser(user, null, writableDb) != 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); } } + /** + * @param input + * @return + */ + public static boolean notNullOrBlank(String input) { + return (input != null) && input.length() > 0; + } } diff --git a/src/com/vodafone360/people/service/ServiceUiRequest.java b/src/com/vodafone360/people/service/ServiceUiRequest.java index 4fb2224..b35bae8 100644 --- a/src/com/vodafone360/people/service/ServiceUiRequest.java +++ b/src/com/vodafone360/people/service/ServiceUiRequest.java @@ -1,261 +1,263 @@ /* * 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 */ FETCH_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, /* * 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/utils/LoginPreferences.java b/src/com/vodafone360/people/utils/LoginPreferences.java index f7c6634..b9cf0ce 100644 --- a/src/com/vodafone360/people/utils/LoginPreferences.java +++ b/src/com/vodafone360/people/utils/LoginPreferences.java @@ -1,371 +1,378 @@ /* * 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.util.Calendar; import java.util.GregorianCalendar; import android.content.Context; import android.content.SharedPreferences; import com.vodafone360.people.ApplicationCache; import com.vodafone360.people.datatypes.LoginDetails; import com.vodafone360.people.utils.LogUtils; /*** * Store various preferences used during login in a preferences file. TODO: * Requires some refactoring to clear up underutilised variables. */ public class LoginPreferences { public final static String STORE_PROGRESS = "progress"; private final static String PREFS_PATH = "/data/data/com.vodafone360.people/shared_prefs/"; private final static String SIGNUP_EMAIL_ADDRESS = "SIGNUP_EMAIL_ADDRESS"; private final static String SIGNUP_FIRSTNAME = "SIGNUP_FIRSTNAME"; private final static String SIGNUP_LASTNAME = "SIGNUP_LASTNAME"; private final static String SIGNUP_DOB_DAY = "SIGNUP_DOB_DAY"; private final static String SIGNUP_DOB_MONTH = "SIGNUP_DOB_MONTH"; private final static String SIGNUP_DOB_YEAR = "SIGNUP_DOB_YEAR"; private final static String MOBILE_NUMBER = "MOBILE"; private final static String USERNAME = "USERNAME"; private final static String PASSWORD = "PASSWORD"; private final static String LAST_LOGIN_SCREEN = "NOWPLUS_SCREEN"; private final static String XML_FILE_EXTENSION = ".xml"; /* * Account creation */ // Signup private static String sSignupFirstName = ""; private static String sSignupLastName = ""; private static String sSignupEmailAddress = ""; private static volatile GregorianCalendar sDateOfBirth = null; // Login private static String sMobileNumber = ""; private static String sPassword = ""; private static String sUsername = ""; // TODO: Why are we storing this information twice? private static LoginDetails sLoginDetails = new LoginDetails(); /** * Retrieves the name of the current login activity. Also retrieves login * details from the preferences so that the same screen is displayed when * the user re-enters the wizard. * * @param context - Android context. * @return The name of the current login wizard activity */ public static String getCurrentLoginActivity(Context context) { LogUtils.logV("ApplicationCache.getCurrentLoginActivity()"); SharedPreferences preferences = context .getSharedPreferences(ApplicationCache.PREFS_FILE, 0); // Load sign up settings sSignupEmailAddress = preferences.getString(SIGNUP_EMAIL_ADDRESS, ""); sSignupFirstName = preferences.getString(SIGNUP_FIRSTNAME, ""); sSignupLastName = preferences.getString(SIGNUP_LASTNAME, ""); setSignupDateOfBirth(preferences.getInt(SIGNUP_DOB_DAY, -1), preferences.getInt( SIGNUP_DOB_MONTH, -1), preferences.getInt(SIGNUP_DOB_YEAR, -1)); // Load login Settings sMobileNumber = preferences.getString(MOBILE_NUMBER, ""); sUsername = preferences.getString(USERNAME, ""); sPassword = preferences.getString(PASSWORD, ""); // Return current screen return preferences.getString(LAST_LOGIN_SCREEN, ""); } /** * Stores the name of the current login activity. Also stores the login * details in the preferences so that they can be retrieved when the user * has been diverted away from the login wizard. * * @param loginScreenName The name of the current login wizard activity. */ public static void setCurrentLoginActivity(String loginScreenName, Context context) { LogUtils.logV("MainApplication.setCurrentLoginActivity() loginScreenName[" + loginScreenName + "]"); SharedPreferences.Editor editor = context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).edit(); // Save log in screen name. editor.putString(LAST_LOGIN_SCREEN, loginScreenName); // Save sign up settings. editor.putString(SIGNUP_EMAIL_ADDRESS, sSignupEmailAddress); editor.putString(SIGNUP_FIRSTNAME, sSignupFirstName); editor.putString(SIGNUP_LASTNAME, sSignupLastName); editor.putInt(SIGNUP_DOB_DAY, sDateOfBirth != null ? sDateOfBirth .get(Calendar.DAY_OF_MONTH) : -1); editor.putInt(SIGNUP_DOB_MONTH, sDateOfBirth != null ? sDateOfBirth.get(Calendar.MONTH) : -1); editor.putInt(SIGNUP_DOB_YEAR, sDateOfBirth != null ? sDateOfBirth.get(Calendar.YEAR) : -1); // Save login settings. editor.putString(MOBILE_NUMBER, sMobileNumber); editor.putString(USERNAME, sUsername); editor.putString(PASSWORD, sPassword); if (!editor.commit()) { throw new NullPointerException("MainApplication.setCurrentLoginActivity() Failed to" + " set current login activity"); } } /** * Clear cached login details. */ public static void clearCachedLoginDetails() { // Clear sign up settings. sSignupEmailAddress = ""; sSignupFirstName = ""; sSignupLastName = ""; sDateOfBirth = null; // Clear login settings. sMobileNumber = ""; sUsername = ""; sPassword = ""; sLoginDetails = new LoginDetails(); } /** * Store current login details. * * @param loginDetails Current login details. */ public static void setLoginDetails(LoginDetails loginDetails) { sLoginDetails = loginDetails; } /** * Re-initialise login details currently held in application cache. */ public static void initLoginDetails() { sLoginDetails = new LoginDetails(); } /** * Gets the current set of login parameters. * * @return current login details. */ public static LoginDetails getLoginDetails() { return sLoginDetails; } /** * Gets the current login password. * * @return The current user entered login password. */ public static String getPassword() { return sPassword; } /** * Sets the current login password. * * @param aPassword login password */ public static void setPassword(String aPassword) { sPassword = aPassword; } /** * Gets the current login user name. * * @return The current user entered login user name. */ public static String getUsername() { return sUsername; } /** * Sets the current login user name. * * @param username login user name */ public static void setUsername(String username) { sUsername = username; } /** * Gets the current login mobile number. * * @return The current user entered login password */ public static String getMobileNumber() { return sMobileNumber; } /** * Sets the current login mobile number. * * @param mobileNumber login mobile number */ public static void setMobileNumber(String mobileNumber) { sMobileNumber = mobileNumber; } /** * Sets the current account creation email address. * * @param aEmailAddress account signup email address */ public static void setSignupEmailAddress(String aEmailAddress) { sSignupEmailAddress = aEmailAddress; } /** * Retrieves the current account creation email address. * * @return Currently stored account creation email address */ public static String getSignupEmailAddress() { return sSignupEmailAddress; } /** * Sets the current account creation first name. * * @param aFirstName account creation first name */ public static void setSignupFirstName(String aFirstName) { sSignupFirstName = aFirstName; } /** * Sets the current account creation last name. * * @param aLastName account creation last name */ public static void setSignupLastName(String aLastName) { sSignupLastName = aLastName; } /** * Retrieves the current account creation first name. * * @return Current account creation first name */ public static String getSignupFirstName() { return sSignupFirstName; } /** * Retrieves the current account creation last name. * * @return Current account creation last name */ public static String getSignupLastName() { return sSignupLastName; } /** * Return the date of birth from current account details. * * @return Date containing date of birth */ public static GregorianCalendar getSignupDateOfBirth() { if (sDateOfBirth != null) { LogUtils.logV("MainApplication.getSignupDateOfBirth() mDateOfBirth[" + sDateOfBirth.toString() + "]"); } else { LogUtils.logV("MainApplication.getSignupDateOfBirth() mDateOfBirth is NULL"); } return sDateOfBirth; } /** * Set date of birth for current account. * * @param day Date of birth within month. * @param month Month of birth * @param year Year of birth */ public static void setSignupDateOfBirth(int day, int month, int year) { LogUtils.logV("MainApplication.setSignupDateOfBirth() DOB: " + day + " " + month + " " + year); if (day < 0 || month < 0 || year < 0) { return; } if (sDateOfBirth == null) { sDateOfBirth = new GregorianCalendar(year, month, day); } sDateOfBirth.set(year, month, day); } - + + /** + * reset object of GregorianCalendar to be null when user input invalid + * birthday date in signup screen. + */ + public static void resetSignupDateOfBirth() { + sDateOfBirth = null; + } /** * Clears all details stored in the preferences. */ public static void clearPreferencesFile(Context context) { LogUtils.logV("MainApplication.clearPreferencesFile()"); SharedPreferences.Editor editor = context.getSharedPreferences(ApplicationCache.PREFS_FILE, 0).edit(); editor.clear(); if (editor.commit()) { LogUtils.logV("MainApplication.clearPreferencesFile() All preferences cleared"); } else { LogUtils.logE("MainApplication.clearPreferencesFile() Failed to clear preferences"); } // TODO: Is is necessary to delete the original file? // Login details are stored in the preferences file below so that // they can be used to pre-populate the edit fields if the // user is interrupted in the middle of login/signup // Delete this file as this function is called by remove user data // functionality if (!new File(PREFS_PATH + ApplicationCache.PREFS_FILE + XML_FILE_EXTENSION).delete()) { LogUtils.logE("LoginPreferences.clearPreferencesFile(context) failed"); } } }
360/360-Engine-for-Android
0f17ba77fea2b7333c1dd108b79b44dff551ea6f
Fixes to JUnit tests
diff --git a/tests/src/com/vodafone360/people/tests/service/transport/tcp/conn_less/respreader/ResponseReaderThreadTest.java b/tests/src/com/vodafone360/people/tests/service/transport/tcp/conn_less/respreader/ResponseReaderThreadTest.java index 646c0f0..62ddd85 100644 --- a/tests/src/com/vodafone360/people/tests/service/transport/tcp/conn_less/respreader/ResponseReaderThreadTest.java +++ b/tests/src/com/vodafone360/people/tests/service/transport/tcp/conn_less/respreader/ResponseReaderThreadTest.java @@ -1,261 +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.tests.service.transport.tcp.conn_less.respreader; +import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.util.Arrays; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.Suppress; import com.vodafone360.people.service.transport.DecoderThread; import com.vodafone360.people.tests.service.transport.tcp.conn_less.hb_tests.MockTcpConnectionThread; public class ResponseReaderThreadTest extends InstrumentationTestCase { public void setUp() throws Exception {} public void tearDown() throws Exception {} @Suppress @MediumTest public void testStartConnection() { DecoderThread decoder = new DecoderThread(); MockTcpConnectionThread mockThread = new MockTcpConnectionThread(decoder, null); MockResponseReaderThread respReader = new MockResponseReaderThread(mockThread, decoder, null // QUICKFIX: Not sure about this value ); MockOTAInputStream mIs = new MockOTAInputStream( new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5})); - respReader.setInputStream(mIs); + respReader.setInputStream(new BufferedInputStream(mIs)); assertNull(respReader.getConnectionThread()); respReader.startConnection(); try { Thread.sleep(1000); } catch (InterruptedException e) {} assertNotNull(respReader.getConnectionThread()); if (null != respReader.getConnectionThread()) { assertTrue(respReader.getConnectionThread().isAlive()); } assertTrue(respReader.getIsConnectionRunning()); } @Suppress @MediumTest public void testStopConnection() { DecoderThread decoder = new DecoderThread(); MockTcpConnectionThread mockThread = new MockTcpConnectionThread(decoder, null); MockResponseReaderThread respReader = new MockResponseReaderThread(mockThread, decoder, null // QUICKFIX: Not sure about this value ); MockOTAInputStream mIs = new MockOTAInputStream( new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5})); - respReader.setInputStream(mIs); + respReader.setInputStream(new BufferedInputStream(mIs)); respReader.startConnection(); try { Thread.sleep(1000); } catch (InterruptedException e) {} Thread t = respReader.getConnectionThread(); assertNotNull(t); if (null != t) { assertTrue(t.isAlive()); assertTrue(respReader.getIsConnectionRunning()); } // now comes the actual test respReader.stopConnection(); try { Thread.sleep(1000); } catch (InterruptedException e) {} assertNull(respReader.getInputStream()); assertNull(respReader.getConnectionThread()); assertFalse(respReader.getIsConnectionRunning()); } @MediumTest public void testSetInputstream() { DecoderThread decoder = new DecoderThread(); MockTcpConnectionThread mockThread = new MockTcpConnectionThread(decoder, null); MockResponseReaderThread respReader = new MockResponseReaderThread(mockThread, decoder, null // QUICKFIX: Not sure about this value ); ByteArrayInputStream bais = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5}); - respReader.setInputStream(bais); + respReader.setInputStream(new BufferedInputStream(bais)); DataInputStream dis = (DataInputStream) respReader.getInputStream(); assertNotNull(dis); // let's test all the bytes... if (null != dis) { boolean areBytesCorrect = true; for (int i = 1; i < 6; i++) { try { int j = dis.readByte(); if (-1 == j) { fail("Unexpected end of the DataInputStream"); areBytesCorrect = false; } else if (i != j) { fail("Characters differ: i: " + i + " vs. j: " + j); areBytesCorrect = false; } } catch (IOException e) {} } assertTrue(areBytesCorrect); } respReader.setInputStream(null); assertNull(respReader.getInputStream()); } @Suppress @MediumTest public void testRun_exception() { DecoderThread decoder = new DecoderThread(); MockTcpConnectionThread mockThread = new MockTcpConnectionThread(decoder, null); MockResponseReaderThread respReader = new MockResponseReaderThread(mockThread, decoder, null // QUICKFIX: Not sure about this value ); MockOTAInputStream mIs = new MockOTAInputStream( new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5})); - respReader.setInputStream(mIs); + respReader.setInputStream(new BufferedInputStream(mIs)); // IO Exception test try { mIs.close(); } catch (IOException e) {} respReader.startConnection(); try { Thread.sleep(1000); } catch (Exception e) {} assertTrue(mockThread.getDidErrorOccur()); respReader.stopConnection(); mockThread = null; respReader = null; // NP Exception test mockThread = new MockTcpConnectionThread(new DecoderThread(), null); respReader = new MockResponseReaderThread(mockThread, decoder, null // QUICKFIX: Not sure about this value ); respReader.setInputStream(null); respReader.startConnection(); try { Thread.sleep(1000); } catch (Exception e) {} assertTrue(mockThread.getDidErrorOccur()); respReader.stopConnection(); mockThread = null; respReader = null; // EOF Exception mockThread = new MockTcpConnectionThread(new DecoderThread(), null); respReader = new MockResponseReaderThread(mockThread, decoder, null // QUICKFIX: Not sure about this value ); ByteArrayInputStream bais = new ByteArrayInputStream(new byte[] {1}); - respReader.setInputStream(bais); + respReader.setInputStream(new BufferedInputStream(bais)); respReader.startConnection(); try { Thread.sleep(1000); } catch (Exception e) {} assertTrue(mockThread.getDidErrorOccur()); respReader.stopConnection(); mockThread = null; respReader = null; } /*** * Test DecoderThread.getResponse() call. */ @Suppress @MediumTest public void testReadNextResponse() { /** Happy path test that runs through one whole response. **/ MockDecoderThread decoder = new MockDecoderThread(); MockTcpConnectionThread mockThread = new MockTcpConnectionThread(decoder, null); MockResponseReaderThread respReader = new MockResponseReaderThread(mockThread, decoder, null // QUICKFIX: Not sure about this value ); byte[] payload = new byte[] { /*** RPG header. **/ ((byte) 0xFF), ((byte) 0xFF), 0x04, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 5, 0, /** 5 bytes of payload. **/ 1, 2, 3, 4, 5 }; ByteArrayInputStream bais = new ByteArrayInputStream(payload); - respReader.setInputStream(bais); + respReader.setInputStream(new BufferedInputStream(bais)); respReader.startConnection(); try { Thread.sleep(2000); } catch (InterruptedException ie) { // Do nothing. } assertNotNull("The decoder response should not have been NULL", decoder.getResponse()); assertTrue("Incorrect payload", Arrays.equals(payload, decoder.getResponse())); respReader.stopConnection(); payload = null; respReader = null; mockThread = null; decoder = null; bais = null; /** Sad path test where the 2nd byte is not the delimiter. **/ decoder = new MockDecoderThread(); mockThread = new MockTcpConnectionThread(decoder, null); respReader = new MockResponseReaderThread(mockThread, decoder, null // QUICKFIX: Not sure about this value ); payload = new byte[] { 1, ((byte) 0xFF) }; respReader.startConnection(); try { Thread.sleep(2000); } catch (InterruptedException ie) {} assertNull(decoder.getResponse()); respReader.stopConnection(); payload = null; respReader = null; mockThread = null; decoder = null; bais = null; } } \ No newline at end of file diff --git a/tests/src/com/vodafone360/people/tests/ui/utils/SimNetworkTest.java b/tests/src/com/vodafone360/people/tests/ui/utils/SimNetworkTest.java deleted file mode 100644 index 614bd0b..0000000 --- a/tests/src/com/vodafone360/people/tests/ui/utils/SimNetworkTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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.ui.utils; - -import com.vodafone360.people.ui.utils.SimNetwork; -import com.vodafone360.people.utils.LogUtils; - -import junit.framework.TestCase; - -public class SimNetworkTest extends TestCase { - - public SimNetworkTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testGetNetwork() { - - assertEquals("NULL country didn't return SimNetwork.UNKNOWN", SimNetwork.UNKNOWN, SimNetwork.getNetwork(null)); - assertEquals("Non existing country didn't return SimNetwork.UNKNOWN",SimNetwork.UNKNOWN, SimNetwork.getNetwork("non existing country")); - assertEquals("Empty country didn't return SimNetwork.UNKNOWN", SimNetwork.UNKNOWN, SimNetwork.getNetwork("")); - assertEquals("Blank country didn't return SimNetwork.UNKNOWN", SimNetwork.UNKNOWN, SimNetwork.getNetwork(" ")); - - LogUtils.logV("CORRUPTED DATA TESTS FINISHED"); - - assertEquals(SimNetwork.CH, SimNetwork.getNetwork(SimNetwork.CH.iso())); - assertEquals(SimNetwork.DE, SimNetwork.getNetwork(SimNetwork.DE.iso())); - assertEquals(SimNetwork.FR, SimNetwork.getNetwork(SimNetwork.FR.iso())); - assertEquals(SimNetwork.GB, SimNetwork.getNetwork(SimNetwork.GB.iso())); - assertEquals(SimNetwork.IE, SimNetwork.getNetwork(SimNetwork.IE.iso())); - assertEquals(SimNetwork.IT, SimNetwork.getNetwork(SimNetwork.IT.iso())); - assertEquals(SimNetwork.NL, SimNetwork.getNetwork(SimNetwork.NL.iso())); - assertEquals(SimNetwork.SE, SimNetwork.getNetwork(SimNetwork.SE.iso())); - assertEquals(SimNetwork.TR, SimNetwork.getNetwork(SimNetwork.TR.iso())); - assertEquals(SimNetwork.TW, SimNetwork.getNetwork(SimNetwork.TW.iso())); - assertEquals(SimNetwork.US, SimNetwork.getNetwork(SimNetwork.US.iso())); - assertEquals(SimNetwork.ES, SimNetwork.getNetwork(SimNetwork.ES.iso())); - - LogUtils.logV("SETTINGS DATA TESTS FINISHED"); - } -} \ No newline at end of file diff --git a/tests/src/com/vodafone360/people/tests/ui/utils/SimUtilsTest.java b/tests/src/com/vodafone360/people/tests/ui/utils/SimUtilsTest.java deleted file mode 100644 index b2b6bf8..0000000 --- a/tests/src/com/vodafone360/people/tests/ui/utils/SimUtilsTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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.ui.utils; - -import junit.framework.TestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import com.vodafone360.people.ui.utils.SimUtils; - -public class SimUtilsTest extends TestCase { - - @SmallTest - public void testGetVerifyedMsisdn() throws Exception { - assertEquals("", SimUtils.getVerifyedMsisdn(null, null, null, null)); - assertEquals("", SimUtils.getVerifyedMsisdn("", null, null, null)); - assertEquals("", SimUtils.getVerifyedMsisdn("1234567890", null, null, null)); - assertEquals("+1234567890", SimUtils.getVerifyedMsisdn("+1234567890", null, null, null)); - assertEquals("+4900000000", SimUtils.getVerifyedMsisdn("004900000000", null, null, null)); - - //Real data tests - assertEquals("", SimUtils.getVerifyedMsisdn("", "de", "Vodafone.de", "26202")); - assertEquals("", SimUtils.getVerifyedMsisdn("", "au", "Vodafone.au", "26202")); - assertEquals("+41700000000", SimUtils.getVerifyedMsisdn("+41700000000", "ch", "Swisscom", "22801")); - assertEquals("+491720000000", SimUtils.getVerifyedMsisdn("01720000000", "de", "Vodafone.de", "26202")); - assertEquals("+447960000000", SimUtils.getVerifyedMsisdn("07960000000", "gb", "Orange", "23433")); - assertEquals("+31600000000", SimUtils.getVerifyedMsisdn("+31600000000", "nl", "vodafone NL", "20404")); - assertEquals("+46700000000", SimUtils.getVerifyedMsisdn("+46700000000", "se", "Sweden3G", "24005")); - assertEquals("+886988000000", SimUtils.getVerifyedMsisdn("0988000000", "tw", "????", "46692")); - assertEquals("+15550000000", SimUtils.getVerifyedMsisdn("15550000000", "us", "Android", "310260")); //Emulator - assertEquals("+15500000000", SimUtils.getVerifyedMsisdn("+15500000000", "us", "Android", "310260")); //Emulator - } - - @SmallTest - public void testGetAnonymisedMsisdn() throws Exception { - assertEquals("", SimUtils.getAnonymisedMsisdn(null)); - assertEquals("", SimUtils.getAnonymisedMsisdn("")); - assertEquals("1", SimUtils.getAnonymisedMsisdn("1")); - assertEquals("12", SimUtils.getAnonymisedMsisdn("12")); - assertEquals("123", SimUtils.getAnonymisedMsisdn("123")); - assertEquals("1234", SimUtils.getAnonymisedMsisdn("1234")); - assertEquals("12340", SimUtils.getAnonymisedMsisdn("12345")); - assertEquals("1234000000", SimUtils.getAnonymisedMsisdn("1234567890")); - assertEquals("+1230000000", SimUtils.getAnonymisedMsisdn("+1234567890")); - } -} \ No newline at end of file diff --git a/tests/src/com/vodafone360/people/tests/ui/utils/interfaces/DialogEventTest.java b/tests/src/com/vodafone360/people/tests/ui/utils/interfaces/DialogEventTest.java deleted file mode 100644 index 20f8cd7..0000000 --- a/tests/src/com/vodafone360/people/tests/ui/utils/interfaces/DialogEventTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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.ui.utils.interfaces; - -import junit.framework.TestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import com.vodafone360.people.service.ServiceUiRequest; -import com.vodafone360.people.ui.utils.interfaces.DialogEvent; - -public class DialogEventTest extends TestCase { - - @SmallTest - public void testGetUiEvent() throws Exception { - - // Normal use - assertEquals(DialogEvent.DIALOG_UPGRADE, DialogEvent - .getDialogEvent(DialogEvent.DIALOG_UPGRADE.ordinal())); - assertEquals(DialogEvent.UNKNOWN, DialogEvent.getDialogEvent(DialogEvent.UNKNOWN.ordinal())); - - // Border conditions - assertEquals(DialogEvent.UNKNOWN, DialogEvent.getDialogEvent(-100)); - assertEquals(DialogEvent.UNKNOWN, DialogEvent.getDialogEvent(-1)); - assertEquals(DialogEvent.UNKNOWN, DialogEvent.getDialogEvent(ServiceUiRequest.UNKNOWN - .ordinal() + 1)); - assertEquals(DialogEvent.UNKNOWN, DialogEvent.getDialogEvent(100)); - } -} diff --git a/tests/src/com/vodafone360/people/tests/ui/utils/interfaces/UiEventTest.java b/tests/src/com/vodafone360/people/tests/ui/utils/interfaces/UiEventTest.java deleted file mode 100644 index 45eec84..0000000 --- a/tests/src/com/vodafone360/people/tests/ui/utils/interfaces/UiEventTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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.ui.utils.interfaces; - -import junit.framework.TestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import com.vodafone360.people.service.ServiceUiRequest; - -public class UiEventTest extends TestCase { - - @SmallTest - public void testGetUiEvent() throws Exception { - - // Normal use - assertEquals(ServiceUiRequest.UI_REQUEST_COMPLETE, ServiceUiRequest - .getUiEvent(ServiceUiRequest.UI_REQUEST_COMPLETE.ordinal())); - assertEquals(ServiceUiRequest.DATABASE_CHANGED_EVENT, ServiceUiRequest - .getUiEvent(ServiceUiRequest.DATABASE_CHANGED_EVENT.ordinal())); - assertEquals(ServiceUiRequest.SETTING_CHANGED_EVENT, ServiceUiRequest - .getUiEvent(ServiceUiRequest.SETTING_CHANGED_EVENT.ordinal())); - assertEquals(ServiceUiRequest.UNSOLICITED_CHAT, ServiceUiRequest - .getUiEvent(ServiceUiRequest.UNSOLICITED_CHAT.ordinal())); - assertEquals(ServiceUiRequest.UNSOLICITED_PRESENCE, ServiceUiRequest - .getUiEvent(ServiceUiRequest.UNSOLICITED_PRESENCE.ordinal())); - assertEquals(ServiceUiRequest.UNSOLICITED_GO_TO_LANDING_PAGE, ServiceUiRequest - .getUiEvent(ServiceUiRequest.UNSOLICITED_GO_TO_LANDING_PAGE.ordinal())); - assertEquals(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, ServiceUiRequest - .getUiEvent(ServiceUiRequest.UNSOLICITED_CHAT_ERROR.ordinal())); - assertEquals(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, ServiceUiRequest - .getUiEvent(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH.ordinal())); - assertEquals(ServiceUiRequest.UNSOLICITED_PRESENCE_ERROR, ServiceUiRequest - .getUiEvent(ServiceUiRequest.UNSOLICITED_PRESENCE_ERROR.ordinal())); - assertEquals(ServiceUiRequest.UNKNOWN, ServiceUiRequest.getUiEvent(ServiceUiRequest.UNKNOWN - .ordinal())); - - // Border conditions - assertEquals(ServiceUiRequest.UNKNOWN, ServiceUiRequest.getUiEvent(-100)); - assertEquals(ServiceUiRequest.UNKNOWN, ServiceUiRequest.getUiEvent(-1)); - assertEquals(ServiceUiRequest.UNKNOWN, ServiceUiRequest.getUiEvent(ServiceUiRequest.UNKNOWN - .ordinal() + 1)); - assertEquals(ServiceUiRequest.UNKNOWN, ServiceUiRequest.getUiEvent(100)); - } -}
360/360-Engine-for-Android
a7f9f1d10f6ebd12da43e02f61c0aa539a173697
adding config.properties to ignorelist
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bace426 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +config.properties
360/360-Engine-for-Android
755249cf17eae8e571f40e4a968e4375f5b9521a
Merging CLRF errors
diff --git a/src/com/caucho/hessian/micro/MicroHessianInput.java b/src/com/caucho/hessian/micro/MicroHessianInput.java index 1fa53f8..b2776d5 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 - // 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(); - } - - 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; - } - } -} +/* + * 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 + // 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(); + } + + 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/service/transport/DecoderThread.java b/src/com/vodafone360/people/service/transport/DecoderThread.java index 5b4b1db..8e34246 100644 --- a/src/com/vodafone360/people/service/transport/DecoderThread.java +++ b/src/com/vodafone360/people/service/transport/DecoderThread.java @@ -1,333 +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.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 engine = 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; - engine = request.mEngineId; - } else { - type = Type.COMMON; - } - } - - // Set an engine id via Hessian decoder - - List<BaseDataType> data = mHessianDecoder.decodeHessianByteArray(decode.mData, - type, decode.mIsCompressed); - - if (type == Type.PUSH_MSG && data.size() != 0 - && data.get(0) instanceof PushEvent) { - engine = ((PushEvent)data.get(0)).mEngineId; - } - - // 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 && engine == EngineId.UNDEFINED) { - Request request = QueueManager.getInstance().getRequest(reqId); - if (request != null) { - engine = request.mEngineId; - } - } - - if (engine == 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[" + engine + "] with data [" + data - + "]"); - mRespQueue.addToResponseQueue(decode.mReqId, data, engine); - - // 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 && engine != EngineId.UNDEFINED) { - List<BaseDataType> list = new ArrayList<BaseDataType>(); - ServerError error = new ServerError(); - // this error type was chosen to make engines remove request - // or retry - // we may consider using other error code later - error.errorType = ServerError.ErrorTypes.INTERNALERROR.name(); - error.errorValue = "Decoder thread was unable to decode server message"; - list.add(error); - mRespQueue.addToResponseQueue(reqId, list, engine); - } - 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; - } - } - } - } - } -} +/* + * 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.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 engine = 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; + engine = request.mEngineId; + } else { + type = Type.COMMON; + } + } + + // Set an engine id via Hessian decoder + + List<BaseDataType> data = mHessianDecoder.decodeHessianByteArray(decode.mData, + type, decode.mIsCompressed); + + if (type == Type.PUSH_MSG && data.size() != 0 + && data.get(0) instanceof PushEvent) { + engine = ((PushEvent)data.get(0)).mEngineId; + } + + // 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 && engine == EngineId.UNDEFINED) { + Request request = QueueManager.getInstance().getRequest(reqId); + if (request != null) { + engine = request.mEngineId; + } + } + + if (engine == 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[" + engine + "] with data [" + data + + "]"); + mRespQueue.addToResponseQueue(decode.mReqId, data, engine); + + // 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 && engine != EngineId.UNDEFINED) { + List<BaseDataType> list = new ArrayList<BaseDataType>(); + ServerError error = new ServerError(); + // this error type was chosen to make engines remove request + // or retry + // we may consider using other error code later + error.errorType = ServerError.ErrorTypes.INTERNALERROR.name(); + error.errorValue = "Decoder thread was unable to decode server message"; + list.add(error); + mRespQueue.addToResponseQueue(reqId, list, engine); + } + 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; + } + } + } + } + } +} diff --git a/src/com/vodafone360/people/service/transport/tcp/ResponseReaderThread.java b/src/com/vodafone360/people/service/transport/tcp/ResponseReaderThread.java index 5e9058a..ca14631 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 - } - - 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 - } - } -} +/* + * 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 + } + + 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 849b163..42e4aa0 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(); - 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()); - } - - 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) { - } -} +/* + * 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(); + 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()); + } + + 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) { + } +} diff --git a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java index dd1a32d..8dd78f2 100644 --- a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java +++ b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java @@ -1,493 +1,493 @@ -/* - * 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.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 data byte array containing Hessian encoded data - * @param type Event type - * @return List of BaseDataType items parsed from Hessian data - * @throws IOException - */ - public List<BaseDataType> decodeHessianByteArray(byte[] data, Request.Type type, - boolean isZipped) 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); - } - - List<BaseDataType> mBaseDataTypeList = null; - mMicroHessianInput.init(is); - - LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); - try { - mBaseDataTypeList = decodeResponse(is, type); - } catch (IOException e) { - LogUtils.logE("HessianDecoder.decodeHessianByteArray() " - + "IOException during decodeResponse", e); - } - - CloseUtils.close(bis); - CloseUtils.close(is); - return mBaseDataTypeList; - } - - @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; - } - } - - /** - * TODO: we cast every response to a Map, losing e.g. push event "c0" which - * only contains a string - to fix - * - * @param is - * @param type - * @return - * @throws IOException - */ - @SuppressWarnings("unchecked") - private List<BaseDataType> decodeResponse(InputStream is, Request.Type type) throws IOException { - boolean usesReplyTag = false; - List<BaseDataType> mResultList = 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(); - zybErr.errorType = mMicroHessianInput.readFault().errString(); - mResultList.add(zybErr); - return mResultList; - } - - // 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(mResultList, is, tag); - return mResultList; - } - - // 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); - decodeResponseByRequestType(mResultList, hash, type); - } else { // if we have a common request - 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); - - mResultList.add(auth.createFromHashtable(authHash)); - } else if (map.containsKey(KEY_CONTACT_LIST)) { - // contact list - getContacts(mResultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); - } 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) { - mResultList.add(UserProfile.createFromHashtable(obj)); - } - } else if (map.containsKey(KEY_USER_PROFILE)) { - Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map - .get(KEY_USER_PROFILE); - mResultList.add(UserProfile.createFromHashtable(userProfileHash)); - } else if ((map.containsKey(KEY_IDENTITY_LIST)) - || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { - Vector<Hashtable<String, Object>> idcap = null; - if (map.containsKey(KEY_IDENTITY_LIST)) { - idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); - } else { - idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); - } - - for (Hashtable<String, Object> obj : idcap) { - Identity id = new Identity(); - mResultList.add(id.createFromHashtable(obj)); - } - - } 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) { - mResultList.add(ActivityItem.createFromHashtable(obj)); - } - } - } - - if (usesReplyTag) { - is.read(); // read the last 'z' - } - - return mResultList; - } - - 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); - } - - private void decodeResponseByRequestType(List<BaseDataType> clist, - Hashtable<String, Object> hash, Request.Type type) { - switch (type) { - case CONTACT_CHANGES_OR_UPDATES: - - // create ContactChanges - ContactChanges contChanges = new ContactChanges(); - contChanges = contChanges.createFromHashtable(hash); - clist.add(contChanges); - break; - - case ADD_CONTACT: - case SIGN_UP: - clist.add(Contact.createFromHashtable(hash)); - break; - case RETRIEVE_PUBLIC_KEY: - // AA define new object type - clist.add(PublicKeyDetails.createFromHashtable(hash)); - break; - - case FRIENDSHIP_REQUEST: - 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); - break; - case CONTACT_DETAIL_DELETE: - ContactDetailDeletion cdel = new ContactDetailDeletion(); - clist.add(cdel.createFromHashtable(hash)); - break; - - case USER_INVITATION: - // Not currently supported. - break; - - case CONTACT_GROUP_RELATION_LIST: - ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); - groupRelationList.populateFromHashtable(hash); - clist.add(groupRelationList); - break; - - case CONTACT_GROUP_RELATIONS: - ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); - groupRelationsList.populateFromHashtable(hash); - clist.add(groupRelationsList); - break; - - case GROUP_LIST: - ItemList zyblist = new ItemList(ItemList.Type.group_privacy); - zyblist.populateFromHashtable(hash); - clist.add(zyblist); - break; - - case ITEM_LIST_OF_LONGS: - ItemList listOfLongs = new ItemList(ItemList.Type.long_value); - listOfLongs.populateFromHashtable(hash); - clist.add(listOfLongs); - break; - - case STATUS_LIST: - ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); - zybstatlist.populateFromHashtable(hash); - clist.add(zybstatlist); - 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); - } - break; - - case EXPECTING_STATUS_ONLY: - StatusMsg statMsg = new StatusMsg(); - clist.add(statMsg.createFromHashtable(hash)); - - break; - - case STATUS: - StatusMsg s = new StatusMsg(); - s.mStatus = true; - clist.add(s); - break; - - case PRESENCE_LIST: - PresenceList mPresenceList = new PresenceList(); - mPresenceList.createFromHashtable(hash); - clist.add(mPresenceList); - break; - - case PUSH_MSG: - // parse content of RPG Push msg - parsePushMessage(clist, hash); - break; - case CREATE_CONVERSATION: - Conversation mConversation = new Conversation(); - mConversation.createFromHashtable(hash); - clist.add(mConversation); - break; - default: - LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" - + type.name() + "]"); - } - } - - 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: - case IDENTITY_CHANGE: - engineId = EngineId.PRESENCE_ENGINE; - break; - case SYSTEM_NOTIFICATION: - LogUtils.logE("SYSTEM_NOTIFICATION push msg:" + msg.mHash); - list.add(SystemNotification.createFromHashtable(msg.mHash, engineId)); - return; - case IDENTITY_NETWORK_CHANGE: - break; - default: - - } - - list.add(PushEvent.createPushEvent(msg, engineId)); - } - } -} +/* + * 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.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 data byte array containing Hessian encoded data + * @param type Event type + * @return List of BaseDataType items parsed from Hessian data + * @throws IOException + */ + public List<BaseDataType> decodeHessianByteArray(byte[] data, Request.Type type, + boolean isZipped) 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); + } + + List<BaseDataType> mBaseDataTypeList = null; + mMicroHessianInput.init(is); + + LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); + try { + mBaseDataTypeList = decodeResponse(is, type); + } catch (IOException e) { + LogUtils.logE("HessianDecoder.decodeHessianByteArray() " + + "IOException during decodeResponse", e); + } + + CloseUtils.close(bis); + CloseUtils.close(is); + return mBaseDataTypeList; + } + + @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; + } + } + + /** + * TODO: we cast every response to a Map, losing e.g. push event "c0" which + * only contains a string - to fix + * + * @param is + * @param type + * @return + * @throws IOException + */ + @SuppressWarnings("unchecked") + private List<BaseDataType> decodeResponse(InputStream is, Request.Type type) throws IOException { + boolean usesReplyTag = false; + List<BaseDataType> mResultList = 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(); + zybErr.errorType = mMicroHessianInput.readFault().errString(); + mResultList.add(zybErr); + return mResultList; + } + + // 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(mResultList, is, tag); + return mResultList; + } + + // 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); + decodeResponseByRequestType(mResultList, hash, type); + } else { // if we have a common request + 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); + + mResultList.add(auth.createFromHashtable(authHash)); + } else if (map.containsKey(KEY_CONTACT_LIST)) { + // contact list + getContacts(mResultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); + } 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) { + mResultList.add(UserProfile.createFromHashtable(obj)); + } + } else if (map.containsKey(KEY_USER_PROFILE)) { + Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map + .get(KEY_USER_PROFILE); + mResultList.add(UserProfile.createFromHashtable(userProfileHash)); + } else if ((map.containsKey(KEY_IDENTITY_LIST)) + || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { + Vector<Hashtable<String, Object>> idcap = null; + if (map.containsKey(KEY_IDENTITY_LIST)) { + idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); + } else { + idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); + } + + for (Hashtable<String, Object> obj : idcap) { + Identity id = new Identity(); + mResultList.add(id.createFromHashtable(obj)); + } + + } 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) { + mResultList.add(ActivityItem.createFromHashtable(obj)); + } + } + } + + if (usesReplyTag) { + is.read(); // read the last 'z' + } + + return mResultList; + } + + 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); + } + + private void decodeResponseByRequestType(List<BaseDataType> clist, + Hashtable<String, Object> hash, Request.Type type) { + switch (type) { + case CONTACT_CHANGES_OR_UPDATES: + + // create ContactChanges + ContactChanges contChanges = new ContactChanges(); + contChanges = contChanges.createFromHashtable(hash); + clist.add(contChanges); + break; + + case ADD_CONTACT: + case SIGN_UP: + clist.add(Contact.createFromHashtable(hash)); + break; + case RETRIEVE_PUBLIC_KEY: + // AA define new object type + clist.add(PublicKeyDetails.createFromHashtable(hash)); + break; + + case FRIENDSHIP_REQUEST: + 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); + break; + case CONTACT_DETAIL_DELETE: + ContactDetailDeletion cdel = new ContactDetailDeletion(); + clist.add(cdel.createFromHashtable(hash)); + break; + + case USER_INVITATION: + // Not currently supported. + break; + + case CONTACT_GROUP_RELATION_LIST: + ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); + groupRelationList.populateFromHashtable(hash); + clist.add(groupRelationList); + break; + + case CONTACT_GROUP_RELATIONS: + ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); + groupRelationsList.populateFromHashtable(hash); + clist.add(groupRelationsList); + break; + + case GROUP_LIST: + ItemList zyblist = new ItemList(ItemList.Type.group_privacy); + zyblist.populateFromHashtable(hash); + clist.add(zyblist); + break; + + case ITEM_LIST_OF_LONGS: + ItemList listOfLongs = new ItemList(ItemList.Type.long_value); + listOfLongs.populateFromHashtable(hash); + clist.add(listOfLongs); + break; + + case STATUS_LIST: + ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); + zybstatlist.populateFromHashtable(hash); + clist.add(zybstatlist); + 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); + } + break; + + case EXPECTING_STATUS_ONLY: + StatusMsg statMsg = new StatusMsg(); + clist.add(statMsg.createFromHashtable(hash)); + + break; + + case STATUS: + StatusMsg s = new StatusMsg(); + s.mStatus = true; + clist.add(s); + break; + + case PRESENCE_LIST: + PresenceList mPresenceList = new PresenceList(); + mPresenceList.createFromHashtable(hash); + clist.add(mPresenceList); + break; + + case PUSH_MSG: + // parse content of RPG Push msg + parsePushMessage(clist, hash); + break; + case CREATE_CONVERSATION: + Conversation mConversation = new Conversation(); + mConversation.createFromHashtable(hash); + clist.add(mConversation); + break; + default: + LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" + + type.name() + "]"); + } + } + + 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: + case IDENTITY_CHANGE: + engineId = EngineId.PRESENCE_ENGINE; + break; + case SYSTEM_NOTIFICATION: + LogUtils.logE("SYSTEM_NOTIFICATION push msg:" + msg.mHash); + list.add(SystemNotification.createFromHashtable(msg.mHash, engineId)); + return; + case IDENTITY_NETWORK_CHANGE: + break; + default: + + } + + list.add(PushEvent.createPushEvent(msg, engineId)); + } + } +}
360/360-Engine-for-Android
3a085af22f38089c7ed85641bce6aad2d8c0ca76
PAND 1648 Improving performance on network reading and decoding
diff --git a/src/com/caucho/hessian/micro/MicroHessianInput.java b/src/com/caucho/hessian/micro/MicroHessianInput.java index d1b887b..1fa53f8 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 sb = new StringBuilder(100); + 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 // new one. - sb.setLength(0); + mStringBuilder.setLength(0); for (int i = 0; i < length; i++) { int ch = is.read(); if (ch < 0x80) - sb.append((char)ch); + mStringBuilder.append((char)ch); else if ((ch & 0xe0) == 0xc0) { int ch1 = is.read(); int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f); - sb.append((char)v); + 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); - sb.append((char)v); + 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(); - sb.append(new String(b, "utf-8")); + mStringBuilder.append(new String(b, "utf-8")); i++; } else throw new IOException("bad utf-8 encoding"); } - return sb.toString(); + return mStringBuilder.toString(); } 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/service/transport/DecoderThread.java b/src/com/vodafone360/people/service/transport/DecoderThread.java index 8088fca..5b4b1db 100644 --- a/src/com/vodafone360/people/service/transport/DecoderThread.java +++ b/src/com/vodafone360/people/service/transport/DecoderThread.java @@ -1,329 +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.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; - private HessianDecoder hessianDecoder = new HessianDecoder(); + /** + * 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 engine = 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; engine = request.mEngineId; } else { type = Type.COMMON; } } // Set an engine id via Hessian decoder - List<BaseDataType> data = hessianDecoder.decodeHessianByteArray(decode.mData, + List<BaseDataType> data = mHessianDecoder.decodeHessianByteArray(decode.mData, type, decode.mIsCompressed); if (type == Type.PUSH_MSG && data.size() != 0 && data.get(0) instanceof PushEvent) { engine = ((PushEvent)data.get(0)).mEngineId; } // 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 && engine == EngineId.UNDEFINED) { Request request = QueueManager.getInstance().getRequest(reqId); if (request != null) { engine = request.mEngineId; } } if (engine == 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[" + engine + "] with data [" + data + "]"); mRespQueue.addToResponseQueue(decode.mReqId, data, engine); // 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 && engine != EngineId.UNDEFINED) { List<BaseDataType> list = new ArrayList<BaseDataType>(); ServerError error = new ServerError(); // this error type was chosen to make engines remove request // or retry // we may consider using other error code later error.errorType = ServerError.ErrorTypes.INTERNALERROR.name(); error.errorValue = "Decoder thread was unable to decode server message"; list.add(error); mRespQueue.addToResponseQueue(reqId, list, engine); } 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; } } } } } } diff --git a/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java b/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java index 96858a0..849b163 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 mIs; + 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(); 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()); } 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); - mIs = new BufferedInputStream(mSocket.getInputStream()); + 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(mIs); + 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; - mIs = 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) { } } diff --git a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java index 7484051..dd1a32d 100644 --- a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java +++ b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java @@ -1,494 +1,493 @@ /* * 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.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"; - private MicroHessianInput mhi = new MicroHessianInput(); + /** + * 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 data byte array containing Hessian encoded data * @param type Event type * @return List of BaseDataType items parsed from Hessian data * @throws IOException */ public List<BaseDataType> decodeHessianByteArray(byte[] data, Request.Type type, boolean isZipped) 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); } List<BaseDataType> mBaseDataTypeList = null; - mhi.init(is); - - if (mhi != null) { - LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); - try { - mBaseDataTypeList = decodeResponse(is, type); - } catch (IOException e) { - LogUtils.logE("HessianDecoder.decodeHessianByteArray() " - + "IOException during decodeResponse", e); - } + mMicroHessianInput.init(is); - } else { - LogUtils.logV("HessianDecoder.decodeHessianByteArray() MicroHessianInput IS NULL!!"); + LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); + try { + mBaseDataTypeList = decodeResponse(is, type); + } catch (IOException e) { + LogUtils.logE("HessianDecoder.decodeHessianByteArray() " + + "IOException during decodeResponse", e); } CloseUtils.close(bis); CloseUtils.close(is); return mBaseDataTypeList; } @SuppressWarnings("unchecked") public Hashtable<String, Object> decodeHessianByteArrayToHashtable(byte[] data) throws IOException { InputStream is = new ByteArrayInputStream(data); - mhi.init(is); + mMicroHessianInput.init(is); Object obj = null; - if (mhi != null) { - obj = mhi.decodeTag(); - } + obj = mMicroHessianInput.decodeTag(); if (obj instanceof Hashtable) { return (Hashtable<String, Object>)obj; } else { return null; } } /** * TODO: we cast every response to a Map, losing e.g. push event "c0" which * only contains a string - to fix * * @param is * @param type * @return * @throws IOException */ @SuppressWarnings("unchecked") private List<BaseDataType> decodeResponse(InputStream is, Request.Type type) throws IOException { boolean usesReplyTag = false; List<BaseDataType> mResultList = new ArrayList<BaseDataType>(); - mhi.init(is); + 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(); - zybErr.errorType = mhi.readFault().errString(); + zybErr.errorType = mMicroHessianInput.readFault().errString(); mResultList.add(zybErr); return mResultList; } // 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(mResultList, is, tag); return mResultList; } // 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>)mhi.decodeType(tag); + Hashtable<String, Object> hash = (Hashtable<String, Object>)mMicroHessianInput + .decodeType(tag); decodeResponseByRequestType(mResultList, hash, type); } else { // if we have a common request - Hashtable<String, Object> map = (Hashtable<String, Object>)mhi.readHashMap(tag); + 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); mResultList.add(auth.createFromHashtable(authHash)); } else if (map.containsKey(KEY_CONTACT_LIST)) { // contact list getContacts(mResultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); } 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) { mResultList.add(UserProfile.createFromHashtable(obj)); } } else if (map.containsKey(KEY_USER_PROFILE)) { Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map .get(KEY_USER_PROFILE); mResultList.add(UserProfile.createFromHashtable(userProfileHash)); } else if ((map.containsKey(KEY_IDENTITY_LIST)) || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { Vector<Hashtable<String, Object>> idcap = null; if (map.containsKey(KEY_IDENTITY_LIST)) { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); } else { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); } for (Hashtable<String, Object> obj : idcap) { Identity id = new Identity(); mResultList.add(id.createFromHashtable(obj)); } } 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) { mResultList.add(ActivityItem.createFromHashtable(obj)); } } } if (usesReplyTag) { is.read(); // read the last 'z' } return mResultList; } private void parseExternalResponse(List<BaseDataType> clist, InputStream is, int tag) throws IOException { - mhi.init(is); + 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 (mhi.readInt(tag) != 200) { + if (mMicroHessianInput.readInt(tag) != 200) { return; } try { - resp.mMimeType = mhi.readString(); + resp.mMimeType = mMicroHessianInput.readString(); } catch (IOException ioe) { LogUtils.logE("Failed to parse hessian string."); return; } // read data - could be gzipped try { - resp.mBody = mhi.readBytes(); + 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); } private void decodeResponseByRequestType(List<BaseDataType> clist, Hashtable<String, Object> hash, Request.Type type) { switch (type) { case CONTACT_CHANGES_OR_UPDATES: // create ContactChanges ContactChanges contChanges = new ContactChanges(); contChanges = contChanges.createFromHashtable(hash); clist.add(contChanges); break; case ADD_CONTACT: case SIGN_UP: clist.add(Contact.createFromHashtable(hash)); break; case RETRIEVE_PUBLIC_KEY: // AA define new object type clist.add(PublicKeyDetails.createFromHashtable(hash)); break; case FRIENDSHIP_REQUEST: 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); break; case CONTACT_DETAIL_DELETE: ContactDetailDeletion cdel = new ContactDetailDeletion(); clist.add(cdel.createFromHashtable(hash)); break; case USER_INVITATION: // Not currently supported. break; case CONTACT_GROUP_RELATION_LIST: ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); groupRelationList.populateFromHashtable(hash); clist.add(groupRelationList); break; case CONTACT_GROUP_RELATIONS: ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); groupRelationsList.populateFromHashtable(hash); clist.add(groupRelationsList); break; case GROUP_LIST: ItemList zyblist = new ItemList(ItemList.Type.group_privacy); zyblist.populateFromHashtable(hash); clist.add(zyblist); break; case ITEM_LIST_OF_LONGS: ItemList listOfLongs = new ItemList(ItemList.Type.long_value); listOfLongs.populateFromHashtable(hash); clist.add(listOfLongs); break; case STATUS_LIST: ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); zybstatlist.populateFromHashtable(hash); clist.add(zybstatlist); 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); } break; case EXPECTING_STATUS_ONLY: StatusMsg statMsg = new StatusMsg(); clist.add(statMsg.createFromHashtable(hash)); break; case STATUS: StatusMsg s = new StatusMsg(); s.mStatus = true; clist.add(s); break; case PRESENCE_LIST: PresenceList mPresenceList = new PresenceList(); mPresenceList.createFromHashtable(hash); clist.add(mPresenceList); break; case PUSH_MSG: // parse content of RPG Push msg parsePushMessage(clist, hash); break; case CREATE_CONVERSATION: Conversation mConversation = new Conversation(); mConversation.createFromHashtable(hash); clist.add(mConversation); break; default: LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" + type.name() + "]"); } } 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: case IDENTITY_CHANGE: engineId = EngineId.PRESENCE_ENGINE; break; case SYSTEM_NOTIFICATION: LogUtils.logE("SYSTEM_NOTIFICATION push msg:" + msg.mHash); list.add(SystemNotification.createFromHashtable(msg.mHash, engineId)); return; case IDENTITY_NETWORK_CHANGE: break; default: } list.add(PushEvent.createPushEvent(msg, engineId)); } } }
360/360-Engine-for-Android
193309d19f872e7cbe3136221914a1ca8f877578
PAND-1648 Improving performance on network reading and decoding
diff --git a/src/com/caucho/hessian/micro/MicroHessianInput.java b/src/com/caucho/hessian/micro/MicroHessianInput.java index 2de8f88..d1b887b 100644 --- a/src/com/caucho/hessian/micro/MicroHessianInput.java +++ b/src/com/caucho/hessian/micro/MicroHessianInput.java @@ -1,592 +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.*; -import java.util.*; - - -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 InputStream is; - - /** - * 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 = 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.read(); - is.read(); - - } - - /** - * 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.read(); - is.read(); - 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 { - StringBuffer sb = new StringBuffer(); - - for (int i = 0; i < length; i++) { - int ch = is.read(); - - if (ch < 0x80) - sb.append((char)ch); - else if ((ch & 0xe0) == 0xc0) { - int ch1 = is.read(); - int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f); - - sb.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); - - sb.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(); - sb.append(new String(b, "utf-8")); - i++; - } else - throw new IOException("bad utf-8 encoding"); - } - - return sb.toString(); - } - - 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; - } - } -} +/* + * 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 sb = new StringBuilder(100); + + /** + * 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 + // new one. + sb.setLength(0); + + for (int i = 0; i < length; i++) { + int ch = is.read(); + + if (ch < 0x80) + sb.append((char)ch); + + else if ((ch & 0xe0) == 0xc0) { + int ch1 = is.read(); + int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f); + sb.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); + sb.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(); + sb.append(new String(b, "utf-8")); + i++; + } else + throw new IOException("bad utf-8 encoding"); + } + + return sb.toString(); + } + + 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/service/transport/DecoderThread.java b/src/com/vodafone360/people/service/transport/DecoderThread.java index a4fa1c6..8088fca 100644 --- a/src/com/vodafone360/people/service/transport/DecoderThread.java +++ b/src/com/vodafone360/people/service/transport/DecoderThread.java @@ -1,327 +1,329 @@ /* * 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.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; + private HessianDecoder hessianDecoder = 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 engine = EngineId.UNDEFINED; - Type type = Type.PUSH_MSG; + 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; engine = request.mEngineId; } else { type = Type.COMMON; } } - + // Set an engine id via Hessian decoder - HessianDecoder hessianDecoder = new HessianDecoder(); + List<BaseDataType> data = hessianDecoder.decodeHessianByteArray(decode.mData, type, decode.mIsCompressed); - if (type == Type.PUSH_MSG && data.size() != 0 && data.get(0) instanceof PushEvent) { engine = ((PushEvent)data.get(0)).mEngineId; } - + // 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 && engine == EngineId.UNDEFINED) { Request request = QueueManager.getInstance().getRequest(reqId); if (request != null) { engine = request.mEngineId; } } if (engine == 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[" + engine + "] with data [" + data + "]"); mRespQueue.addToResponseQueue(decode.mReqId, data, engine); // 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 && engine != EngineId.UNDEFINED) { List<BaseDataType> list = new ArrayList<BaseDataType>(); ServerError error = new ServerError(); // this error type was chosen to make engines remove request // or retry // we may consider using other error code later error.errorType = ServerError.ErrorTypes.INTERNALERROR.name(); error.errorValue = "Decoder thread was unable to decode server message"; list.add(error); mRespQueue.addToResponseQueue(reqId, list, engine); } 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( + 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; } } } } } } diff --git a/src/com/vodafone360/people/service/transport/tcp/ResponseReaderThread.java b/src/com/vodafone360/people/service/transport/tcp/ResponseReaderThread.java index b652698..5e9058a 100644 --- a/src/com/vodafone360/people/service/transport/tcp/ResponseReaderThread.java +++ b/src/com/vodafone360/people/service/transport/tcp/ResponseReaderThread.java @@ -1,335 +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.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -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(InputStream 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 - } - - 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 - } - } -} +/* + * 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 + } + + 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 e67adc3..96858a0 100644 --- a/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java +++ b/src/com/vodafone360/people/service/transport/tcp/TcpConnectionThread.java @@ -1,587 +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.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -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 InputStream mIs; - - 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(); - 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()); - } - - 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); - - mIs = 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(mIs); - - 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; - mIs = 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) { - } -} +/* + * 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 mIs; + + 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(); + 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()); + } + + 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); + + mIs = 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(mIs); + + 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; + mIs = 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) { + } +} diff --git a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java index a3cdc6a..7484051 100644 --- a/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java +++ b/src/com/vodafone360/people/service/utils/hessian/HessianDecoder.java @@ -1,492 +1,494 @@ /* * 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.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"; + private MicroHessianInput mhi = new MicroHessianInput(); + /** * Parse Hessian encoded byte array placing parsed contents into List. * * @param data byte array containing Hessian encoded data * @param type Event type * @return List of BaseDataType items parsed from Hessian data * @throws IOException */ public List<BaseDataType> decodeHessianByteArray(byte[] data, Request.Type type, boolean isZipped) 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); } List<BaseDataType> mBaseDataTypeList = null; - MicroHessianInput mhi = new MicroHessianInput(is); + mhi.init(is); if (mhi != null) { LogUtils.logV("HessianDecoder.decodeHessianByteArray() Begin Hessian decode"); try { mBaseDataTypeList = decodeResponse(is, type); } catch (IOException e) { LogUtils.logE("HessianDecoder.decodeHessianByteArray() " + "IOException during decodeResponse", e); } } else { LogUtils.logV("HessianDecoder.decodeHessianByteArray() MicroHessianInput IS NULL!!"); } CloseUtils.close(bis); CloseUtils.close(is); return mBaseDataTypeList; } @SuppressWarnings("unchecked") public Hashtable<String, Object> decodeHessianByteArrayToHashtable(byte[] data) throws IOException { InputStream is = new ByteArrayInputStream(data); - MicroHessianInput mhi = new MicroHessianInput(is); + mhi.init(is); Object obj = null; if (mhi != null) { obj = mhi.decodeTag(); } if (obj instanceof Hashtable) { return (Hashtable<String, Object>)obj; } else { return null; } } /** * TODO: we cast every response to a Map, losing e.g. push event "c0" which * only contains a string - to fix * * @param is * @param type * @return * @throws IOException */ @SuppressWarnings("unchecked") private List<BaseDataType> decodeResponse(InputStream is, Request.Type type) throws IOException { boolean usesReplyTag = false; List<BaseDataType> mResultList = new ArrayList<BaseDataType>(); - MicroHessianInput mhi = new MicroHessianInput(is); + mhi.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(); zybErr.errorType = mhi.readFault().errString(); mResultList.add(zybErr); return mResultList; } // 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(mResultList, is, tag); return mResultList; } // 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>)mhi.decodeType(tag); decodeResponseByRequestType(mResultList, hash, type); } else { // if we have a common request Hashtable<String, Object> map = (Hashtable<String, Object>)mhi.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); mResultList.add(auth.createFromHashtable(authHash)); } else if (map.containsKey(KEY_CONTACT_LIST)) { // contact list getContacts(mResultList, ((Vector<?>)map.get(KEY_CONTACT_LIST))); } 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) { mResultList.add(UserProfile.createFromHashtable(obj)); } } else if (map.containsKey(KEY_USER_PROFILE)) { Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>)map .get(KEY_USER_PROFILE); mResultList.add(UserProfile.createFromHashtable(userProfileHash)); } else if ((map.containsKey(KEY_IDENTITY_LIST)) || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) { Vector<Hashtable<String, Object>> idcap = null; if (map.containsKey(KEY_IDENTITY_LIST)) { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_IDENTITY_LIST); } else { idcap = (Vector<Hashtable<String, Object>>)map.get(KEY_AVAILABLE_IDENTITY_LIST); } for (Hashtable<String, Object> obj : idcap) { Identity id = new Identity(); mResultList.add(id.createFromHashtable(obj)); } } 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) { mResultList.add(ActivityItem.createFromHashtable(obj)); } } } if (usesReplyTag) { is.read(); // read the last 'z' } return mResultList; } private void parseExternalResponse(List<BaseDataType> clist, InputStream is, int tag) throws IOException { - MicroHessianInput mhi = new MicroHessianInput(is); + mhi.init(is); ExternalResponseObject resp = new ExternalResponseObject(); // we already read the 'I' in the decodeResponse()-method // now we read and check the response code if (mhi.readInt(tag) != 200) { return; } try { resp.mMimeType = mhi.readString(); } catch (IOException ioe) { LogUtils.logE("Failed to parse hessian string."); return; } // read data - could be gzipped try { resp.mBody = mhi.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); } private void decodeResponseByRequestType(List<BaseDataType> clist, Hashtable<String, Object> hash, Request.Type type) { switch (type) { case CONTACT_CHANGES_OR_UPDATES: // create ContactChanges ContactChanges contChanges = new ContactChanges(); contChanges = contChanges.createFromHashtable(hash); clist.add(contChanges); break; case ADD_CONTACT: case SIGN_UP: clist.add(Contact.createFromHashtable(hash)); break; case RETRIEVE_PUBLIC_KEY: // AA define new object type clist.add(PublicKeyDetails.createFromHashtable(hash)); break; case FRIENDSHIP_REQUEST: 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); break; case CONTACT_DETAIL_DELETE: ContactDetailDeletion cdel = new ContactDetailDeletion(); clist.add(cdel.createFromHashtable(hash)); break; case USER_INVITATION: // Not currently supported. break; case CONTACT_GROUP_RELATION_LIST: ItemList groupRelationList = new ItemList(ItemList.Type.contact_group_relation); groupRelationList.populateFromHashtable(hash); clist.add(groupRelationList); break; case CONTACT_GROUP_RELATIONS: ItemList groupRelationsList = new ItemList(ItemList.Type.contact_group_relations); groupRelationsList.populateFromHashtable(hash); clist.add(groupRelationsList); break; case GROUP_LIST: ItemList zyblist = new ItemList(ItemList.Type.group_privacy); zyblist.populateFromHashtable(hash); clist.add(zyblist); break; case ITEM_LIST_OF_LONGS: ItemList listOfLongs = new ItemList(ItemList.Type.long_value); listOfLongs.populateFromHashtable(hash); clist.add(listOfLongs); break; case STATUS_LIST: ItemList zybstatlist = new ItemList(ItemList.Type.status_msg); zybstatlist.populateFromHashtable(hash); clist.add(zybstatlist); 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); } break; case EXPECTING_STATUS_ONLY: StatusMsg statMsg = new StatusMsg(); clist.add(statMsg.createFromHashtable(hash)); break; case STATUS: StatusMsg s = new StatusMsg(); s.mStatus = true; clist.add(s); break; case PRESENCE_LIST: PresenceList mPresenceList = new PresenceList(); mPresenceList.createFromHashtable(hash); clist.add(mPresenceList); break; case PUSH_MSG: // parse content of RPG Push msg parsePushMessage(clist, hash); break; case CREATE_CONVERSATION: Conversation mConversation = new Conversation(); mConversation.createFromHashtable(hash); clist.add(mConversation); break; default: LogUtils.logE("HessianDecoder.decodeResponseByRequestType() Unhandled type[" + type.name() + "]"); } } 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: case IDENTITY_CHANGE: engineId = EngineId.PRESENCE_ENGINE; break; case SYSTEM_NOTIFICATION: LogUtils.logE("SYSTEM_NOTIFICATION push msg:" + msg.mHash); list.add(SystemNotification.createFromHashtable(msg.mHash, engineId)); return; case IDENTITY_NETWORK_CHANGE: break; default: } list.add(PushEvent.createPushEvent(msg, engineId)); } } }
360/360-Engine-for-Android
eaa293a9baef036eea9f957e0b85322322e0dae8
follow up on code review comments for PAND-1583/1464
diff --git a/src/com/vodafone360/people/database/tables/ContactDetailsTable.java b/src/com/vodafone360/people/database/tables/ContactDetailsTable.java index c95962e..0c3b26e 100644 --- a/src/com/vodafone360/people/database/tables/ContactDetailsTable.java +++ b/src/com/vodafone360/people/database/tables/ContactDetailsTable.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.database.tables; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; 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.text.TextUtils; import com.vodafone360.people.Settings; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.SQLKeys; import com.vodafone360.people.database.DatabaseHelper.ServerIdInfo; import com.vodafone360.people.database.tables.ContactsTable.ContactIdInfo; import com.vodafone360.people.datatypes.Contact; import com.vodafone360.people.datatypes.ContactDetail; 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.presence.PresenceDbUtils; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.CloseUtils; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.StringBufferPool; /** * Provides a wrapper for all the operations on the Contact Details Table. Class * is never instantiated, all methods and fields are static. */ public abstract class ContactDetailsTable { /** * Name of the table in the people database. */ public static final String TABLE_NAME = "ContactDetails"; /** * SELECT LocalContactId, DetailLocalId, NativeDetailId, NativeContactIdDup, Key, Type, StringVal, OrderNo FROM ContactDetails. * * @see #getContactChanges(long, SQLiteDatabase) */ private final static String QUERY_CONTACT_DETAILS_BY_LOCAL_ID = "SELECT " + Field.LOCALCONTACTID + ", " + Field.DETAILLOCALID + ", " + Field.NATIVEDETAILID + ", " + Field.NATIVECONTACTID + ", " + Field.TYPE + ", " + Field.ORDER + ", " + Field.KEY + ", " + Field.STRINGVAL + ", " + Field.DETAILSERVERID + " FROM " + TABLE_NAME + " WHERE " + Field.LOCALCONTACTID + " = ?"; /** * */ private final static String QUERY_NATIVE_SYNCABLE_CONTACT_DETAILS_BY_LOCAL_ID = QUERY_CONTACT_DETAILS_BY_LOCAL_ID + " AND (" + Field.NATIVESYNCCONTACTID + " IS NULL OR " + Field.NATIVESYNCCONTACTID + " <> -1)"; /** * SELECT DISTINCT LocalId * FROM ContactDetails * WHERE NativeSyncId IS NULL OR NativeSyncId <> -1 */ public final static String QUERY_NATIVE_SYNCABLE_CONTACTS_LOCAL_IDS = "SELECT " + Field.LOCALCONTACTID + " FROM " + TABLE_NAME + " WHERE " + Field.NATIVESYNCCONTACTID + " IS NULL OR " + Field.NATIVESYNCCONTACTID + " <> -1"; /** * SELECT DetailLocalId, DetailServerId * FROM ContactDetails * WHERE LocalContactId = ? */ public final static String QUERY_DETAIL_LOCAL_AND_SERVER_IDS_BY_LOCAL_CONTACT_ID = "SELECT " + Field.DETAILLOCALID + ", "+ Field.DETAILSERVERID + " FROM " + TABLE_NAME + " WHERE " + Field.LOCALCONTACTID + " = ?"; /** * SELECT * DetailLocalId, Key, * DetailServerId, NativeContactIdDup, * NativeDetailId, NativeValue1, * NativeValue2, NativeValue3, * NativeSyncContactId * FROM ContactDetails * WHERE LocalContactId = ? */ private static final String QUERY_DETAIL_BY_LOCAL_CONTACT_ID = "SELECT " + Field.DETAILLOCALID + "," + Field.KEY + "," + Field.DETAILSERVERID + "," + Field.NATIVECONTACTID + "," + Field.NATIVEDETAILID + "," + Field.NATIVEDETAILVAL1 + "," + Field.NATIVEDETAILVAL2 + "," + Field.NATIVEDETAILVAL3 + "," + Field.NATIVESYNCCONTACTID + " FROM " + TABLE_NAME + " WHERE " + Field.LOCALCONTACTID + "=?"; /** * DetailLocalId Column for QUERY_DETAIL_BY_LOCAL_CONTACT_ID query */ final static int QUERY_COLUMN_LOCALDETAILID = 0; /** * Key Column for QUERY_DETAIL_BY_LOCAL_CONTACT_ID query */ final static int QUERY_COLUMN_KEY = 1; /** * DetailServerId Column for QUERY_DETAIL_BY_LOCAL_CONTACT_ID query */ final static int QUERY_COLUMN_SERVERDETAILID = 2; /** * NativeContactIdDup Column for QUERY_DETAIL_BY_LOCAL_CONTACT_ID query */ final static int QUERY_COLUMN_NATIVECONTACTID = 3; /** * NativeDetailId Column for QUERY_DETAIL_BY_LOCAL_CONTACT_ID query */ final static int QUERY_COLUMN_NATIVEDETAILID = 4; /** * NativeValue1 Column for QUERY_DETAIL_BY_LOCAL_CONTACT_ID query */ final static int QUERY_COLUMN_NATIVEVAL1 = 5; /** * NativeValue2 Column for QUERY_DETAIL_BY_LOCAL_CONTACT_ID query */ final static int QUERY_COLUMN_NATIVEVAL2 = 6; /** * NativeValue3 Column for QUERY_DETAIL_BY_LOCAL_CONTACT_ID query */ final static int QUERY_COLUMN_NATIVEVAL3 = 7; /** * NativeSyncContactId Column for QUERY_DETAIL_BY_LOCAL_CONTACT_ID query */ final static int QUERY_COLUMN_NATIVESYNCCONTACTID = 8; /** * Equals the number of comma separated items returned by * {@link #getFullQueryList()}. * * @See {@link #getQueryDataLength()} */ private static final int DATA_QUERY_LENGTH = 14; /** * Associates a constant with a field string in the People database. */ public static enum Field { DETAILLOCALID("DetailLocalId"), DETAILSERVERID("DetailServerId"), KEY("Key"), TYPE("Type"), STRINGVAL("StringVal"), ALT("Alt"), DELETED("Deleted"), ORDER("OrderNo"), BYTES("Bytes"), BYTESMIMETYPE("BytesMimeType"), PHOTOURL("PhotoUrl"), UPDATED("Updated"), LOCALCONTACTID("LocalContactId"), NATIVECONTACTID("NativeContactIdDup"), NATIVEDETAILID("NativeDetailId"), NATIVEDETAILVAL1("NativeValue1"), NATIVEDETAILVAL2("NativeValue2"), NATIVEDETAILVAL3("NativeValue3"), SERVERSYNCCONTACTID("ServerSyncContactId"), NATIVESYNCCONTACTID("NativeSyncContactId"); /** * Name of the table field as it appears in the database. */ private final String mField; /** * Constructs the enumeration value by associating it with a string. * * @param field The string specified in the list above. */ private Field(String field) { mField = field; } /** * Returns the enum value as the associated field name. */ public String toString() { return mField; } } /** * Holds the Native Contact information that is stored in the database for a * contact detail. Information is used when matching a contact detail from * People with a detail in the Android native phonebook. */ public static class NativeIdInfo { /** * Associated with the primary key (localDetailId) in the People Contact * Details table. */ public long localId; /** * Associated with the primary key (_id) in the native People table. */ public Integer nativeContactId; /** * Associated with the primary key (_id) in the native Phones, * ContactMethods or Organizations table (depending on contact detail). * Can be null for some types of detail. */ public Integer nativeDetailId; /** * Detail type specific. Stores value of one of the fields in a native * table (Phones, ContactMethods or Organisations). Used to determine if * the detail in the native table has changed. Examples: 1) In case of * phone number, this value holds the phone number in the same format as * the native database. 2) In case of address, this value holds the full * address (all in one string). This differs from the value field which * stores the address in VCard format. */ public String nativeVal1; /** * Detail type specific. Stores value of one of the fields in a native * table (Phones, ContactMethods or Organisations). Used to determine if * the detail in the native table has changed. */ public String nativeVal2; /** * Detail type specific. Stores value of one of the fields in a native * table (Phones, ContactMethods or Organisations). Used to determine if * the detail in the native table has changed. */ public String nativeVal3; /** * Can hold one of the following values: * <ul> * <li><b>NULL</b> Contact has just been added to the database</li> * <li><b>-1</b> Detail in People database has been synced with the * native</li> * <li><b>Positive Integer</b> Detail has been added or changed and * needs to be synced to the native.</li> * </ul> */ public long syncNativeContactId = -1L; } /** * Creates the contact detail table. * * @param writeableDb The SQLite database * @throws SQLException If the table already exists or the database is * corrupt */ public static void create(SQLiteDatabase writeableDb) throws SQLException { DatabaseHelper.trace(true, "ContactDetailsTable.create()"); writeableDb.execSQL("CREATE TABLE " + TABLE_NAME + " (" + Field.DETAILLOCALID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.DETAILSERVERID + " LONG, " + Field.KEY + " INTEGER, " + Field.TYPE + " INTEGER, " + Field.STRINGVAL + " TEXT, " + Field.ALT + " TEXT, " + Field.DELETED + " BOOLEAN, " + Field.ORDER + " INTEGER, " + Field.BYTES + " BINARY, " + Field.BYTESMIMETYPE + " TEXT, " + Field.PHOTOURL + " TEXT, " + Field.UPDATED + " INTEGER, " + Field.LOCALCONTACTID + " LONG NOT NULL, " + Field.NATIVECONTACTID + " INTEGER, " + Field.NATIVEDETAILID + " INTEGER," + Field.NATIVEDETAILVAL1 + " TEXT," + Field.NATIVEDETAILVAL2 + " TEXT," + Field.NATIVEDETAILVAL3 + " TEXT," + Field.SERVERSYNCCONTACTID + " LONG," + Field.NATIVESYNCCONTACTID + " INTEGER);"); } /** * Fetches the list of table fields that can be injected into an SQL query * statement. The {@link #getQueryData(Cursor)} method can be used to obtain * the data from the query. * * @return The query string * @Note Constant {@link #DATA_QUERY_LENGTH} must equal the number of comma * separated items returned by this function. */ private static String getFullQueryList() { return Field.DETAILLOCALID + ", " + Field.DETAILSERVERID + ", " + Field.LOCALCONTACTID + ", " + Field.KEY + ", " + Field.TYPE + ", " + Field.STRINGVAL + ", " + Field.ALT + ", " + Field.ORDER + ", " + Field.UPDATED + ", " + Field.NATIVECONTACTID + ", " + Field.NATIVEDETAILID + ", " + Field.NATIVEDETAILVAL1 + ", " + Field.NATIVEDETAILVAL2 + ", " + Field.NATIVEDETAILVAL3 + ", " + Field.SERVERSYNCCONTACTID + ", " + Field.NATIVESYNCCONTACTID; } /** * Returns the SQL for doing a raw query on the contact details table. The * {@link #getQueryData(Cursor)} method can be used for fetching the data * from the resulting cursor. * * @param whereClause The SQL constraint (cannot be empty or null) * @return The SQL query string */ public static String getQueryStringSql(String whereClause) { return "SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE " + whereClause; } /** * Returns the number of comma separated items returned by * {@link #getFullQueryList()}. * * @See {@link #DATA_QUERY_LENGTH} * @return The number of items */ private static int getQueryDataLength() { return DATA_QUERY_LENGTH; } /** * Identifies the columns of the data returned by getFullQueryList() */ private static final int COLUMN_LOCALDETAILID = 0; private static final int COLUMN_SERVERDETAILID = 1; private static final int COLUMN_LOCALCONTACTID = 2; private static final int COLUMN_KEY = 3; private static final int COLUMN_KEYTYPE = 4; private static final int COLUMN_VALUE = 5; private static final int COLUMN_ALT = 6; private static final int COLUMN_ORDER = 7; private static final int COLUMN_UPDATED = 8; private static final int COLUMN_NATIVECONTACTID = 9; private static final int COLUMN_NATIVEDETAILID = 10; private static final int COLUMN_NATIVEVAL1 = 11; private static final int COLUMN_NATIVEVAL2 = 12; private static final int COLUMN_NATIVEVAL3 = 13; private static final int COLUMN_SERVER_SYNC = 14; private static final int COLUMN_NATIVE_SYNC_CONTACT_ID = 15; /** * Returns the contact detail for the current record in the cursor. Query to * produce the cursor must be obtained using the {@link #getFullQueryList()} * . * * @param The cursor obtained from doing the query * @return The contact detail object. */ public static ContactDetail getQueryData(Cursor c) { ContactDetail detail = new ContactDetail(); if (!c.isNull(COLUMN_LOCALDETAILID)) { detail.localDetailID = c.getLong(COLUMN_LOCALDETAILID); } if (!c.isNull(COLUMN_SERVERDETAILID)) { detail.unique_id = c.getLong(COLUMN_SERVERDETAILID); } if (!c.isNull(COLUMN_LOCALCONTACTID)) { detail.localContactID = c.getLong(COLUMN_LOCALCONTACTID); } detail.key = ContactDetail.DetailKeys.values()[c.getInt(COLUMN_KEY)]; if (!c.isNull(COLUMN_KEYTYPE)) { detail.keyType = ContactDetail.DetailKeyTypes.values()[c.getInt(COLUMN_KEYTYPE)]; } detail.value = c.getString(COLUMN_VALUE); if (!c.isNull(COLUMN_ALT)) { detail.alt = c.getString(COLUMN_ALT); } if (!c.isNull(COLUMN_ORDER)) { detail.order = c.getInt(COLUMN_ORDER); } if (!c.isNull(COLUMN_UPDATED)) { detail.updated = c.getLong(COLUMN_UPDATED); } if (!c.isNull(COLUMN_NATIVECONTACTID)) { detail.nativeContactId = c.getInt(COLUMN_NATIVECONTACTID); } if (!c.isNull(COLUMN_NATIVEDETAILID)) { detail.nativeDetailId = c.getInt(COLUMN_NATIVEDETAILID); } if (!c.isNull(COLUMN_NATIVEVAL1)) { detail.nativeVal1 = c.getString(COLUMN_NATIVEVAL1); } if (!c.isNull(COLUMN_NATIVEVAL2)) { detail.nativeVal2 = c.getString(COLUMN_NATIVEVAL2); } if (!c.isNull(COLUMN_NATIVEVAL3)) { detail.nativeVal3 = c.getString(COLUMN_NATIVEVAL3); } if (!c.isNull(COLUMN_SERVER_SYNC)) { detail.serverContactId = c.getLong(COLUMN_SERVER_SYNC); } if (!c.isNull(COLUMN_NATIVE_SYNC_CONTACT_ID)) { detail.syncNativeContactId = c.getInt(COLUMN_NATIVE_SYNC_CONTACT_ID); } return detail; } /** * Extracts the suitable content values from a contact detail which can be * used to update or insert a record in the table. * * @param detail The contact detail * @param syncToServer If true the detail needs to be synced to the server, * otherwise no sync required * @param syncToNative If true the detail needs to be synced with the * native, otherwise no sync required * @return The ContentValues to use for the update or insert. * @note If any given field values are NULL they will NOT be added to the * content values data. */ private static ContentValues fillUpdateData(ContactDetail detail, boolean syncToServer, boolean syncToNative) { ContentValues contactDetailValues = new ContentValues(); if (detail.key != null) { contactDetailValues.put(Field.KEY.toString(), detail.key.ordinal()); } if (detail.keyType != null) { contactDetailValues.put(Field.TYPE.toString(), detail.keyType.ordinal()); } if (detail.localDetailID != null) { contactDetailValues.put(Field.DETAILLOCALID.toString(), detail.localDetailID); } contactDetailValues.put(Field.STRINGVAL.toString(), detail.value); if (detail.alt != null || (detail.key != null && detail.key == ContactDetail.DetailKeys.PRESENCE_TEXT)) { contactDetailValues.put(Field.ALT.toString(), detail.alt); } if (detail.unique_id != null) { contactDetailValues.put(Field.DETAILSERVERID.toString(), detail.unique_id); } if (detail.order != null) { contactDetailValues.put(Field.ORDER.toString(), detail.order); } if (detail.updated != null) { contactDetailValues.put(Field.UPDATED.toString(), detail.updated); } contactDetailValues.put(Field.LOCALCONTACTID.toString(), detail.localContactID); if (detail.deleted != null) { contactDetailValues.put(Field.DELETED.toString(), false); } // contactDetailValues.put(Field.BYTES.toString(), (byte[])null); // // TODO: Needs implementation if (detail.photo_mime_type != null) { contactDetailValues.put(Field.BYTESMIMETYPE.toString(), detail.photo_mime_type); } if (detail.photo_url != null) { contactDetailValues.put(Field.PHOTOURL.toString(), detail.photo_url); } if (detail.nativeContactId != null) { contactDetailValues.put(Field.NATIVECONTACTID.toString(), detail.nativeContactId); } if (detail.nativeDetailId != null) { contactDetailValues.put(Field.NATIVEDETAILID.toString(), detail.nativeDetailId); } if (syncToServer) { contactDetailValues.put(Field.SERVERSYNCCONTACTID.toString(), detail.serverContactId); } else { contactDetailValues.put(Field.SERVERSYNCCONTACTID.toString(), -1); } if (syncToNative) { contactDetailValues.put(Field.NATIVESYNCCONTACTID.toString(), detail.syncNativeContactId); } else { contactDetailValues.put(Field.NATIVESYNCCONTACTID.toString(), -1); if (detail.nativeVal1 != null) { contactDetailValues.put(Field.NATIVEDETAILVAL1.toString(), detail.nativeVal1); } if (detail.nativeVal2 != null) { contactDetailValues.put(Field.NATIVEDETAILVAL2.toString(), detail.nativeVal2); } if (detail.nativeVal3 != null) { contactDetailValues.put(Field.NATIVEDETAILVAL3.toString(), detail.nativeVal3); } } return contactDetailValues; } /** * Fetches a contact detail from the table * * @param localDetailId The local ID of the required detail * @param readableDb The readable SQLite database object * @return ContactDetail object or NULL if the detail was not found */ public static ContactDetail fetchDetail(long localDetailId, SQLiteDatabase readableDb) { String[] mArgs = { String.format("%d", localDetailId) }; ContactDetail detail = null; Cursor cursor = null; try { cursor = readableDb.rawQuery(getQueryStringSql(Field.DETAILLOCALID + " = ?"), mArgs); if (cursor.moveToFirst()) { detail = getQueryData(cursor); } } catch (SQLiteException e) { LogUtils.logE( "ContactDetailsTable.fetchDetail() Exception - Unable to fetch contact detail", e); return null; } finally { CloseUtils.close(cursor); cursor = null; } if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(false, "ContactDetailsTable.fetchDetail() localDetailId[" + localDetailId + "] unique_id[" + detail.unique_id + "] value[" + detail.value + "]"); } return detail; } /** * Removes a contact detail from the table * * @param localDetailId The local ID identifying the detail * @param writeableDb A writable SQLite database object. * @return true if the delete was successful, false otherwise */ public static boolean deleteDetailByDetailId(long localDetailId, SQLiteDatabase writeableDb) { try { String[] mArgs = { String.format("%d", localDetailId) }; writeableDb.delete(TABLE_NAME, Field.DETAILLOCALID + "=?", mArgs); DatabaseHelper.trace(true, "ContactDetailsTable.deleteDetailByDetailId() Deleted localDetailId[" + localDetailId + "]"); return true; } catch (SQLException e) { LogUtils @@ -876,1077 +875,1077 @@ public abstract class ContactDetailsTable { return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(c2); c2 = null; } return ServiceStatus.SUCCESS; } /** * Fetch details for a given contact * * @param localContactId The local ID of the contact * @param detailList A list which will be populated with the details * @param readableDb A readable SQLite database object. * @return SUCCESS or a suitable error code. */ public static ServiceStatus fetchContactDetails(Long localContactId, List<ContactDetail> detailList, SQLiteDatabase readableDb) { DatabaseHelper.trace(false, "ContactDetailsTable.fetchContactDetails() localContactId[" + localContactId + "]"); String[] args = { String.format("%d", localContactId) }; Cursor c = null; try { c = readableDb.rawQuery(ContactDetailsTable .getQueryStringSql(ContactDetailsTable.Field.LOCALCONTACTID + " = ?"), args); detailList.clear(); while (c.moveToNext()) { detailList.add(ContactDetailsTable.getQueryData(c)); } } catch (SQLException e) { LogUtils .logE( "ContactDetailsTable.fetchContactDetails() Exception - Unable to fetch contact details for contact", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(c); } return ServiceStatus.SUCCESS; } /** * Set contact detail server ID for all those details which require a server * ID. In any case, the server sync contact ID flag is set to -1 to indicate * that the detail has been fully synced with the server. * * @param serverIdList The list of contact details. This list should include * all details even the ones which don't have server IDs. * @param writableDb A writable SQLite database object * @return SUCCESS or a suitable error code. */ public static ServiceStatus syncSetServerIds(List<ServerIdInfo> serverIdList, SQLiteDatabase writableDb) { final int STATEMENT1_COLUMN_SERVERID = 1; final int STATEMENT1_COLUMN_LOCALID = 2; final int STATEMENT2_COLUMN_LOCALID = 1; DatabaseHelper.trace(true, "ContactDetailsTable.syncSetServerIds()"); if (serverIdList.size() == 0) { return ServiceStatus.SUCCESS; } SQLiteStatement statement1 = null; SQLiteStatement statement2 = null; try { writableDb.beginTransaction(); for (int i = 0; i < serverIdList.size(); i++) { final ServerIdInfo info = serverIdList.get(i); if (info.serverId != null) { if (statement1 == null) { statement1 = writableDb.compileStatement("UPDATE " + TABLE_NAME + " SET " + Field.DETAILSERVERID + "=?," + Field.SERVERSYNCCONTACTID + "=-1 WHERE " + Field.DETAILLOCALID + "=?"); } statement1.bindLong(STATEMENT1_COLUMN_SERVERID, info.serverId); statement1.bindLong(STATEMENT1_COLUMN_LOCALID, info.localId); statement1.execute(); } else { if (statement2 == null) { statement2 = writableDb.compileStatement("UPDATE " + TABLE_NAME + " SET " + Field.SERVERSYNCCONTACTID + "=-1 WHERE " + Field.DETAILLOCALID + "=?"); } statement2.bindLong(STATEMENT2_COLUMN_LOCALID, info.localId); statement2.execute(); } } writableDb.setTransactionSuccessful(); return ServiceStatus.SUCCESS; } catch (SQLException e) { LogUtils .logE( "ContactDetailsTable.syncSetServerIds() SQLException - Unable to update contact detail server Ids", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); if(statement1 != null) { statement1.close(); statement1 = null; } if(statement2 != null) { statement2.close(); statement2 = null; } } } /** * Set native detail ID for all those details which require an ID. In any * case, the native sync contact ID flag is set to -1 to indicate that the * detail has been fully synced with the native contacts database. * * @param serverIdList The list of contact details. This list should include * all details even the ones which don't have native IDs. * @param writableDb A writable SQLite database object * @return SUCCESS or a suitable error code. */ public static ServiceStatus syncSetNativeIds(List<NativeIdInfo> nativeIdList, SQLiteDatabase writableDb) { final int STATEMENT1_COLUMN_NATIVECONTACTID = 1; final int STATEMENT1_COLUMN_NATIVEDETAILID = 2; final int STATEMENT1_COLUMN_NATIVEVAL1 = 3; final int STATEMENT1_COLUMN_NATIVEVAL2 = 4; final int STATEMENT1_COLUMN_NATIVEVAL3 = 5; final int STATEMENT1_COLUMN_SYNCNATIVECONTACTID = 6; final int STATEMENT1_COLUMN_LOCALID = 7; DatabaseHelper.trace(true, "ContactDetailsTable.syncSetNativeIds()"); if (nativeIdList.size() == 0) { return ServiceStatus.SUCCESS; } try { writableDb.beginTransaction(); SQLiteStatement statement = writableDb.compileStatement("UPDATE " + TABLE_NAME + " SET " + Field.NATIVECONTACTID + "=?," + Field.NATIVEDETAILID + "=?," + Field.NATIVEDETAILVAL1 + "=?," + Field.NATIVEDETAILVAL2 + "=?," + Field.NATIVEDETAILVAL3 + "=?," + Field.NATIVESYNCCONTACTID + "=? WHERE " + Field.DETAILLOCALID + "=?"); for (int i = 0; i < nativeIdList.size(); i++) { final NativeIdInfo info = nativeIdList.get(i); statement.clearBindings(); if (info.nativeContactId != null) { statement.bindLong(STATEMENT1_COLUMN_NATIVECONTACTID, info.nativeContactId); } if (info.nativeDetailId != null) { statement.bindLong(STATEMENT1_COLUMN_NATIVEDETAILID, info.nativeDetailId); } if (info.nativeVal1 != null) { statement.bindString(STATEMENT1_COLUMN_NATIVEVAL1, info.nativeVal1); } if (info.nativeVal2 != null) { statement.bindString(STATEMENT1_COLUMN_NATIVEVAL2, info.nativeVal2); } if (info.nativeVal3 != null) { statement.bindString(STATEMENT1_COLUMN_NATIVEVAL3, info.nativeVal3); } statement.bindLong(STATEMENT1_COLUMN_SYNCNATIVECONTACTID, info.syncNativeContactId); statement.bindLong(STATEMENT1_COLUMN_LOCALID, info.localId); statement.execute(); } writableDb.setTransactionSuccessful(); return ServiceStatus.SUCCESS; } catch (SQLException e) { LogUtils .logE( "ContactDetailsTable.syncSetNativeIds() SQLException - Unable to update contact detail native Ids", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { writableDb.endTransaction(); } } /** * Fetches the preferred detail to use in the contact summary when the name * or status field are blank. * * @param localContactID The local contact ID * @param keyVal The key to fetch (normally either VCARD_PHONE or * VCARD_EMAIL). * @param altDetail A contact detail object where the result will be stored. * @param readableDb A readable SQLite database object * @return true if successful, false otherwise. */ public static boolean fetchPreferredDetail(long localContactID, int keyVal, ContactDetail altDetail, SQLiteDatabase readableDb) { final int QUERY_COLUMN_LOCALDETAILID = 0; final int QUERY_COLUMN_TYPE = 1; final int QUERY_COLUMN_VAL = 2; final int QUERY_COLUMN_ORDER = 3; DatabaseHelper.trace(false, "ContactDetailsTable.fetchPreferredDetail()"); Cursor c = null; try { boolean found = false; c = readableDb.rawQuery("SELECT " + Field.DETAILLOCALID + "," + Field.TYPE + "," + Field.STRINGVAL + "," + Field.ORDER + " FROM " + TABLE_NAME + " WHERE " + Field.LOCALCONTACTID + "=" + localContactID + " AND " + Field.KEY + "=" + keyVal + " AND " + Field.ORDER + "=" + "(SELECT MIN(" + Field.ORDER + ") FROM " + TABLE_NAME + " WHERE " + Field.LOCALCONTACTID + "=" + localContactID + " AND " + Field.KEY + "=" + keyVal + ")", null); if (c.moveToFirst()) { if (!c.isNull(QUERY_COLUMN_LOCALDETAILID)) { altDetail.localDetailID = c.getLong(QUERY_COLUMN_LOCALDETAILID); } if (!c.isNull(QUERY_COLUMN_TYPE)) { altDetail.keyType = ContactDetail.DetailKeyTypes.values()[c .getInt(QUERY_COLUMN_TYPE)]; } if (!c.isNull(QUERY_COLUMN_VAL)) { altDetail.value = c.getString(QUERY_COLUMN_VAL); } if (!c.isNull(QUERY_COLUMN_ORDER)) { altDetail.order = c.getInt(QUERY_COLUMN_ORDER); } found = true; } return found; } catch (SQLException e) { LogUtils.logE("ContactDetailsTable.fetchPreferredDetail() SQLException " + "- Unable to fetch preferred detail", e); return false; } finally { CloseUtils.close(c); c = null; } } /** * Fixes the phone numbers and emails of a contact to ensure that at least * one of each is a preferred detail. * * @param localContactId The local Id of the contact * @param writableDb A writable SQLite database object * @return SUCCESS or a suitable error code. */ public static ServiceStatus fixPreferredValues(long localContactId, SQLiteDatabase writableDb) { DatabaseHelper.trace(false, "ContactDetailsTable.fixPreferredValues()"); ServiceStatus status = fixPreferredDetail(localContactId, ContactDetail.DetailKeys.VCARD_PHONE, writableDb); if (ServiceStatus.SUCCESS != status) { return status; } return fixPreferredDetail(localContactId, ContactDetail.DetailKeys.VCARD_EMAIL, writableDb); } /** * Ensures that for a given key there is at least one preferred detail. * Modifying the database if necessary. * * @param localContactId The local ID of the contact. * @param key The key to fix. * @param writableDb A writable SQLite database object * @return SUCCESS or a suitable error code. */ private static ServiceStatus fixPreferredDetail(long localContactId, ContactDetail.DetailKeys key, SQLiteDatabase writableDb) { DatabaseHelper.trace(false, "ContactDetailsTable.fixPreferredDetail()"); ContactDetail altDetail = new ContactDetail(); if (fetchPreferredDetail(localContactId, key.ordinal(), altDetail, writableDb)) { if (altDetail.order > 0) { altDetail = fetchDetail(altDetail.localDetailID, writableDb); if (altDetail != null) { altDetail.order = 0; boolean syncWithServer = (null != altDetail.serverContactId) && (altDetail.serverContactId > -1); boolean syncWithNative = (null != altDetail.syncNativeContactId) && (altDetail.syncNativeContactId > -1); return modifyDetail(altDetail, syncWithServer, syncWithNative, writableDb); } return ServiceStatus.ERROR_NOT_FOUND; } } return ServiceStatus.SUCCESS; } /** * Returns a cursor of all the contact details that match a specific key and * value. Used by the {@link #findNativeContact(Contact, SQLiteDatabase)} * method to find all the contacts by name, phone number or email. * * @param value The string value to match. * @param key The key to match. * @param readableDb A readable SQLite database object * @return A cursor containing the local detail ID and local contact ID for * each result. */ private static Cursor findDetailByKey(String value, ContactDetail.DetailKeys key, SQLiteDatabase readableDb) { try { if (value == null || key == null) { return null; } final String searchValue = DatabaseUtils.sqlEscapeString(value); return readableDb.rawQuery("SELECT " + Field.DETAILLOCALID + "," + Field.LOCALCONTACTID + " FROM " + TABLE_NAME + " WHERE " + Field.KEY + "=" + key.ordinal() + " AND " + Field.STRINGVAL + "=" + searchValue + " AND " + Field.NATIVECONTACTID + " IS NULL", null); } catch (SQLException e) { LogUtils.logE("ContactDetailsTable.findDetailByKey() SQLException - " + "Unable to search for native contact ", e); return null; } } /** * Moves native details ownership from the duplicate contact to the original * contact. * * @param info the info for duplicated and original contacts * @param nativeInfoList the list of native details from the duplicated * contact * @param writableDb A writable SQLite database object * @return SUCCESS or a suitable error code. */ public static ServiceStatus mergeContactDetails(ContactIdInfo info, List<ContactDetail> nativeInfoList, SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "ContactDetailsTable.mergeContactDetails()"); /** * Used to hold some contact details info. */ final class DetailsInfo { /** * The detail local id. */ public Long localId; /** * The detail server id. */ public Long serverId; public DetailsInfo(Long localId, Long serverId) { this.localId = localId; this.serverId = serverId; } } // the list of details from the original contact List<DetailsInfo> detailLocalIds = new ArrayList<DetailsInfo>(); // the result cursor from the original contact details query Cursor cursor = null; try { // Retrieve a list of detail local IDs from the merged contact // (original one) final String[] args = {String.valueOf(info.mergedLocalId)}; cursor = writableDb.rawQuery( QUERY_DETAIL_LOCAL_AND_SERVER_IDS_BY_LOCAL_CONTACT_ID, args); while (cursor.moveToNext()) { if (!cursor.isNull(0) && !cursor.isNull(1)) { // only adding details with a detailServerId (Name and // Nickname don't have detailServerIds) detailLocalIds.add(new DetailsInfo(cursor.getLong(0),cursor .getLong(1))); } } DatabaseHelper.trace(true, "ContactDetailsTable.mergeContactDetails(): detailLocalIds.size()=" + detailLocalIds.size()); } catch (Exception e) { LogUtils.logE("ContactDetailsTable.mergeContactDetails() Exception - " + "Unable to query merged contact details list", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { if (cursor != null) { cursor.close(); cursor = null; } } try { final ContentValues cv = new ContentValues(); // Go through the duplicated contact details and find details that // matches with the original contact // If there is a match, move the native details ownership from the // duplicated contact to the original contact for (int infoListIndex = 0; infoListIndex < nativeInfoList.size(); infoListIndex++) { final ContactDetail detailInfo = nativeInfoList.get(infoListIndex); // Change the ownership for (int detailsIndex = 0; detailsIndex < detailLocalIds.size(); detailsIndex++) { final DetailsInfo currentDetails = detailLocalIds.get(detailsIndex); if (currentDetails.serverId.equals(detailInfo.unique_id)) { cv.put(Field.LOCALCONTACTID.toString(), info.mergedLocalId); cv.put(Field.NATIVECONTACTID.toString(), detailInfo.nativeContactId); cv.put(Field.NATIVEDETAILID.toString(), detailInfo.nativeDetailId); cv.put(Field.NATIVEDETAILVAL1.toString(), detailInfo.nativeVal1); cv.put(Field.NATIVEDETAILVAL2.toString(), detailInfo.nativeVal2); cv.put(Field.NATIVEDETAILVAL3.toString(), detailInfo.nativeVal3); cv .put(Field.NATIVESYNCCONTACTID.toString(), detailInfo.syncNativeContactId); DatabaseHelper.trace(true, "ContactDetailsTable.mergeContactDetails():" + " changing ownership for duplicated detail: " + detailInfo); writableDb.update(TABLE_NAME, cv, Field.DETAILLOCALID + "=" + currentDetails.localId, null); cv.clear(); detailLocalIds.remove(detailsIndex); break; } } } return ServiceStatus.SUCCESS; } catch (SQLException e) { LogUtils.logE("ContactDetailsTable.mergeContactDetails() SQLException - " + "Unable to merge contact detail native info", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } /** * Fetches a list of contact details with only the native sync information * filled in. This method is used in preference to * {@link #fetchContactDetails(Long, List, SQLiteDatabase)} during contact * sync operations to improve performance. * * @param localContactId Local Id of the contact (in the database). * @param nativeInfoList A list which will be filled with contact detail * objects. * @param writableDb A writable SQLite database object * @return SUCCESS or a suitable error code. */ public static ServiceStatus fetchNativeInfo(long localContactId, List<ContactDetail> nativeInfoList, SQLiteDatabase writableDb) { DatabaseHelper.trace(true, "ContactDetailsTable.fetchNativeInfo()"); Cursor c = null; try { final String[] args = { String.valueOf(localContactId) }; c = writableDb.rawQuery(QUERY_DETAIL_BY_LOCAL_CONTACT_ID, args); nativeInfoList.clear(); while (c.moveToNext()) { ContactDetail detailInfo = new ContactDetail(); if (!c.isNull(QUERY_COLUMN_LOCALDETAILID)) { detailInfo.localDetailID = c.getLong(QUERY_COLUMN_LOCALDETAILID); } if (!c.isNull(QUERY_COLUMN_KEY)) { detailInfo.key = ContactDetail.DetailKeys.values()[c.getInt(QUERY_COLUMN_KEY)]; } if (!c.isNull(QUERY_COLUMN_SERVERDETAILID)) { detailInfo.unique_id = c.getLong(QUERY_COLUMN_SERVERDETAILID); } if (!c.isNull(QUERY_COLUMN_NATIVECONTACTID)) { detailInfo.nativeContactId = c.getInt(QUERY_COLUMN_NATIVECONTACTID); } if (!c.isNull(QUERY_COLUMN_NATIVEDETAILID)) { detailInfo.nativeDetailId = c.getInt(QUERY_COLUMN_NATIVEDETAILID); } if (!c.isNull(QUERY_COLUMN_NATIVEVAL1)) { detailInfo.nativeVal1 = c.getString(QUERY_COLUMN_NATIVEVAL1); } if (!c.isNull(QUERY_COLUMN_NATIVEVAL2)) { detailInfo.nativeVal2 = c.getString(QUERY_COLUMN_NATIVEVAL2); } if (!c.isNull(QUERY_COLUMN_NATIVEVAL3)) { detailInfo.nativeVal3 = c.getString(QUERY_COLUMN_NATIVEVAL3); } if (!c.isNull(QUERY_COLUMN_NATIVESYNCCONTACTID)) { detailInfo.syncNativeContactId = c.getInt(QUERY_COLUMN_NATIVESYNCCONTACTID); } nativeInfoList.add(detailInfo); } } catch (SQLException e) { LogUtils.logE("ContactDetailsTable.fetchNativeInfo() - error:\n", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(c); c = null; } return ServiceStatus.SUCCESS; } /** * This method finds the localContactId corresponding to the wanted Key and * StringVal fields. * * @param value - StringVal * @param key - Key * @param readableDb A readable SQLite database object * @return - localContactId (it is unique) */ public static long findLocalContactIdByKey(String networkName, String value, ContactDetail.DetailKeys key, SQLiteDatabase readableDb) throws SQLException { long localContactId = -1; Cursor c = null; try { if (value == null || key == null) { return localContactId; } value = DatabaseUtils.sqlEscapeString(value); networkName = DatabaseUtils.sqlEscapeString(networkName); StringBuffer query = StringBufferPool.getStringBuffer(SQLKeys.SELECT); query.append(Field.LOCALCONTACTID).append(SQLKeys.FROM).append(TABLE_NAME).append( SQLKeys.WHERE).append(Field.KEY).append(SQLKeys.EQUALS).append(key.ordinal()) .append(SQLKeys.AND).append(Field.STRINGVAL).append(SQLKeys.EQUALS).append( value); - if (PresenceDbUtils.notNullOrBlank(networkName)) { + if (!TextUtils.isEmpty(networkName)) { query.append(SQLKeys.AND).append(Field.ALT).append(SQLKeys.EQUALS).append( networkName); } c = readableDb.rawQuery(StringBufferPool.toStringThenRelease(query), null); while (c.moveToNext()) { if (!c.isNull(0)) { localContactId = c.getLong(0); break; } } } finally { CloseUtils.close(c); c = null; } return localContactId; } /** * This method finds the chat id corresponding to the wanted Alt, * LocalContactId and Key fields * * @param networkName - network name (google,MSN) * @param localContactId - localContactId of the contcat * @param readableDb A readable SQLite database object * @return - chatId for this network(it is unique) */ public static String findChatIdByLocalContactIdAndNetwork(String networkName, long localContactId, SQLiteDatabase readableDb) throws NullPointerException, SQLException { if (readableDb == null) { throw new NullPointerException( "ContactDetailsTable.findChatIdByLocalContactIdAndNetwork(): The database passed in was null!"); } String chatId = null; Cursor c = null; try { if (localContactId == -1 || networkName == null) { return chatId; } networkName = DatabaseUtils.sqlEscapeString(networkName); String query = "SELECT " + Field.STRINGVAL + " FROM " + TABLE_NAME + " WHERE " + Field.KEY + "=" + ContactDetail.DetailKeys.VCARD_IMADDRESS.ordinal() + " AND " + Field.LOCALCONTACTID + "=" - + (PresenceDbUtils.notNullOrBlank(networkName) ? localContactId + " AND " + + (!TextUtils.isEmpty(networkName) ? localContactId + " AND " + Field.ALT + "=" + networkName : String.valueOf(localContactId)); c = readableDb.rawQuery(query, null); while (c.moveToNext()) { if (!c.isNull(0)) { chatId = c.getString(0); break; } } } finally { CloseUtils.close(c); } return chatId; } /** * Compares the details given with a specific contact in the database. If * the contacts match a list of native sync information is returned. * * @param c Contact to compare * @param localContactId Contact in the database to compare with * @param detailIdList A list which will be populated if a match is found. * @param readableDb A readable SQLite database object * @return true if a match is found, false otherwise */ public static boolean doContactsMatch(Contact c, long localContactId, List<NativeIdInfo> detailIdList, SQLiteDatabase readableDb) { List<ContactDetail> srcDetails = new ArrayList<ContactDetail>(); ServiceStatus status = fetchContactDetails(localContactId, srcDetails, readableDb); if (ServiceStatus.SUCCESS != status) { return false; } detailIdList.clear(); for (int i = 0; i < c.details.size(); i++) { final ContactDetail destDetail = c.details.get(i); Long foundDetailId = null; for (int j = 0; j < srcDetails.size(); j++) { final ContactDetail srcDetail = srcDetails.get(j); if (srcDetail.changeID == null && srcDetail.key != null && srcDetail.key.equals(destDetail.key)) { if (srcDetail.value != null && srcDetail.value.equals(destDetail.value)) { foundDetailId = srcDetail.localDetailID; srcDetail.changeID = 1L; break; } if (srcDetail.value == null && destDetail.value == null) { foundDetailId = srcDetail.localDetailID; srcDetail.changeID = 1L; break; } if (srcDetail.key == ContactDetail.DetailKeys.VCARD_NAME && srcDetail.value != null && srcDetail.value.indexOf(VCardHelper.LIST_SEPARATOR) < 0) { VCardHelper.Name name1 = srcDetail.getName(); VCardHelper.Name name2 = destDetail.getName(); if (name1 != null && name2 != null && name1.toString().equals(name2.toString())) { foundDetailId = srcDetail.localDetailID; srcDetail.changeID = 1L; } } if (srcDetail.key == ContactDetail.DetailKeys.VCARD_ADDRESS && srcDetail.value != null && srcDetail.value.indexOf(VCardHelper.LIST_SEPARATOR) < 0) { VCardHelper.PostalAddress addr1 = srcDetail.getPostalAddress(); VCardHelper.PostalAddress addr2 = destDetail.getPostalAddress(); if (addr1 != null && addr2 != null && addr1.toString().equals(addr2.toString())) { foundDetailId = srcDetail.localDetailID; srcDetail.changeID = 1L; } } } } if (foundDetailId == null) { if (destDetail.value != null && destDetail.value.length() > 0) { LogUtils.logD("ContactDetailTable.doContactsMatch - The detail " + destDetail.key + ", <" + destDetail.value + "> was not found"); for (int j = 0; j < srcDetails.size(); j++) { final ContactDetail srcDetail = srcDetails.get(j); if (srcDetail.key != null && srcDetail.key.equals(destDetail.key)) { LogUtils.logD("ContactDetailTable.doContactsMatch - No Match Key: " + srcDetail.key + ", Value: <" + srcDetail.value + ">, Used: " + srcDetail.changeID); } } return false; } } else { NativeIdInfo nativeIdInfo = new NativeIdInfo(); nativeIdInfo.localId = foundDetailId; nativeIdInfo.nativeContactId = c.nativeContactId; nativeIdInfo.nativeDetailId = destDetail.nativeDetailId; nativeIdInfo.nativeVal1 = destDetail.nativeVal1; nativeIdInfo.nativeVal2 = destDetail.nativeVal2; nativeIdInfo.nativeVal3 = destDetail.nativeVal3; detailIdList.add(nativeIdInfo); } } for (int j = 0; j < srcDetails.size(); j++) { final ContactDetail srcDetail = srcDetails.get(j); if (srcDetail.nativeContactId == null) { boolean found = false; for (int i = 0; i < detailIdList.size(); i++) { NativeIdInfo info = detailIdList.get(i); if (info.localId == srcDetail.localDetailID.longValue()) { found = true; break; } } if (!found) { NativeIdInfo nativeIdInfo = new NativeIdInfo(); nativeIdInfo.localId = srcDetail.localDetailID; nativeIdInfo.nativeContactId = srcDetail.nativeContactId; nativeIdInfo.nativeDetailId = srcDetail.nativeDetailId; nativeIdInfo.nativeVal1 = srcDetail.nativeVal1; nativeIdInfo.nativeVal2 = srcDetail.nativeVal2; nativeIdInfo.nativeVal3 = srcDetail.nativeVal3; nativeIdInfo.syncNativeContactId = c.nativeContactId; detailIdList.add(nativeIdInfo); } } } return true; } /** * Searches the contact details table for a contact from the native * phonebook. If a match is found, the native sync information is transfered * from the given contact into the matching database contact. Tries to match * in the following sequence: 1) If there is a name, match by name 2) * Otherwise, if there is a phone number, match by number 3) Otherwise, if * there is an email, match by email 4) Otherwise return false For a match * to occur, all given contact details must be identical to those in the * database. There may be more details in the database but this won't change * the result. * * @param c The contact to match * @param writableDb A writable SQLite database object * @return true if the contact was found, false otherwise */ public static boolean findNativeContact(Contact c, SQLiteDatabase writableDb) { String name = null; String phone = null; String email = null; List<ContactIdInfo> contactIdList = new ArrayList<ContactIdInfo>(); List<NativeIdInfo> detailIdList = new ArrayList<NativeIdInfo>(); for (int i = 0; i < c.details.size(); i++) { if (c.details.get(i).key == ContactDetail.DetailKeys.VCARD_NICKNAME) { name = c.details.get(i).getValue(); if (name != null && name.length() > 0) { break; } } if (c.details.get(i).key == ContactDetail.DetailKeys.VCARD_PHONE) { if (phone == null || phone.length() > 0) { phone = c.details.get(i).getValue(); } } if (c.details.get(i).key == ContactDetail.DetailKeys.VCARD_EMAIL) { if (email == null || email.length() > 0) { email = c.details.get(i).getValue(); } } } Cursor candidateListCursor = null; if (name != null && name.length() > 0) { LogUtils.logD("ContactDetailsTable.findNativeContact - " + "Searching for contact called " + name); candidateListCursor = findDetailByKey(name, ContactDetail.DetailKeys.VCARD_NICKNAME, writableDb); } else if (phone != null && phone.length() > 0) { LogUtils.logD("ContactDetailsTable.findNativeContact - " + "Searching for contact with phone " + phone); candidateListCursor = findDetailByKey(phone, ContactDetail.DetailKeys.VCARD_PHONE, writableDb); } else if (email != null && email.length() > 0) { LogUtils.logD("ContactDetailsTable.findNativeContact - " + "Searching for contact with email " + email); candidateListCursor = findDetailByKey(email, ContactDetail.DetailKeys.VCARD_EMAIL, writableDb); } List<NativeIdInfo> tempDetailIdList = new ArrayList<NativeIdInfo>(); List<NativeIdInfo> currentDetailIdList = new ArrayList<NativeIdInfo>(); Integer minNoOfDetails = null; Long chosenContactId = null; if (candidateListCursor != null) { while (candidateListCursor.moveToNext()) { long localContactId = candidateListCursor.getLong(1); tempDetailIdList.clear(); if (doContactsMatch(c, localContactId, tempDetailIdList, writableDb)) { if (minNoOfDetails == null || minNoOfDetails.intValue() > tempDetailIdList.size()) { if (ContactsTable.fetchSyncToPhone(localContactId, writableDb)) { minNoOfDetails = tempDetailIdList.size(); chosenContactId = localContactId; currentDetailIdList.clear(); currentDetailIdList.addAll(tempDetailIdList); } } } } candidateListCursor.close(); if (chosenContactId != null) { LogUtils.logD("ContactDetailsTable.findNativeContact - " + "Found contact (no need to add)"); ContactIdInfo contactIdInfo = new ContactIdInfo(); contactIdInfo.localId = chosenContactId; contactIdInfo.nativeId = c.nativeContactId; contactIdList.add(contactIdInfo); detailIdList.addAll(currentDetailIdList); // Update contact IDs of the contacts which are already in the // database ServiceStatus status = ContactsTable.syncSetNativeIds(contactIdList, writableDb); if (ServiceStatus.SUCCESS != status) { return false; } status = ContactSummaryTable.syncSetNativeIds(contactIdList, writableDb); if (ServiceStatus.SUCCESS != status) { return false; } status = ContactDetailsTable.syncSetNativeIds(detailIdList, writableDb); if (ServiceStatus.SUCCESS != status) { return false; } return true; } } LogUtils.logD("ContactDetailsTable.findNativeContact - Contact not found (will be added)"); return false; } /** * Fetches all the details that have changed and need to be synced with the * server. Details associated with new contacts are returned separately, * this is determined by a parameter. The * {@link #syncSetServerIds(List, SQLiteDatabase)} method is used to mark * the details as up to date, once the sync has completed. * * @param readableDb A readable SQLite database object * @param newContacts true if details associated with new contacts should be * returned, otherwise modified details are returned. * @return A cursor which can be passed into the * {@link #syncServerGetNextNewContactDetails(Cursor, List, int)} * method. */ public static Cursor syncServerFetchContactChanges(SQLiteDatabase readableDb, boolean newContacts) { try { String statusMatch = ""; if (newContacts) { statusMatch = Field.SERVERSYNCCONTACTID + " IS NULL"; } else { /** Note this won't return NULLs. **/ statusMatch = Field.SERVERSYNCCONTACTID + "<>-1"; } return readableDb.rawQuery("SELECT " + Field.LOCALCONTACTID + "," + Field.SERVERSYNCCONTACTID + "," + Field.DETAILLOCALID + "," + Field.DETAILSERVERID + "," + Field.KEY + "," + Field.TYPE + "," + Field.STRINGVAL + "," + Field.ORDER + "," + Field.PHOTOURL + " FROM " + TABLE_NAME + " WHERE " + statusMatch, null); } catch (SQLException e) { LogUtils.logE("ContactDetailsTable.syncServerFetchContactChanges() SQLException - " + "Unable to search for native contact ", e); return null; } } /** * Returns the next batch of contacts which need to be added on the server. * The {@link #syncServerFetchContactChanges(SQLiteDatabase, boolean)} * method is used to retrieve the cursor initially, then this function can * be called many times until all the contacts have been fetched. When the * list returned from this method is empty the cursor has reached the end * and the sync is complete. * * @param c The cursor (see description above) * @param contactList Will be filled with contacts that need to be added to * the server * @param maxContactsToFetch Maximum number of contacts to return in the * list. The function can be called in a loop until all the * contacts have been retrieved. */ public static void syncServerGetNextNewContactDetails(Cursor c, List<Contact> contactList, int maxContactsToFetch) { final int QUERY_COLUMN_LOCALCONTACTID = 0; final int QUERY_COLUMN_SERVERSYNCCONTACTID = 1; final int QUERY_COLUMN_LOCALDETAILID = 2; final int QUERY_COLUMN_SERVERDETAILID = 3; final int QUERY_COLUMN_KEY = 4; final int QUERY_COLUMN_KEYTYPE = 5; final int QUERY_COLUMN_VAL = 6; final int QUERY_COLUMN_ORDER = 7; final int QUERY_COLUMN_PHOTOURL = 8; contactList.clear(); Contact currentContact = null; while (c.moveToNext()) { final ContactDetail detail = new ContactDetail(); if (!c.isNull(QUERY_COLUMN_LOCALCONTACTID)) { detail.localContactID = c.getLong(QUERY_COLUMN_LOCALCONTACTID); } if (!c.isNull(QUERY_COLUMN_SERVERSYNCCONTACTID)) { detail.serverContactId = c.getLong(QUERY_COLUMN_SERVERSYNCCONTACTID); } if (currentContact == null || !currentContact.localContactID.equals(detail.localContactID)) { if (contactList.size() >= maxContactsToFetch) { if (currentContact != null) { c.moveToPrevious(); } break; } currentContact = new Contact(); currentContact.localContactID = detail.localContactID; if (detail.serverContactId == null) { currentContact.synctophone = true; } currentContact.contactID = detail.serverContactId; contactList.add(currentContact); } if (!c.isNull(QUERY_COLUMN_LOCALDETAILID)) { detail.localDetailID = c.getLong(QUERY_COLUMN_LOCALDETAILID); } if (!c.isNull(QUERY_COLUMN_SERVERDETAILID)) { detail.unique_id = c.getLong(QUERY_COLUMN_SERVERDETAILID); } detail.key = ContactDetail.DetailKeys.values()[c.getInt(QUERY_COLUMN_KEY)]; if (!c.isNull(QUERY_COLUMN_KEYTYPE)) { detail.keyType = ContactDetail.DetailKeyTypes.values()[c .getInt(QUERY_COLUMN_KEYTYPE)]; } detail.value = c.getString(QUERY_COLUMN_VAL); if (!c.isNull(QUERY_COLUMN_ORDER)) { detail.order = c.getInt(QUERY_COLUMN_ORDER); } if (!c.isNull(QUERY_COLUMN_PHOTOURL)) { detail.photo_url = c.getString(QUERY_COLUMN_PHOTOURL); } currentContact.details.add(detail); } } /** * Retrieves the total number of details that have changed and need to be * synced with the server. Includes both new and modified contacts. * * @param db Readable SQLiteDatabase object. * @return The number of details. */ public static int syncServerFetchNoOfChanges(final SQLiteDatabase db) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(false, "ContactDetailsTable." + "syncServerFetchNoOfChanges()"); } Cursor cursor = null; try { /** Return all values from this table (including new contacts) **/ cursor = db.rawQuery("SELECT COUNT(distinct " + Field.LOCALCONTACTID + ") FROM " + TABLE_NAME + " WHERE " + Field.SERVERSYNCCONTACTID + "<>-1 OR " + Field.SERVERSYNCCONTACTID + " IS NULL", null); if (cursor.moveToFirst()) { int result = cursor.getInt(0); return result; } else { LogUtils.logE("ContactDetailsTable." + "syncServerFetchNoOfChanges() COUNT(*) " + "should not return an empty cursor, returning 0"); return 0; } } finally { CloseUtils.close(cursor); } } /** * Fetches all the details that have changed and need to be synced with the * native. Details associated with new contacts are returned separately, * this is determined by a parameter. The * {@link #syncSetNativeIds(List, SQLiteDatabase)} method is used to mark * the details as up to date, once the sync has completed. * * @param readableDb A readable SQLite database object * @param newContacts true if details associated with new contacts should be * returned, otherwise modified details are returned. * @return A cursor which can be passed into the * {@link #syncNativeGetNextNewContactDetails(Cursor, List, int)} * method. */ public static Cursor syncNativeFetchContactChanges(SQLiteDatabase readableDb, boolean newContacts) { try { String statusMatch = ""; if (newContacts) { statusMatch = Field.NATIVESYNCCONTACTID + " IS NULL"; } else { /** Note this won't return NULLs. **/ statusMatch = Field.NATIVESYNCCONTACTID + "<>-1"; } return readableDb.rawQuery("SELECT " + Field.LOCALCONTACTID + "," + Field.NATIVECONTACTID + "," + Field.NATIVESYNCCONTACTID + "," + Field.DETAILLOCALID + "," + Field.NATIVEDETAILID + "," + Field.KEY + "," + Field.TYPE + "," + Field.STRINGVAL + "," + Field.ORDER + "," + Field.NATIVEDETAILVAL1 + "," + Field.NATIVEDETAILVAL2 + "," + Field.NATIVEDETAILVAL3 + " FROM " + TABLE_NAME + " WHERE " + statusMatch + " ORDER BY " + Field.LOCALCONTACTID, null); } catch (SQLException e) { LogUtils.logE("ContactDetailsTable.findDetailByKey() SQLException - " + "Unable to search for native contact ", e); return null; } } /** * Returns the next batch of contacts which need to be added on the native * database. The * {@link #syncNativeFetchContactChanges(SQLiteDatabase, boolean)} method is * used to retrieve the cursor initially, then this function can be called * many times until all the contacts have been fetched. When the list * returned from this method is empty the cursor has reached the end and the * sync is complete. * * @param c The cursor (see description above) * @param contactList Will be filled with contacts that need to be added to * the native * @param maxContactsToFetch Maximum number of contacts to return in the * list. The function can be called in a loop until all the * contacts have been retrieved. * @return true if successful, false if an error occurred (there seems to be * a defect in Android which occasionally causes this to fail due to * bad cursor state. The workaround is to retry the operation). */ public static boolean syncNativeGetNextNewContactDetails(Cursor c, List<Contact> contactList, int maxContactsToFetch) { final int QUERY_COLUMN_LOCALCONTACTID = 0; final int QUERY_COLUMN_NATIVECONTACTID = 1; final int QUERY_COLUMN_NATIVESYNCCONTACTID = 2; final int QUERY_COLUMN_LOCALDETAILID = 3; final int QUERY_COLUMN_NATIVEDETAILID = 4; final int QUERY_COLUMN_KEY = 5; final int QUERY_COLUMN_KEYTYPE = 6; final int QUERY_COLUMN_VAL = 7; final int QUERY_COLUMN_ORDER = 8; final int QUERY_COLUMN_NATIVEVAL1 = 9; final int QUERY_COLUMN_NATIVEVAL2 = 10; final int QUERY_COLUMN_NATIVEVAL3 = 11; try { contactList.clear(); Contact currentContact = null; while (c.moveToNext()) { final ContactDetail detail = new ContactDetail(); detail.localContactID = c.getLong(QUERY_COLUMN_LOCALCONTACTID); if (!c.isNull(QUERY_COLUMN_NATIVECONTACTID)) { detail.nativeContactId = c.getInt(QUERY_COLUMN_NATIVECONTACTID); } else { detail.nativeContactId = null; } if (currentContact == null || !currentContact.localContactID.equals(detail.localContactID)) { if (contactList.size() >= maxContactsToFetch) { if (currentContact != null) { c.moveToPrevious(); } break; } currentContact = new Contact(); currentContact.localContactID = detail.localContactID; currentContact.nativeContactId = detail.nativeContactId; contactList.add(currentContact); } if (!c.isNull(QUERY_COLUMN_NATIVESYNCCONTACTID)) { detail.syncNativeContactId = c.getInt(QUERY_COLUMN_NATIVESYNCCONTACTID); } else { detail.syncNativeContactId = null; } if (!c.isNull(QUERY_COLUMN_LOCALDETAILID)) { detail.localDetailID = c.getLong(QUERY_COLUMN_LOCALDETAILID); } if (!c.isNull(QUERY_COLUMN_NATIVEDETAILID)) { detail.nativeDetailId = c.getInt(QUERY_COLUMN_NATIVEDETAILID); } else { detail.nativeDetailId = null; } detail.key = ContactDetail.DetailKeys.values()[c.getInt(QUERY_COLUMN_KEY)]; if (!c.isNull(QUERY_COLUMN_KEYTYPE)) { detail.keyType = ContactDetail.DetailKeyTypes.values()[c .getInt(QUERY_COLUMN_KEYTYPE)]; } detail.value = c.getString(QUERY_COLUMN_VAL); if (!c.isNull(QUERY_COLUMN_ORDER)) { detail.order = c.getInt(QUERY_COLUMN_ORDER); } if (!c.isNull(QUERY_COLUMN_NATIVEVAL1)) { detail.nativeVal1 = c.getString(QUERY_COLUMN_NATIVEVAL1); } if (!c.isNull(QUERY_COLUMN_NATIVEVAL2)) { detail.nativeVal2 = c.getString(QUERY_COLUMN_NATIVEVAL2); } if (!c.isNull(QUERY_COLUMN_NATIVEVAL3)) { detail.nativeVal3 = c.getString(QUERY_COLUMN_NATIVEVAL3); } currentContact.details.add(detail); } return true; } catch (IllegalStateException e) { LogUtils.logE("ContactDetailsTable.syncNativeGetNextNewContactDetails - " + "Unable to fetch modified contacts from people\n" + e); c.requery(); return false; } } /** * Retrieves the total number of details that have changed and need to be diff --git a/src/com/vodafone360/people/database/tables/PresenceTable.java b/src/com/vodafone360/people/database/tables/PresenceTable.java index 41e0a11..00c6804 100644 --- a/src/com/vodafone360/people/database/tables/PresenceTable.java +++ b/src/com/vodafone360/people/database/tables/PresenceTable.java @@ -1,414 +1,425 @@ /* * 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.Iterator; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.SQLKeys; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.NetworkPresence; import com.vodafone360.people.engine.presence.User; import com.vodafone360.people.utils.CloseUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.StringBufferPool; /** * PresenceTable... The table for storing the presence states of contacts. * * @throws SQLException is thrown when request to create a table fails with an * SQLException * @throws NullPointerException if the passed in database instance is null */ public abstract class PresenceTable { /*** * The name of the table as it appears in the database. */ public static final String TABLE_NAME = "Presence"; // it is used in the // tests /** * The return types for the add/update method: if a new record was added. */ public static final int USER_ADDED = 0; /** * The return types for the add/update method: if an existing record was * updated. */ public static final int USER_UPDATED = 1; /** * The return types for the add/update method: if an error happened and * prevented the record from being added or updated. */ public static final int USER_NOTADDED = 2; /** * An enumeration of all the field names in the database, containing ID, * LOCAL_CONTACT_ID, USER_ID, NETWORK_ID, NETWORK_STATUS. */ private static enum Field { /** * The primary key. */ ID("id"), /** * The internal representation of the serverId for this account. */ LOCAL_CONTACT_ID("LocalContactId"), /** * This is contact list id: gmail, facebook, nowplus or other account, * STRING. */ USER_ID("ImAddress"), /** * The SocialNetwork id, INT. */ NETWORK_ID("NetworkId"), /** * The presence status id, INT. */ NETWORK_STATUS("Status"); /** * The name of the field as it appears in the database. */ private String mField; /** * Constructor. * * @param field - Field name */ private Field(String field) { mField = field; } /* * This implementation returns the field name. (non-Javadoc) * @see java.lang.Enum#toString() */ public String toString() { return mField; } } /** * The constants for column indexes in the table: LocalContactId */ private static final int LOCAL_CONTACT_ID = 1; /** * The constants for column indexes in the table: ImAddress */ private static final int USER_ID = 2; /** * The constants for column indexes in the table: NetworkId */ private static final int NETWORK_ID = 3; /** * The constants for column indexes in the table: Status */ private static final int NETWORK_STATUS = 4; /** * The default message for the NullPointerException caused by the null * instance of database passed into PresenceTable methods. */ private static final String DEFAULT_ERROR_MESSAGE = "PresenceTable: the passed in database is null!"; + + /** + * Constant for "," + */ + private final static String COMMA = ","; /** * This method creates the PresenceTable. * * @param writableDb - the writable database * @throws SQLException is thrown when request to create a table fails with * an SQLException * @throws NullPointerException if the passed in database instance is null */ public static void create(SQLiteDatabase writableDb) throws SQLException, NullPointerException { DatabaseHelper.trace(true, "PresenceTable.create()"); if (writableDb == null) { throw new NullPointerException(DEFAULT_ERROR_MESSAGE); } String createSql = "CREATE TABLE IF NOT EXISTS " + DatabaseHelper.DATABASE_PRESENCE + "." + TABLE_NAME + " (" + Field.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.LOCAL_CONTACT_ID + " LONG, " + Field.USER_ID + " STRING, " + Field.NETWORK_ID + " INT, " + Field.NETWORK_STATUS + " INT);"; writableDb.execSQL(createSql); } /** * This method updates the user with the information from the User wrapper. * * @param user2Update - User info to update * @param ignoredNetworkIds - ArrayList of integer network ids presence state for which must be ignored. * @param writableDatabase - writable database * @return USER_ADDED if no user with user id like the one in user2Update * payload "status.getUserId()" ever existed in this table, * USER_UPDATED if the user already existed in the table and has * been successfully added, USER_NOT_ADDED - if user was not added. * @throws SQLException if the database layer throws this exception. * @throws NullPointerException if the passed in database instance is null. */ public static int updateUser(User user2Update, ArrayList<Integer> ignoredNetworkIds, SQLiteDatabase writableDatabase) throws SQLException, NullPointerException { int ret = USER_NOTADDED; if (writableDatabase == null) { throw new NullPointerException(DEFAULT_ERROR_MESSAGE); } if (user2Update != null) { ArrayList<NetworkPresence> statusesOnNetworks = user2Update.getPayload(); if (!statusesOnNetworks.isEmpty()) { ContentValues values = new ContentValues(); StringBuffer where = null; Iterator<NetworkPresence> itr = statusesOnNetworks.iterator(); NetworkPresence status = null; + long localContactId = user2Update.getLocalContactId(); + int networkId = 0; while (itr.hasNext()) { status = itr.next(); - if (ignoredNetworkIds == null || !ignoredNetworkIds.contains(status.getNetworkId())) { - values.put(Field.LOCAL_CONTACT_ID.toString(), user2Update.getLocalContactId()); + networkId = status.getNetworkId(); + if (ignoredNetworkIds == null || !ignoredNetworkIds.contains(networkId)) { + values.put(Field.LOCAL_CONTACT_ID.toString(), localContactId); values.put(Field.USER_ID.toString(), status.getUserId()); - values.put(Field.NETWORK_ID.toString(), status.getNetworkId()); + values.put(Field.NETWORK_ID.toString(), networkId); values.put(Field.NETWORK_STATUS.toString(), status.getOnlineStatusId()); where = StringBufferPool.getStringBuffer(Field.LOCAL_CONTACT_ID.toString()); - where.append(SQLKeys.EQUALS).append(user2Update.getLocalContactId()). - append(SQLKeys.AND).append(Field.NETWORK_ID).append(SQLKeys.EQUALS).append(status.getNetworkId()); + where.append(SQLKeys.EQUALS).append(localContactId). + append(SQLKeys.AND).append(Field.NETWORK_ID).append(SQLKeys.EQUALS).append(networkId); int numberOfAffectedRows = writableDatabase.update(TABLE_NAME, values, StringBufferPool.toStringThenRelease(where), null); if (numberOfAffectedRows == 0) { if (writableDatabase.insert(TABLE_NAME, null, values) != -1) { ret = USER_ADDED; } else { LogUtils.logE("PresenceTable updateUser(): could not add new user!"); } } else { if (ret == USER_NOTADDED) { ret = USER_UPDATED; } } values.clear(); } else if (ignoredNetworkIds != null) { // presence information from this network needs to be ignored itr.remove(); } } } } return ret; } /** * This method fills the provided user object with presence information. * * @param user User - the user with a localContactId != -1 * @param readableDatabase - the database to read from * @return user/me profile presence state wrapped in "User" wrapper class, * or NULL if the specified localContactId doesn't exist * @throws SQLException if the database layer throws this exception. * @throws NullPointerException if the passed in database instance is null. */ public static void getUserPresence(User user, SQLiteDatabase readableDatabase) throws SQLException, NullPointerException { if (readableDatabase == null) { throw new NullPointerException(DEFAULT_ERROR_MESSAGE); } if (user.getLocalContactId() < 0) { LogUtils.logE("PresenceTable.getUserPresenceByLocalContactId(): " + "#localContactId# parameter is -1 "); return; } Cursor c = null; try { c = readableDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + "=" + user.getLocalContactId(), null); - - int onlineStatus = OnlineStatus.OFFLINE.ordinal(); // i.e. 0 - - user.getPayload().clear(); - - while (c.moveToNext()) { - String userId = c.getString(USER_ID); - int networkId = c.getInt(NETWORK_ID); - int statusId = c.getInt(NETWORK_STATUS); - if (statusId > onlineStatus) { - onlineStatus = statusId; + if (c != null) { + int onlineStatus = OnlineStatus.OFFLINE.ordinal(); // i.e. 0 + ArrayList<NetworkPresence> payload = user.getPayload(); + payload.clear(); + while (c.moveToNext()) { + String userId = c.getString(USER_ID); + int networkId = c.getInt(NETWORK_ID); + int statusId = c.getInt(NETWORK_STATUS); + if (statusId > onlineStatus) { + onlineStatus = statusId; + } + payload.add(new NetworkPresence(userId, networkId, statusId)); } - user.getPayload().add(new NetworkPresence(userId, networkId, statusId)); + user.setOverallOnline(onlineStatus); } - user.setOverallOnline(onlineStatus); } finally { CloseUtils.close(c); c = null; } } /** * This method returns user/me profile presence state. * * @param localContactId - me profile localContactId * @param readableDatabase - the database to read from * @return user/me profile presence state wrapped in "User" wrapper class, * or NULL if the specified localContactId doesn't exist * @throws SQLException if the database layer throws this exception. * @throws NullPointerException if the passed in database instance is null. * @return user - User object filled with presence information. */ public static User getUserPresenceByLocalContactId(long localContactId, SQLiteDatabase readableDatabase) throws SQLException, NullPointerException { if (readableDatabase == null) { throw new NullPointerException(DEFAULT_ERROR_MESSAGE); } User user = null; if (localContactId < 0) { LogUtils.logE("PresenceTable.getUserPresenceByLocalContactId(): " + "#localContactId# parameter is -1 "); return user; } Cursor c = null; try { c = readableDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + "=" + localContactId, null); ArrayList<NetworkPresence> networkPresence = new ArrayList<NetworkPresence>(); user = new User(); int onlineStatus = OnlineStatus.OFFLINE.ordinal(); // i.e. 0 while (c.moveToNext()) { user.setLocalContactId(c.getLong(LOCAL_CONTACT_ID)); String userId = c.getString(USER_ID); int networkId = c.getInt(NETWORK_ID); int statusId = c.getInt(NETWORK_STATUS); if (statusId > onlineStatus) { onlineStatus = statusId; } networkPresence.add(new NetworkPresence(userId, networkId, statusId)); } if (!networkPresence.isEmpty()) { user.setOverallOnline(onlineStatus); user.setPayload(networkPresence); } } finally { CloseUtils.close(c); c = null; } return user; } /** * The method cleans the presence table: deletes all the rows. * * @param writableDatabase - database to write to. * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. * @throws NullPointerException if the passed in database instance is null. */ public static int setAllUsersOffline(SQLiteDatabase writableDatabase) throws NullPointerException { if (writableDatabase == null) { throw new NullPointerException(DEFAULT_ERROR_MESSAGE); } // To remove all rows and get a count pass "1" as the whereClause return writableDatabase.delete(TABLE_NAME, "1", null); } /** * The method cleans the presence table: deletes all the rows, except for * the given user localContactId ("Me Profile" localContactId) * * @param localContactIdOfMe - the localContactId of the user (long), whose * info should not be deleted * @param writableDatabase - database to write to. * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. * @throws NullPointerException if the passed in database instance is null. */ public static int setAllUsersOfflineExceptForMe(long localContactIdOfMe, SQLiteDatabase writableDatabase) throws NullPointerException { if (writableDatabase == null) { throw new NullPointerException(DEFAULT_ERROR_MESSAGE); } return writableDatabase.delete(TABLE_NAME, Field.LOCAL_CONTACT_ID + " != " + localContactIdOfMe, null); } /** * This method returns the array of distinct user local contact ids in this table. * @param readableDatabase - database. * @return ArrayList of Long distinct local contact ids from this table. */ public static ArrayList<Long> getLocalContactIds(SQLiteDatabase readableDatabase) { Cursor c = null; ArrayList<Long> ids = new ArrayList<Long>(); - c = readableDatabase.rawQuery("SELECT DISTINCT " +Field.LOCAL_CONTACT_ID+ " FROM " + TABLE_NAME, null); + try { - while (c.moveToNext()) { - ids.add(c.getLong(0)); + c = readableDatabase.rawQuery("SELECT DISTINCT " +Field.LOCAL_CONTACT_ID+ " FROM " + TABLE_NAME, null); + if (c != null) { + while (c.moveToNext()) { + ids.add(c.getLong(0)); + } } } finally { - c.close(); + CloseUtils.close(c); c = null; } return ids; } + /** * This method deletes information about the user presence states on the provided networks. * @param networksToDelete - ArrayList of integer network ids. * @param writableDatabase - writable database. * @throws NullPointerException is thrown when the provided database is null. */ public static void setTPCNetworksOffline(ArrayList<Integer> networksToDelete, SQLiteDatabase writableDatabase) throws NullPointerException { if (writableDatabase == null) { throw new NullPointerException(DEFAULT_ERROR_MESSAGE); } StringBuffer networks = StringBufferPool.getStringBuffer(); - final String COMMA = ","; for (Integer network : networksToDelete) { networks.append(network).append(COMMA); } if (networks.length() > 0) { networks.deleteCharAt(networks.lastIndexOf(COMMA)); } - StringBuilder where = new StringBuilder(Field.NETWORK_ID.toString()); + final StringBuilder where = new StringBuilder(Field.NETWORK_ID.toString()); where.append(" IN (").append(StringBufferPool.toStringThenRelease(networks)).append(")"); writableDatabase.delete(TABLE_NAME, where.toString(), null); } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index 49cae52..401f190 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,323 +1,318 @@ /* * 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.ContactSummary.OnlineStatus; 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 // TODO: this hard code needs change, must filter the identities // info by VCARD.IMADRESS Hashtable<String, String> status = new Hashtable<String, String>(); status.put("google", "online"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("facebook.com", "online"); status.put("hyves.nl", "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 users 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 modifications. */ protected static boolean updateDatabase(List<User> users, long idListeningTo, DatabaseHelper dbHelper) { boolean presenceChanged = false; boolean deleteNetworks = false; - - // the list of networks presence information for me we ignore - the networks where user is offline. + // the list of networks presence information for me we ignore - the networks where 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 (notNullOrBlank(userId)) { - int networkId = presence.getNetworkId(); + 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 + } // 360 contact, PC or MOBILE network else if (networkId == SocialNetwork.PC.ordinal() || networkId == SocialNetwork.MOBILE.ordinal()) { localContactId = ContactsTable.fetchLocalIdFromUserId(Long - .valueOf(userId), dbHelper.getReadableDatabase()); + .valueOf(userId), writableDb); if (localContactId != -1) { break; } } else { // 3rd party accounts localContactId = ContactDetailsTable.findLocalContactIdByKey( SocialNetwork.getPresenceValue(networkId).toString(), userId, - ContactDetail.DetailKeys.VCARD_IMADDRESS, dbHelper - .getReadableDatabase()); + 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, dbHelper.getWritableDatabase()); + // delete the information about offline networks from PresenceTable + PresenceTable.setTPCNetworksOffline(ignoredNetworks, writableDb); } } if (user.getLocalContactId() > -1) { - SQLiteDatabase writableDb = dbHelper.getWritableDatabase(); - -// 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); - + 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 alter the User wrapper fro me profile, and returns true if me profile information contains the ignored TPC networks information. + * 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); } } - if (!ignoredNetworks.isEmpty()) { - return true; - } - return false; + return !ignoredNetworks.isEmpty(); } protected static boolean updateMyPresence(User user, DatabaseHelper dbHelper) { boolean contactsChanged = false; SQLiteDatabase writableDb = dbHelper.getWritableDatabase(); if (PresenceTable.updateUser(user, null, writableDb) != 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); } } - /** - * @param input - * @return - */ - public static boolean notNullOrBlank(String input) { - return (input != null) && input.length() > 0; - } - } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index a0d7714..1c28acf 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,823 +1,802 @@ /* * 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.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.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; 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.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, IContactSyncObserver, ITcpConnectionListener { /** Check every 10 minutes. **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; - /** Max attempts to try. **/ -// private final static int MAX_RETRY_COUNT = 3; - /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private long mNextRuntime = -1; -// private AgentState mNetworkAgentState = AgentState.CONNECTED; - private DatabaseHelper mDbHelper; - private int mRetryNumber; - private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private List<TimelineSummaryItem> mFailedMessagesList; // (to, network) private boolean mContObsAdded; /** 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; /** * * @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>(); addAsContactSyncObserver(); } @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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (!mContObsAdded) { addAsContactSyncObserver(); } if (!canRun()) { mNextRuntime = -1; LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" + mNextRuntime); return mNextRuntime; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { 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 (mNextRuntime == -1) { LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!"); return 0; } else { return mNextRuntime; } } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + mNextRuntime + "]"); 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) { if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) { if (canRun()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setNextRuntime(); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20; } } } else { 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); } private void setNextRuntime() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again in [" + (CHECK_FREQUENCY / (1000 * 60)) + "] minutes"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY; } private void setRunNow() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW"); mNextRuntime = 0; } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setNextRuntime(); } else { setPresenceOffline(); mContObsAdded = false; - mRetryNumber = 0; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } /*** * 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); } @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: setRunNow(); } } @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++; } } if (mUsers.size() > 0) { 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 + "]"); UiAgent uiAgent = mEventCallback.getUiAgent(); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { uiAgent.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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { - mRetryNumber = 0; // reset time out 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:" + mRetryNumber); -// I believe retrying getPresenceList makes no sense, as it may "confuse" the RPG -// if (mRetryNumber < MAX_RETRY_COUNT) { -// getPresenceList(); -// mRetryNumber++; -// } else { -// mRetryNumber = 0; -// setPresenceOffline(); -// } + LogUtils.logW("PresenceEngine handleServerResponce(): TIME OUT IS RETURNED TO PRESENCE ENGINE."); } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { - mRetryNumber = 0; // reset time out 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: - mRetryNumber = 0; // reset time out 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; case IDENTITY_CHANGE: // identity has been added or removed, reset availability initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.name()); } } 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()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { Presence.setMyAvailability((Hashtable<String, String>)data); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); break; case CREATE_CONVERSATION: if (data != null) { List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; case SEND_CHAT_MESSAGE: if (data != null) { 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); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); } } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } private void initSetMyAvailabilityRequest(User myself) { if (myself == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !canRun()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the state of the engine. Also displays the login notification if * necessary. * * @param accounts */ public void setMyAvailability(Hashtable<String, String> myselfPresence) { if (myselfPresence == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with:" + myselfPresence); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), myselfPresence); Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values for myself myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } 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); } } } /** * 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. */ private void addAsContactSyncObserver() { if (EngineManager.getInstance() != null && EngineManager.getInstance().getContactSyncEngine() != null) { EngineManager.getInstance().getContactSyncEngine().addEventCallback(this); mContObsAdded = true; LogUtils.logD("ActivityEngine contactSync observer added."); } else { LogUtils.logE("ActivityEngine can't add to contactSync observers."); } } @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { LogUtils.logD("PresenceEngine onContactSyncStateChange called."); } @Override public void onProgressEvent(State currentState, int percent) { if (percent == 100) { switch (currentState) { case FETCHING_SERVER_CONTACTS: LogUtils .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_CONTACTS is done"); // mDownloadServerContactsComplete = true; // break; // case SYNCING_SERVER_ME_PROFILE: // LogUtils // .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_ME_PROFILE is done"); // mDownloadMeProfileComplete = true; // break; default: // nothing to do now break; } } } @Override public void onSyncComplete(ServiceStatus status) { LogUtils.logD("PresenceEngine onSyncComplete called."); } @Override public void onConnectionStateChanged(int state) { switch (state) { case STATE_CONNECTED: getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); - mRetryNumber = 0; mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } diff --git a/src/com/vodafone360/people/utils/HardcodedUtils.java b/src/com/vodafone360/people/utils/HardcodedUtils.java index fc97e55..c76e198 100644 --- a/src/com/vodafone360/people/utils/HardcodedUtils.java +++ b/src/com/vodafone360/people/utils/HardcodedUtils.java @@ -1,71 +1,65 @@ /* * 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.ArrayList; import java.util.Hashtable; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.NetworkPresence; import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; /** * @author timschwerdtner * Collection of hardcoded and duplicated code as a first step for refactoring. */ public class HardcodedUtils { /** * To be used with IPeopleService.setAvailability until identity handling * has been refactored. * @param Desired availability state * @return A hashtable for the set availability call */ public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) { Hashtable<String, String> availability = new Hashtable<String, String>(); LogUtils.logD("Setting Availability to: " + onlineStatus.toString()); // TODO: REMOVE HARDCODE setting everything possible to currentStatus availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString()); availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString()); availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString()); availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString()); availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString()); return availability; } /** * The static list of supported TPC accounts. */ - public static final ArrayList<Integer> THIRD_PARTY_CHAT_ACCOUNTS = new ArrayList<Integer>(); - - static { - THIRD_PARTY_CHAT_ACCOUNTS.add(SocialNetwork.FACEBOOK_COM.ordinal()); - THIRD_PARTY_CHAT_ACCOUNTS.add(SocialNetwork.GOOGLE.ordinal()); - THIRD_PARTY_CHAT_ACCOUNTS.add(SocialNetwork.HYVES_NL.ordinal()); - THIRD_PARTY_CHAT_ACCOUNTS.add(SocialNetwork.MICROSOFT.ordinal()); - } + public static final int[] THIRD_PARTY_CHAT_ACCOUNTS = new int[]{SocialNetwork.FACEBOOK_COM.ordinal(), + SocialNetwork.GOOGLE.ordinal(), SocialNetwork.HYVES_NL.ordinal(), + SocialNetwork.MICROSOFT.ordinal()}; }
360/360-Engine-for-Android
d4193cb50c7d34b73430d3e021a58aa50da7ef28
PAND-1634 Application crashes if user opens a text message before Timline entries are displayed
diff --git a/res/values/strings.xml b/res/values/strings.xml index 0972aa2..38e811d 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -1,641 +1,642 @@ <?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <string name="app_name">360 People</string> <!-- 2.X Accounts localized strings --> <string name="android_account_settings_category">General Settings</string> <string name="android_account_settings_title">Settings</string> <string name="android_account_settings_summary">Change settings in 360 People.</string> <string name="android_contact_profile_summary">"360 People profile"</string> <string name="android_contact_profile_detail">"View profile"</string> <string name="only_one_account_notice">Only one 360 People account is supported</string> <!-- .ui.status.StatusListAdapter --> <string name="StatusSummaryAdapter_today">Today</string> <string name="StatusSummaryAdapter_no_status_text">No status text</string> <string name="StatusSummaryAdapter_no_contact_name">Blank name</string> <!-- .ui.thirdparty.SyncingYourAddressBookActivity --> <string name="SyncingYourAddressBookActivity_Action_Default">Getting ready to sync...</string> <string name="SyncingYourAddressBookActivity_Action_Step_DownloadServerContacts">Retrieving contacts...</string> <string name="SyncingYourAddressBookActivity_Action_Step_FetchNativeContacts">Fetching phone\'s address book contacts...</string> <string name="SyncingYourAddressBookActivity_Action_Step_SyncMeProfile">Synchronizing your contact profile...</string> <string name="SyncingYourAddressBookActivity_Action_Step_UpdateServerContacts">Updating online contacts...</string> <string name="SyncingYourAddressBookActivity_ActionStatus_Sent">Sent %s of %s contacts</string> <string name="SyncingYourAddressBookActivity_ActionStatus_Received">Received %s of %s contacts</string> <string name="SyncingYourAddressBookActivity_ActionStatus_Changes">Sent %s of %s changes</string> <string name="SyncingYourAddressBookActivity_ActionProgress_Default">Step %s of %s</string> <string name="syncing_your_address_book">Syncing your Address Book ...</string> <!-- .engine.upgrade.UpgradeStatus --> <string name="UpgradeStatus_Message_default">A new version of this application is available for download on the Android Market</string> <string name="UpgradeStatus_Button_download">Download</string> <string name="UpgradeStatus_Button_cancel">Cancel</string> <!-- .ui.debug.UpdateServiceAgentActivity [update_serviceAgent.xml] --> <string name="UpdateServiceAgentActivity_TextView_title">External Events Simulator</string> <string name="UpdateServiceAgentActivity_CheckBox_NoInternetConnection">Is Connected To Internet</string> <string name="UpdateServiceAgentActivity_CheckBox_NoWorkingNetwork">Network Is Working</string> <string name="UpdateServiceAgentActivity_CheckBox_IsRoaming">In Roaming</string> <string name="UpdateServiceAgentActivity_CheckBox_IsRoamingAllowed">Data Roaming Is Allowed</string> <string name="UpdateServiceAgentActivity_CheckBox_IsBgConnection">In Background</string> <string name="UpdateServiceAgentActivity_CheckBox_IsBgDataAllowed">Background Data Is Allowed</string> <string name="UpdateServiceAgentActivity_CheckBox_NoWiFi">WiFi Is Active</string> <string name="UpdateServiceAgentActivity_Button_save">Apply Changes</string> <string name="UpdateServiceAgentActivity_Button_refresh">Refresh</string> <string name="UpdateServiceAgentActivity_ToggleButton_enabled">Test Enabled</string> <string name="UpdateServiceAgentActivity_ToggleButton_disabled">Test Disabled</string> <string name="UpdateServiceAgentActivity_TextView_statusConnected">Connection Status:</string> <string name="UpdateServiceAgentActivity_TextView_reasonDisconnected">Disconnection Reason:</string> <string name="UpdateServiceAgentActivity_TextView_deviceSettings">Device Settings:</string> <string name="UpdateServiceAgentActivity_TextView_options">Options:</string> <string name="UpdateServiceAgentActivity_TextView_networkOptions">Network Options:</string> <string name="UpdateServiceAgentActivity_TextView_networkType">Type Of Connection:</string> <string name="UpdateServiceAgentActivity_Radio_wiFi">WiFi</string> <string name="UpdateServiceAgentActivity_Radio_other">Other</string> <!-- Commonly used text strings --> <string name="Common_next">Next</string> <string name="Common_back">Back</string> <string name="Common_privacy_statement"><u>Privacy statement</u></string> <string name="Common_hint_mobile_number">Mobile number</string> <string name="Common_ok">ok</string> <string name="Common_yes">Yes</string> <string name="Common_no">No</string> <string name="Common_no_name">(No Name)</string> <string name="Common_unable_to_open_activity">Unable to open application</string> <string name="editContactDescription">Edit contact</string> <string name="insertContactDescription">Create contact</string> <!-- Validating Third Party Account Activity - validating_your_third_party_acount.xml --> <string name="ValidatingYourThirdPartyAccountActivity_validating_your">Logging in to </string> <string name="ValidatingYourThirdPartyAccountActivity_your_phone_is_validating_your_account">360 People is backing up and syncing your contacts. This may take a few minutes.</string> <!-- .ui.startup.signup.SignupPasswordCreationActivity [signup_password_creation.xml] --> <string name="SignupPasswordCreationActivity_hint_confirm_password">confirm password</string> <string name="SignupPasswordCreationActivity_hint_username">username</string> <string name="SignupPasswordCreationActivity_hint_password">password</string> <string name="SignupPasswordCreationActivity_account_information">360 People Set-up</string> <string name="SignupPasswordCreationActivity_i_agree_to_terms_and_conditions">I agree to the Terms &amp; Conditions</string> <string name="SignupPasswordCreationActivity_create_account">Create account</string> <string name="SignupPasswordCreationActivity_password_strength">Password strength</string> <string name="SignupPasswordCreationActivity_too_short">Your password must be at least 6 characters</string> <string name="SignupPasswordCreationActivity_terms_and_conditions"><u>Terms &amp; Conditions</u></string> <!-- .ui.startup.login.LoginAccountDetailsActivity [login_account_details.xml] --> <string name="LoginAccountDetailsActivity_by_signing_in_you_agree_to_the">By logging in you agree to the </string> <string name="LoginAccountDetailsActivity_welcome_to_nowplus">360 People Login</string> <string name="LoginAccountDetailsActivity_signin_hint_username">username</string> <string name="LoginAccountDetailsActivity_signin_hint_password">password</string> <string name="LoginAccountDetailsActivity_forgot_password"><u>I\'ve forgotten my username/password</u></string> <string name="LoginAccountDetailsActivity_signin">Log in</string> <!-- .ui.startup.LandingPageActivity [landing_page1.xml]--> <string name="LandingPage_landing_text1">Welcome to 360 People!</string> <string name="LandingPage_landing_page_overlay_text0">A Vodafone 360 service</string> <string name="LandingPage_landing_page_overlay_text">Bringing your world\ntogether</string> <string name="LandingPage_landing_button_sign_up_text">Sign up for an account</string> <string name="LandingPage_landing_button_sign_in_text">Log in to my account</string> <string name="LandingPage_landing_page_your_information">Your information will be sent to Vodafone.</string> <string name="sim_not_present">SIM not inserted</string> <string name="prompt_remove_user_data">Do you wish to remove all existing user data?</string> <string name="sim_has_changed">SIM has changed</string> <string name="user_data_has_been_removed">User data has been removed</string> <string name="information">Information</string> <!-- 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> </resources> \ No newline at end of file
360/360-Engine-for-Android
3ad3eff0298962b61500d4c3976fdccaa2efb79e
Fix for PAND-1637 Crash: ConcurrentModificationException in com.vodafone360.people
diff --git a/src/com/vodafone360/people/service/io/RequestQueue.java b/src/com/vodafone360/people/service/io/RequestQueue.java index ea8890c..d1dd299 100644 --- a/src/com/vodafone360/people/service/io/RequestQueue.java +++ b/src/com/vodafone360/people/service/io/RequestQueue.java @@ -1,474 +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.io; import java.util.ArrayList; import java.util.List; import com.vodafone360.people.Settings; 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 + "]"); - if (mListeners != null) { - mListeners.add(listener); - } - } + 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 + "]"); - if (mListeners != null) { - mListeners.remove(listener); - } - } + 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() { - LogUtils.logW("RequestQueue.notifyOfItemInRequestQueue() listener[" + mListeners + "]"); - for (IQueueListener listener : mListeners) - listener.notifyOfItemInRequestQueue(); - } + 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 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. * @return True if the request was found and removed. */ protected boolean removeRequest(int requestId) { 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 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(request.getRequestId(), null, request.mEngineId); // 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(request.getRequestId(), null, request.mEngineId); } } } } } /** * 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(request.getRequestId(), null, request.mEngineId); } } } /** * 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 ""; } StringBuffer sb = new StringBuffer("Queue Size: " + mRequests.size() + "; 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() + " [" + request.isActive() + "]"); } if (i < (mRequests.size() - 1)) { sb.append(", "); } } return sb.toString(); } }
360/360-Engine-for-Android
3defe15680b7d244b7760317bd80a0e8d069dab3
Added tests/res directory
diff --git a/tests/res/.placeholder b/tests/res/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/tests/res/drawable-hdpi/.placeholder b/tests/res/drawable-hdpi/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/tests/res/drawable-ldpi/.placeholder b/tests/res/drawable-ldpi/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/tests/res/drawable-mdpi/.placeholder b/tests/res/drawable-mdpi/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/tests/res/layout/.placeholder b/tests/res/layout/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/tests/res/raw/.placeholder b/tests/res/raw/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/tests/res/values/.placeholder b/tests/res/values/.placeholder new file mode 100644 index 0000000..e69de29
360/360-Engine-for-Android
b301a117151d798c3773e1e3635ae7059b5df93c
Added tests/res directory
diff --git a/tests/res/.placeholder b/tests/res/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/tests/res/drawable-hdpi/.placeholder b/tests/res/drawable-hdpi/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/tests/res/drawable-ldpi/.placeholder b/tests/res/drawable-ldpi/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/tests/res/drawable-mdpi/.placeholder b/tests/res/drawable-mdpi/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/tests/res/layout/.placeholder b/tests/res/layout/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/tests/res/raw/.placeholder b/tests/res/raw/.placeholder new file mode 100644 index 0000000..e69de29 diff --git a/tests/res/values/.placeholder b/tests/res/values/.placeholder new file mode 100644 index 0000000..e69de29
360/360-Engine-for-Android
2c2d493911bfc3c6c9b30c51265916d74e0d3da4
- suited tests/build.xml for blocking unit tests
diff --git a/tests/build.xml b/tests/build.xml index 87ceb78..f808c93 100644 --- a/tests/build.xml +++ b/tests/build.xml @@ -1,696 +1,697 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <project name="tests"> <property environment="env"/> <!-- The build.properties file can be created by you and is never touched by the 'android' tool. This is the place to change some of the default property values used by the Ant rules. Here are some properties you may want to change/update: application.package the name of your application package as defined in the manifest. Used by the 'uninstall' rule. source.dir the name of the source directory. Default is 'src'. out.dir the name of the output directory. Default is 'bin'. Properties related to the SDK location or the project target should be updated using the 'android' tool with the 'update' action. This file is an integral part of the build system for your application and should be checked in in Version Control Systems. --> <property file="build.properties" /> <!-- The default.properties file is created and updated by the 'android' tool, as well as ADT. This file is an integral part of the build system for your application and should be checked in in Version Control Systems. --> <property file="default.properties" /> <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it already on your system, please do so. After setting it, create a new properties file in build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties to it. --> <property file="../build_property_files/${env.USERNAME_360}.properties" /> <echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the XMLTask is found in ${xml.task.dir}...</echo> <!-- Custom Android task to deal with the project target, and import the proper rules. This requires ant 1.6.0 or above. --> <path id="android.antlibs"> <pathelement path="${sdk.dir}/tools/lib/anttasks.jar" /> <pathelement path="${sdk.dir}/tools/lib/sdklib.jar" /> <pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" /> <pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" /> <pathelement path="${sdk.dir}/tools/lib/jarutils.jar" /> </path> <taskdef name="setup" classname="com.android.ant.SetupTask" classpathref="android.antlibs" /> <!-- Execute the Android Setup task that will setup some properties specific to the target, and import the build rules files. The rules file is imported from <SDK>/platforms/<target_platform>/templates/android_rules.xml To customize some build steps for your project: - copy the content of the main node <project> from android_rules.xml - paste it in this build.xml below the <setup /> task. - disable the import by changing the setup task below to <setup import="false" /> This will ensure that the properties are setup correctly but that your customized build steps are used. --> <setup import="false" /> <!-- EMMA Coverage interface for build script --> <target name="emma-coverage-interface"> <echo>EMMA Coverage interface for build script.</echo> <ant target="coverage" /> </target> <!-- JUunit interface for build script --> - <target name="run-tests-interface"> + <target name="run-tests-interface" depends="-dirs"> <echo>JUunit interface for build script.</echo> <ant target="run-tests" /> </target> <!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############ This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be run inside the build script without path issues. --> <!-- This rules file is meant to be imported by the custom Ant task: com.android.ant.AndroidInitTask The following properties are put in place by the importing task: android.jar, android.aidl, aapt, aidl, and dx Additionnaly, the task sets up the following classpath reference: android.target.classpath This is used by the compiler task as the boot classpath. --> <!-- Custom tasks --> <taskdef name="aaptexec" classname="com.android.ant.AaptExecLoopTask" classpathref="android.antlibs" /> <taskdef name="apkbuilder" classname="com.android.ant.ApkBuilderTask" classpathref="android.antlibs" /> <taskdef name="xpath" classname="com.android.ant.XPathTask" classpathref="android.antlibs" /> <!-- Properties --> <!-- Tells adb which device to target. You can change this from the command line by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for the emulator. --> <property name="adb.device.arg" value="" /> <property name="android.tools.dir" location="${sdk.dir}/tools" /> <!-- Name of the application package extracted from manifest file --> <xpath input="AndroidManifest.xml" expression="/manifest/@package" output="manifest.package" /> <!-- Input directories --> <property name="source.dir" value="src" /> <property name="source.absolute.dir" location="${source.dir}" /> <property name="gen.dir" value="gen" /> <property name="gen.absolute.dir" location="${gen.dir}" /> <property name="resource.dir" value="res" /> <property name="resource.absolute.dir" location="${resource.dir}" /> <property name="asset.dir" value="assets" /> <property name="asset.absolute.dir" location="${asset.dir}" /> <!-- Directory for the third party java libraries --> <property name="external.libs.dir" value="libs" /> <property name="external.libs.absolute.dir" location="${external.libs.dir}" /> <!-- Directory for the native libraries --> <property name="native.libs.dir" value="libs" /> <property name="native.libs.absolute.dir" location="${native.libs.dir}" /> <!-- Output directories --> <property name="out.dir" value="bin" /> <property name="out.absolute.dir" location="${out.dir}" /> <property name="out.classes.dir" value="${out.absolute.dir}/classes" /> <property name="out.classes.absolute.dir" location="${out.classes.dir}" /> <!-- Intermediate files --> <property name="dex.file.name" value="classes.dex" /> <property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" /> <!-- The final package file to generate --> <property name="out.debug.unaligned.package" location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" /> <property name="out.debug.package" location="${out.absolute.dir}/${ant.project.name}-debug.apk" /> <property name="out.unsigned.package" location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" /> <property name="out.unaligned.package" location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" /> <property name="out.release.package" location="${out.absolute.dir}/${ant.project.name}-release.apk" /> <!-- Verbosity --> <property name="verbose" value="false" /> <!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false' The property 'verbosity' is not user configurable and depends exclusively on 'verbose' value.--> <condition property="verbosity" value="verbose" else="quiet"> <istrue value="${verbose}" /> </condition> <!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose' --> <condition property="v.option" value="-v" else=""> <istrue value="${verbose}" /> </condition> <!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' --> <condition property="verbose.option" value="--verbose" else=""> <istrue value="${verbose}" /> </condition> <!-- Tools --> <condition property="exe" value=".exe" else=""><os family="windows" /></condition> <property name="adb" location="${android.tools.dir}/adb${exe}" /> <property name="zipalign" location="${android.tools.dir}/zipalign${exe}" /> <!-- Emma configuration --> <property name="emma.dir" value="${sdk.dir}/tools/lib" /> <path id="emma.lib"> <pathelement location="${emma.dir}/emma.jar" /> <pathelement location="${emma.dir}/emma_ant.jar" /> </path> <taskdef resource="emma_ant.properties" classpathref="emma.lib" /> <!-- End of emma configuration --> <!-- Macros --> <!-- Configurable macro, which allows to pass as parameters output directory, output dex filename and external libraries to dex (optional) --> <macrodef name="dex-helper"> <element name="external-libs" optional="yes" /> <element name="extra-parameters" optional="yes" /> <sequential> <echo>Converting compiled files and external libraries into ${intermediate.dex.file}... </echo> <apply executable="${dx}" failonerror="true" parallel="true"> <arg value="--dex" /> <arg value="--output=${intermediate.dex.file}" /> <extra-parameters /> <arg line="${verbose.option}" /> <arg path="${out.classes.absolute.dir}" /> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> <external-libs /> </apply> </sequential> </macrodef> <!-- This is macro that enable passing variable list of external jar files to ApkBuilder Example of use: <package-helper> <extra-jars> <jarfolder path="my_jars" /> <jarfile path="foo/bar.jar" /> <jarfolder path="your_jars" /> </extra-jars> </package-helper> --> <macrodef name="package-helper"> <attribute name="sign.package" /> <element name="extra-jars" optional="yes" /> <sequential> <apkbuilder outfolder="${out.absolute.dir}" basename="${ant.project.name}" signed="@{sign.package}" verbose="${verbose}"> <file path="${intermediate.dex.file}" /> <sourcefolder path="${source.absolute.dir}" /> <nativefolder path="${native.libs.absolute.dir}" /> <jarfolder path="${external.libs.absolute.dir}" /> <extra-jars/> </apkbuilder> </sequential> </macrodef> <!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets debug, -debug-with-emma and release.--> <macrodef name="zipalign-helper"> <attribute name="in.package" /> <attribute name="out.package" /> <sequential> <echo>Running zip align on final apk...</echo> <exec executable="${zipalign}" failonerror="true"> <arg line="${v.option}" /> <arg value="-f" /> <arg value="4" /> <arg path="@{in.package}" /> <arg path="@{out.package}" /> </exec> </sequential> </macrodef> <!-- This is macro used only for sharing code among two targets, -install and -install-with-emma which do exactly the same but differ in dependencies --> <macrodef name="install-helper"> <sequential> <echo>Installing ${out.debug.package} onto default emulator or device...</echo> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="install" /> <arg value="-r" /> <arg path="${out.debug.package}" /> </exec> </sequential> </macrodef> <!-- Rules --> <!-- Creates the output directories if they don't exist yet. --> <target name="-dirs"> <echo>Creating output directories if needed...</echo> <mkdir dir="${resource.absolute.dir}" /> <mkdir dir="${external.libs.absolute.dir}" /> <mkdir dir="${gen.absolute.dir}" /> <mkdir dir="${out.absolute.dir}" /> <mkdir dir="${out.classes.absolute.dir}" /> + <mkdir dir="${tested.project.absolute.dir}/output/" /> </target> <!-- Generates the R.java file for this project's resources. --> <target name="-resource-src" depends="-dirs"> <echo>Generating R.java / Manifest.java from the resources...</echo> <exec executable="${aapt}" failonerror="true"> <arg value="package" /> <arg line="${v.option}" /> <arg value="-m" /> <arg value="-J" /> <arg path="${gen.absolute.dir}" /> <arg value="-M" /> <arg path="AndroidManifest.xml" /> <arg value="-S" /> <arg path="${resource.absolute.dir}" /> <arg value="-I" /> <arg path="${android.jar}" /> </exec> </target> <!-- Generates java classes from .aidl files. --> <target name="-aidl" depends="-dirs"> <echo>Compiling aidl files into Java classes...</echo> <apply executable="${aidl}" failonerror="true"> <arg value="-p${android.aidl}" /> <arg value="-I${source.absolute.dir}" /> <arg value="-o${gen.absolute.dir}" /> <fileset dir="${source.absolute.dir}"> <include name="**/*.aidl" /> </fileset> </apply> </target> <!-- Compiles this project's .java files into .class files. --> <target name="compile" depends="-resource-src, -aidl" description="Compiles project's .java files into .class files"> <!-- If android rules are used for a test project, its classpath should include tested project's location --> <condition property="extensible.classpath" value="${tested.project.absolute.dir}/bin/classes" else="."> <isset property="tested.project.absolute.dir" /> </condition> <echo>extensible.classpath: ${extensible.classpath}</echo> <javac encoding="ascii" target="1.5" debug="true" extdirs="" destdir="${out.classes.absolute.dir}" bootclasspathref="android.target.classpath" verbose="${verbose}" classpath="${extensible.classpath}"> <src path="${source.absolute.dir}" /> - <src path="../../${ui.project.name}/${source.dir}" /> <src path="${gen.absolute.dir}" /> <classpath> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> </classpath> </javac> </target> <!-- Converts this project's .class files into .dex files --> <target name="-dex" depends="compile"> <dex-helper /> </target> <!-- Puts the project's resources into the output package file This actually can create multiple resource package in case Some custom apk with specific configuration have been declared in default.properties. --> <target name="-package-resources"> <echo>Packaging resources</echo> <aaptexec executable="${aapt}" command="package" manifest="AndroidManifest.xml" resources="${resource.absolute.dir}" assets="${asset.absolute.dir}" androidjar="${android.jar}" outfolder="${out.absolute.dir}" basename="${ant.project.name}" /> </target> <!-- Packages the application and sign it with a debug key. --> <target name="-package-debug-sign" depends="-dex, -package-resources"> <package-helper sign.package="true" /> </target> <!-- Packages the application without signing it. --> <target name="-package-no-sign" depends="-dex, -package-resources"> <package-helper sign.package="false" /> </target> <target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again"> <subant target="compile"> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <!-- Builds debug output package, provided all the necessary files are already dexed --> <target name="debug" depends="-compile-tested-if-test, -package-debug-sign" description="Builds the application and signs it with a debug key."> <zipalign-helper in.package="${out.debug.unaligned.package}" out.package="${out.debug.package}" /> <echo>Debug Package: ${out.debug.package}</echo> </target> <target name="-release-check"> <condition property="release.sign"> <and> <isset property="key.store" /> <isset property="key.alias" /> </and> </condition> </target> <target name="-release-nosign" depends="-release-check" unless="release.sign"> <echo>No key.store and key.alias properties found in build.properties.</echo> <echo>Please sign ${out.unsigned.package} manually</echo> <echo>and run zipalign from the Android SDK tools.</echo> </target> <target name="release" depends="-package-no-sign, -release-nosign" if="release.sign" description="Builds the application. The generated apk file must be signed before it is published."> <!-- Gets passwords --> <input message="Please enter keystore password (store:${key.store}):" addproperty="key.store.password" /> <input message="Please enter password for alias '${key.alias}':" addproperty="key.alias.password" /> <!-- Signs the APK --> <echo>Signing final apk...</echo> <signjar jar="${out.unsigned.package}" signedjar="${out.unaligned.package}" keystore="${key.store}" storepass="${key.store.password}" alias="${key.alias}" keypass="${key.alias.password}" verbose="${verbose}" /> <!-- Zip aligns the APK --> <zipalign-helper in.package="${out.unaligned.package}" out.package="${out.release.package}" /> <echo>Release Package: ${out.release.package}</echo> </target> <target name="install" depends="debug" description="Installs/reinstalls the debug package onto a running emulator or device. If the application was previously installed, the signatures must match." > <install-helper /> </target> <target name="-uninstall-check"> <condition property="uninstall.run"> <isset property="manifest.package" /> </condition> </target> <target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run"> <echo>Unable to run 'ant uninstall', manifest.package property is not defined. </echo> </target> <!-- Uninstalls the package from the default emulator/device --> <target name="uninstall" depends="-uninstall-error" if="uninstall.run" description="Uninstalls the application from a running emulator or device."> <echo>Uninstalling ${manifest.package} from the default emulator or device...</echo> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="uninstall" /> <arg value="${manifest.package}" /> </exec> </target> <target name="clean" description="Removes output files created by other targets."> <delete dir="${out.absolute.dir}" verbose="${verbose}" /> <delete dir="${gen.absolute.dir}" verbose="${verbose}" /> </target> <!-- Targets for code-coverage measurement purposes, invoked from external file --> <!-- Emma-instruments tested project classes (compiles the tested project if necessary) and writes instrumented classes to ${instrumentation.absolute.dir}/classes --> <target name="-emma-instrument" depends="compile"> <echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo> <!-- It only instruments class files, not any external libs --> <emma enabled="true"> <instr verbosity="${verbosity}" mode="overwrite" instrpath="${out.absolute.dir}/classes" outdir="${out.absolute.dir}/classes"> </instr> <!-- TODO: exclusion filters on R*.class and allowing custom exclusion from user defined file --> </emma> </target> <target name="-dex-instrumented" depends="-emma-instrument"> <dex-helper> <extra-parameters> <arg value="--no-locals" /> </extra-parameters> <external-libs> <fileset file="${emma.dir}/emma_device.jar" /> </external-libs> </dex-helper> </target> <!-- Invoked from external files for code coverage purposes --> <target name="-package-with-emma" depends="-dex-instrumented, -package-resources"> <package-helper sign.package="true"> <extra-jars> <!-- Injected from external file --> <jarfile path="${emma.dir}/emma_device.jar" /> </extra-jars> </package-helper> </target> <target name="-debug-with-emma" depends="-package-with-emma"> <zipalign-helper in.package="${out.debug.unaligned.package}" out.package="${out.debug.package}" /> </target> <target name="-install-with-emma" depends="-debug-with-emma"> <install-helper /> </target> <!-- End of targets for code-coverage measurement purposes --> <target name="help"> <!-- displays starts at col 13 |13 80| --> <echo>Android Ant Build. Available targets:</echo> <echo> help: Displays this help.</echo> <echo> clean: Removes output files created by other targets.</echo> <echo> compile: Compiles project's .java files into .class files.</echo> <echo> debug: Builds the application and signs it with a debug key.</echo> <echo> release: Builds the application. The generated apk file must be</echo> <echo> signed before it is published.</echo> <echo> install: Installs/reinstalls the debug package onto a running</echo> <echo> emulator or device.</echo> <echo> If the application was previously installed, the</echo> <echo> signatures must match.</echo> <echo> uninstall: Uninstalls the application from a running emulator or</echo> <echo> device.</echo> </target> <!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ --> <!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## --> <property name="tested.project.absolute.dir" location="${tested.project.dir}" /> - <property name="junit.out.file" value="${tested.project.absolute.dir}\output\junit-result.txt" /> + <property name="junit.out.file" value="${tested.project.absolute.dir}/output/junit-result.txt" /> <property name="instrumentation.dir" value="instrumented" /> <property name="instrumentation.absolute.dir" location="${instrumentation.dir}" /> <property name="test.runner" value="android.test.InstrumentationTestRunner" /> <!-- Application package of the tested project extracted from its manifest file --> <xpath input="${tested.project.absolute.dir}/AndroidManifest.xml" expression="/manifest/@package" output="tested.manifest.package" /> <!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated project --> <property name="emma.dump.file" value="/data/data/${tested.manifest.package}/files/coverage.ec" /> <macrodef name="run-tests-helper"> <attribute name="emma.enabled" default="false" /> <element name="extra-instrument-args" optional="yes" /> <sequential> <echo>Running tests with output sent to ${junit.out.file}...</echo> + <exec executable="${adb}" failonerror="true" output="${junit.out.file}"> <arg value="shell" /> <arg value="am" /> <arg value="instrument" /> <arg value="-w" /> <arg value="-r" /> <!-- XML output --> <arg value="-e" /> <arg value="coverage" /> <arg value="@{emma.enabled}" /> <extra-instrument-args /> <arg value="${manifest.package}/${test.runner}" /> </exec> <loadfile srcfile="${junit.out.file}" property="result"> <filterchain> <linecontains> <contains value="INSTRUMENTATION_CODE: -1"/> </linecontains> </filterchain> </loadfile> <loadfile srcfile="${junit.out.file}" property="result2"> <filterchain> <linecontains> <contains value="FAILURES"/> </linecontains> </filterchain> </loadfile> <echo>Result ${result} ${result2}</echo> <loadfile property="junit-out-file" srcFile="${junit.out.file}"/> <echo>Junit results...</echo> <echo>${junit-out-file}</echo> <fail unless="result">JUnit tests failed, please look at ${junit.out.file} for more information.</fail> <fail if="result2">JUnit tests failed, please look at ${junit.out.file} for more information.</fail> </sequential> </macrodef> <!-- Invoking this target sets the value of extensible.classpath, which is being added to javac classpath in target 'compile' (android_rules.xml) --> <target name="-set-coverage-classpath"> <property name="extensible.classpath" location="${instrumentation.absolute.dir}/classes" /> </target> <!-- Ensures that tested project is installed on the device before we run the tests. Used for ordinary tests, without coverage measurement --> <target name="-install-tested-project"> <property name="do.not.compile.again" value="true" /> <subant target="install"> <property name="sdk.dir" location="${sdk.dir}"/> <property name="sdk-location" location="${sdk-location}"/> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <target name="run-tests" depends="-install-tested-project, install" description="Runs tests from the package defined in test.package property"> <run-tests-helper /> </target> <target name="-install-instrumented"> <property name="do.not.compile.again" value="true" /> <subant target="-install-with-emma"> <property name="out.absolute.dir" value="${instrumentation.absolute.dir}" /> <property name="sdk.dir" location="${sdk.dir}"/> <property name="sdk-location" location="${sdk-location}"/> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <target name="coverage" depends="-set-coverage-classpath, -install-instrumented, install" description="Runs the tests against the instrumented code and generates code coverage report"> <run-tests-helper emma.enabled="true"> <extra-instrument-args> <arg value="-e" /> <arg value="coverageFile" /> <arg value="${emma.dump.file}" /> </extra-instrument-args> </run-tests-helper> <echo>Downloading coverage file into project directory...</echo> <exec executable="${adb}" failonerror="true"> <arg value="pull" /> <arg value="${emma.dump.file}" /> <arg value="coverage.ec" /> </exec> <echo>#################### INSERTED CODE #####################</echo> <move file="${tested.project.absolute.dir}/coverage.em" tofile="${tested.project.absolute.dir}/tests/coverage.em"/> <echo>#################### INSERTED CODE #####################</echo> <echo>Extracting coverage report...</echo> <emma> <report sourcepath="${tested.project.absolute.dir}/${source.dir}" verbosity="${verbosity}"> <!-- TODO: report.dir or something like should be introduced if necessary --> <infileset dir="."> <include name="coverage.ec" /> <include name="coverage.em" /> </infileset> <!-- TODO: reports in other, indicated by user formats --> <html outfile="coverage.html" /> </report> </emma> <echo>Cleaning up temporary files...</echo> <delete dir="${instrumentation.absolute.dir}" /> <delete file="coverage.ec" /> <delete file="coverage.em" /> <echo>Saving the report file in ${basedir}/coverage/coverage.html</echo> </target> <!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## --> </project> \ No newline at end of file
360/360-Engine-for-Android
0143c11225c4b1aa22027ca4794e04c840637f44
fix the not compiling unit test
diff --git a/tests/src/com/vodafone360/people/tests/database/NowPlusPresenceTableTest.java b/tests/src/com/vodafone360/people/tests/database/NowPlusPresenceTableTest.java index 0113be1..89e4d25 100644 --- a/tests/src/com/vodafone360/people/tests/database/NowPlusPresenceTableTest.java +++ b/tests/src/com/vodafone360/people/tests/database/NowPlusPresenceTableTest.java @@ -1,216 +1,216 @@ /* * 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.test.suitebuilder.annotation.Suppress; import android.util.Log; import com.vodafone360.people.database.tables.PresenceTable; import com.vodafone360.people.engine.presence.User; import com.vodafone360.people.utils.LogUtils; @Suppress public class NowPlusPresenceTableTest extends NowPlusTableTestCase { public NowPlusPresenceTableTest() { super(); } public void testCreate() { Log.i(LOG_TAG, "***** testCreateTable *****"); mTestDatabase.getWritableDatabase().execSQL("ATTACH DATABASE ':memory:' AS presence1_db;"); PresenceTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "***** testCreateTable SUCCEEDED*****"); } public void testUpdateUser() { Log.i(LOG_TAG, "***** testUpdateUser *****"); PresenceTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "***** testUpdateUser: table created*****"); - assertTrue("The method adds a null user and returns true", PresenceTable.updateUser(null, mTestDatabase.getWritableDatabase())==PresenceTable.USER_NOTADDED); + assertTrue("The method adds a null user and returns true", PresenceTable.updateUser(null, null, mTestDatabase.getWritableDatabase())==PresenceTable.USER_NOTADDED); Log.i(LOG_TAG, "***** testUpdateUser: NULL test SUCCEEDED *****"); 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("google::[email protected]", status); user.setLocalContactId(12L);// fake localId - assertTrue("the user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) != PresenceTable.USER_NOTADDED); + assertTrue("the user was not added to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) != PresenceTable.USER_NOTADDED); Log.i(LOG_TAG, "***** testUpdateUser Good User test SUCCEEDED*****"); user = null; // now, update the user status.put("google", "offline"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("pc", "offline"); user = new User("google::[email protected]", status); user.setLocalContactId(12L);// fake localId - assertTrue("the Existing NowplusUser might be duplicated to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_UPDATED); + assertTrue("the Existing NowplusUser might be duplicated to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_UPDATED); User user1 = PresenceTable.getUserPresenceByLocalContactId(12L, mTestDatabase.getReadableDatabase()); assertTrue("the initial and fetched users are not the same!", user.equals(user1)); Log.i(LOG_TAG, "***** testUpdateUser test SUCCEEDED*****"); } public void testGetMeProfilePresenceById() { Log.i(LOG_TAG, "***** GetMeProfilePresenceById() *****"); PresenceTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "***** GetMeProfilePresenceById(): table created*****"); 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("12345678", status); //imaginary Me Profile user.setLocalContactId(12L);// fake localId - assertTrue("the user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_ADDED); + assertTrue("the user was not added to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_ADDED); Log.i(LOG_TAG, "***** testUpdateUser Good User test SUCCEEDED*****"); User user1 = PresenceTable.getUserPresenceByLocalContactId(12L, mTestDatabase.getReadableDatabase()); assertTrue("the initial and fetched users are not the same!", user.equals(user1)); assertNull(PresenceTable.getUserPresenceByLocalContactId(-1L, mTestDatabase.getReadableDatabase())); Log.i(LOG_TAG, "***** GetMeProfilePresenceById() SUCCEEEDED*****"); } // public void testDropTable() { // Log.i(LOG_TAG, "***** testDropTable() *****"); // PresenceTable.create(mTestDatabase.getWritableDatabase()); // Log.i(LOG_TAG, "***** testDropTable(): table created*****"); // // 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("google::[email protected]", status); // assertTrue("the user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) != PresenceTable.USER_NOTADDED); // user = null; //// 4 // NowPlusPresenceDbUtilsTest.dropTable(mTestDatabase.getWritableDatabase()); // Log.i(LOG_TAG, "***** testDropTable(): dropped table*****"); // // PresenceTable.create(mTestDatabase.getWritableDatabase()); // Log.i(LOG_TAG, "***** testDropTable(): table created again*****"); // // int count = PresenceTable.setAllUsersOffline(mTestDatabase.getWritableDatabase()); // assertTrue("The count of deleted rows is not the expected one:"+count, count == 0); // Log.i(LOG_TAG, "***** testDropTable() test SUCCEEDED*****"); // } public void testSetAllUsersOffline() { Log.i(LOG_TAG, "***** testSetAllUsersOffline() *****"); PresenceTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "***** testSetAllUsersOffline(): table created*****"); - assertTrue("The method adds a null user and returns true", PresenceTable.updateUser(null, mTestDatabase.getWritableDatabase())==PresenceTable.USER_NOTADDED); + assertTrue("The method adds a null user and returns true", PresenceTable.updateUser(null, null, mTestDatabase.getWritableDatabase())==PresenceTable.USER_NOTADDED); Log.i(LOG_TAG, "***** testUpdateUser: NULL test SUCCEEDED *****"); // 1 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("google::[email protected]", status); user.setLocalContactId(12L); - assertTrue("the user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_ADDED); + assertTrue("the user was not added to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_ADDED); LogUtils.logE("User1:"+user.toString()); user = null; //4 // user = new User("UNPARSEBLE", status); // assertTrue("the UNPARSEBLE user was added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase())== PresenceTable.USER_NOTADDED); // user = null; //4 user = new User("12345678", status); user.setLocalContactId(13L); - assertTrue("the NowplusUser user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase())== PresenceTable.USER_ADDED); + assertTrue("the NowplusUser user was not added to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase())== PresenceTable.USER_ADDED); // user = null; //8 // status.put("pc", "offline"); // user = new User("12345678", status); user.setLocalContactId(13L); LogUtils.logE("User2:"+user.toString()); LogUtils.logE(user.toString()); - assertTrue("the Existing NowplusUser might be duplicated to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_UPDATED); + assertTrue("the Existing NowplusUser might be duplicated to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_UPDATED); //8 int count = PresenceTable.setAllUsersOffline(mTestDatabase.getWritableDatabase()); assertTrue("The count of deleted rows is not the expected one:"+count, count == 6); Log.i(LOG_TAG, "***** testSetAllUsersOffline() test SUCCEEDED*****"); } public void testSetAllUsersOfflineExceptForMe() { Log.i(LOG_TAG, "***** testSetAllUsersOfflineExceptForMe() *****"); PresenceTable.create(mTestDatabase.getWritableDatabase()); Log.i(LOG_TAG, "***** testSetAllUsersOfflineExceptForMe(): table created*****"); - assertTrue("The method adds a null user and returns true", PresenceTable.updateUser(null, mTestDatabase.getWritableDatabase())==PresenceTable.USER_NOTADDED); + assertTrue("The method adds a null user and returns true", PresenceTable.updateUser(null, null, mTestDatabase.getWritableDatabase())==PresenceTable.USER_NOTADDED); Log.i(LOG_TAG, "***** testUpdateUser: NULL test SUCCEEDED *****"); // 1 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("google::[email protected]", status); user.setLocalContactId(12L); - assertTrue("the user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_ADDED); + assertTrue("the user was not added to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_ADDED); LogUtils.logE("User1:"+user.toString()); user = null; //4 user = new User("12345678", status); user.setLocalContactId(13L); - assertTrue("the NowplusUser user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase())== PresenceTable.USER_ADDED); + assertTrue("the NowplusUser user was not added to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase())== PresenceTable.USER_ADDED); // user = null; //8 // status.put("pc", "offline"); // user = new User("12345678", status); user.setLocalContactId(13L); LogUtils.logE("User2:"+user.toString()); LogUtils.logE(user.toString()); - assertTrue("the Existing NowplusUser might be duplicated to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_UPDATED); + assertTrue("the Existing NowplusUser might be duplicated to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_UPDATED); //8 int count = PresenceTable.setAllUsersOfflineExceptForMe(12L, mTestDatabase.getWritableDatabase()); assertTrue("The count of deleted rows is not the expected one:"+count, count == 3); Log.i(LOG_TAG, "***** testSetAllUsersOfflineExceptForMe() test SUCCEEDED*****"); } }
360/360-Engine-for-Android
2fbf8a375f83148805640762b9ecdc0af30fb74e
- adapted directory for build server
diff --git a/build_property_files/buildserver.properties b/build_property_files/buildserver.properties index 20d27de..4b0e28f 100644 --- a/build_property_files/buildserver.properties +++ b/build_property_files/buildserver.properties @@ -1,11 +1,11 @@ # The directory that points to the Android SDK file on your machine sdk.dir=/opt/local/android # The directory that points to the XMLTask (ant task) on your machine xml.task.dir=/opt/local/android/xmltask.jar # The default emulator AVD to use for unit testing default.avd=2_1_device_HVGA # Name of the directory of the UI Project TODO move to generic properties file -ui.project.name=360-UI-for-Android \ No newline at end of file +ui.project.name=Android_Trunk_Subtask_Checkout_UI
360/360-Engine-for-Android
0ad88445f4a1729cff10f4ce64f78ce2c75d1145
no comment
diff --git a/tests/build.xml b/tests/build.xml index c73565d..87ceb78 100644 --- a/tests/build.xml +++ b/tests/build.xml @@ -1,696 +1,696 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <project name="tests"> <property environment="env"/> <!-- The build.properties file can be created by you and is never touched by the 'android' tool. This is the place to change some of the default property values used by the Ant rules. Here are some properties you may want to change/update: application.package the name of your application package as defined in the manifest. Used by the 'uninstall' rule. source.dir the name of the source directory. Default is 'src'. out.dir the name of the output directory. Default is 'bin'. Properties related to the SDK location or the project target should be updated using the 'android' tool with the 'update' action. This file is an integral part of the build system for your application and should be checked in in Version Control Systems. --> <property file="build.properties" /> <!-- The default.properties file is created and updated by the 'android' tool, as well as ADT. This file is an integral part of the build system for your application and should be checked in in Version Control Systems. --> <property file="default.properties" /> <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it already on your system, please do so. After setting it, create a new properties file in build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties to it. --> <property file="../build_property_files/${env.USERNAME_360}.properties" /> <echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the XMLTask is found in ${xml.task.dir}...</echo> <!-- Custom Android task to deal with the project target, and import the proper rules. This requires ant 1.6.0 or above. --> <path id="android.antlibs"> <pathelement path="${sdk.dir}/tools/lib/anttasks.jar" /> <pathelement path="${sdk.dir}/tools/lib/sdklib.jar" /> <pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" /> <pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" /> <pathelement path="${sdk.dir}/tools/lib/jarutils.jar" /> </path> <taskdef name="setup" classname="com.android.ant.SetupTask" classpathref="android.antlibs" /> <!-- Execute the Android Setup task that will setup some properties specific to the target, and import the build rules files. The rules file is imported from <SDK>/platforms/<target_platform>/templates/android_rules.xml To customize some build steps for your project: - copy the content of the main node <project> from android_rules.xml - paste it in this build.xml below the <setup /> task. - disable the import by changing the setup task below to <setup import="false" /> This will ensure that the properties are setup correctly but that your customized build steps are used. --> <setup import="false" /> <!-- EMMA Coverage interface for build script --> <target name="emma-coverage-interface"> <echo>EMMA Coverage interface for build script.</echo> <ant target="coverage" /> </target> <!-- JUunit interface for build script --> <target name="run-tests-interface"> <echo>JUunit interface for build script.</echo> <ant target="run-tests" /> </target> <!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############ This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be run inside the build script without path issues. --> <!-- This rules file is meant to be imported by the custom Ant task: com.android.ant.AndroidInitTask The following properties are put in place by the importing task: android.jar, android.aidl, aapt, aidl, and dx Additionnaly, the task sets up the following classpath reference: android.target.classpath This is used by the compiler task as the boot classpath. --> <!-- Custom tasks --> <taskdef name="aaptexec" classname="com.android.ant.AaptExecLoopTask" classpathref="android.antlibs" /> <taskdef name="apkbuilder" classname="com.android.ant.ApkBuilderTask" classpathref="android.antlibs" /> <taskdef name="xpath" classname="com.android.ant.XPathTask" classpathref="android.antlibs" /> <!-- Properties --> <!-- Tells adb which device to target. You can change this from the command line by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for the emulator. --> <property name="adb.device.arg" value="" /> <property name="android.tools.dir" location="${sdk.dir}/tools" /> <!-- Name of the application package extracted from manifest file --> <xpath input="AndroidManifest.xml" expression="/manifest/@package" output="manifest.package" /> <!-- Input directories --> <property name="source.dir" value="src" /> <property name="source.absolute.dir" location="${source.dir}" /> <property name="gen.dir" value="gen" /> <property name="gen.absolute.dir" location="${gen.dir}" /> <property name="resource.dir" value="res" /> <property name="resource.absolute.dir" location="${resource.dir}" /> <property name="asset.dir" value="assets" /> <property name="asset.absolute.dir" location="${asset.dir}" /> <!-- Directory for the third party java libraries --> <property name="external.libs.dir" value="libs" /> <property name="external.libs.absolute.dir" location="${external.libs.dir}" /> <!-- Directory for the native libraries --> <property name="native.libs.dir" value="libs" /> <property name="native.libs.absolute.dir" location="${native.libs.dir}" /> <!-- Output directories --> <property name="out.dir" value="bin" /> <property name="out.absolute.dir" location="${out.dir}" /> <property name="out.classes.dir" value="${out.absolute.dir}/classes" /> <property name="out.classes.absolute.dir" location="${out.classes.dir}" /> <!-- Intermediate files --> <property name="dex.file.name" value="classes.dex" /> <property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" /> <!-- The final package file to generate --> <property name="out.debug.unaligned.package" location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" /> <property name="out.debug.package" location="${out.absolute.dir}/${ant.project.name}-debug.apk" /> <property name="out.unsigned.package" location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" /> <property name="out.unaligned.package" location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" /> <property name="out.release.package" location="${out.absolute.dir}/${ant.project.name}-release.apk" /> <!-- Verbosity --> <property name="verbose" value="false" /> <!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false' The property 'verbosity' is not user configurable and depends exclusively on 'verbose' value.--> <condition property="verbosity" value="verbose" else="quiet"> <istrue value="${verbose}" /> </condition> <!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose' --> <condition property="v.option" value="-v" else=""> <istrue value="${verbose}" /> </condition> <!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' --> <condition property="verbose.option" value="--verbose" else=""> <istrue value="${verbose}" /> </condition> <!-- Tools --> <condition property="exe" value=".exe" else=""><os family="windows" /></condition> <property name="adb" location="${android.tools.dir}/adb${exe}" /> <property name="zipalign" location="${android.tools.dir}/zipalign${exe}" /> <!-- Emma configuration --> <property name="emma.dir" value="${sdk.dir}/tools/lib" /> <path id="emma.lib"> <pathelement location="${emma.dir}/emma.jar" /> <pathelement location="${emma.dir}/emma_ant.jar" /> </path> <taskdef resource="emma_ant.properties" classpathref="emma.lib" /> <!-- End of emma configuration --> <!-- Macros --> <!-- Configurable macro, which allows to pass as parameters output directory, output dex filename and external libraries to dex (optional) --> <macrodef name="dex-helper"> <element name="external-libs" optional="yes" /> <element name="extra-parameters" optional="yes" /> <sequential> <echo>Converting compiled files and external libraries into ${intermediate.dex.file}... </echo> <apply executable="${dx}" failonerror="true" parallel="true"> <arg value="--dex" /> <arg value="--output=${intermediate.dex.file}" /> <extra-parameters /> <arg line="${verbose.option}" /> <arg path="${out.classes.absolute.dir}" /> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> <external-libs /> </apply> </sequential> </macrodef> <!-- This is macro that enable passing variable list of external jar files to ApkBuilder Example of use: <package-helper> <extra-jars> <jarfolder path="my_jars" /> <jarfile path="foo/bar.jar" /> <jarfolder path="your_jars" /> </extra-jars> </package-helper> --> <macrodef name="package-helper"> <attribute name="sign.package" /> <element name="extra-jars" optional="yes" /> <sequential> <apkbuilder outfolder="${out.absolute.dir}" basename="${ant.project.name}" signed="@{sign.package}" verbose="${verbose}"> <file path="${intermediate.dex.file}" /> <sourcefolder path="${source.absolute.dir}" /> <nativefolder path="${native.libs.absolute.dir}" /> <jarfolder path="${external.libs.absolute.dir}" /> <extra-jars/> </apkbuilder> </sequential> </macrodef> <!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets debug, -debug-with-emma and release.--> <macrodef name="zipalign-helper"> <attribute name="in.package" /> <attribute name="out.package" /> <sequential> <echo>Running zip align on final apk...</echo> <exec executable="${zipalign}" failonerror="true"> <arg line="${v.option}" /> <arg value="-f" /> <arg value="4" /> <arg path="@{in.package}" /> <arg path="@{out.package}" /> </exec> </sequential> </macrodef> <!-- This is macro used only for sharing code among two targets, -install and -install-with-emma which do exactly the same but differ in dependencies --> <macrodef name="install-helper"> <sequential> <echo>Installing ${out.debug.package} onto default emulator or device...</echo> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="install" /> <arg value="-r" /> <arg path="${out.debug.package}" /> </exec> </sequential> </macrodef> <!-- Rules --> <!-- Creates the output directories if they don't exist yet. --> <target name="-dirs"> <echo>Creating output directories if needed...</echo> <mkdir dir="${resource.absolute.dir}" /> <mkdir dir="${external.libs.absolute.dir}" /> <mkdir dir="${gen.absolute.dir}" /> <mkdir dir="${out.absolute.dir}" /> <mkdir dir="${out.classes.absolute.dir}" /> </target> <!-- Generates the R.java file for this project's resources. --> <target name="-resource-src" depends="-dirs"> <echo>Generating R.java / Manifest.java from the resources...</echo> <exec executable="${aapt}" failonerror="true"> <arg value="package" /> <arg line="${v.option}" /> <arg value="-m" /> <arg value="-J" /> <arg path="${gen.absolute.dir}" /> <arg value="-M" /> <arg path="AndroidManifest.xml" /> <arg value="-S" /> <arg path="${resource.absolute.dir}" /> <arg value="-I" /> <arg path="${android.jar}" /> </exec> </target> <!-- Generates java classes from .aidl files. --> <target name="-aidl" depends="-dirs"> <echo>Compiling aidl files into Java classes...</echo> <apply executable="${aidl}" failonerror="true"> <arg value="-p${android.aidl}" /> <arg value="-I${source.absolute.dir}" /> <arg value="-o${gen.absolute.dir}" /> <fileset dir="${source.absolute.dir}"> <include name="**/*.aidl" /> </fileset> </apply> </target> <!-- Compiles this project's .java files into .class files. --> <target name="compile" depends="-resource-src, -aidl" description="Compiles project's .java files into .class files"> <!-- If android rules are used for a test project, its classpath should include tested project's location --> <condition property="extensible.classpath" value="${tested.project.absolute.dir}/bin/classes" else="."> <isset property="tested.project.absolute.dir" /> </condition> <echo>extensible.classpath: ${extensible.classpath}</echo> <javac encoding="ascii" target="1.5" debug="true" extdirs="" destdir="${out.classes.absolute.dir}" bootclasspathref="android.target.classpath" verbose="${verbose}" classpath="${extensible.classpath}"> <src path="${source.absolute.dir}" /> - <src path="../../${ui.project}/${source.dir}" /> + <src path="../../${ui.project.name}/${source.dir}" /> <src path="${gen.absolute.dir}" /> <classpath> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> </classpath> </javac> </target> <!-- Converts this project's .class files into .dex files --> <target name="-dex" depends="compile"> <dex-helper /> </target> <!-- Puts the project's resources into the output package file This actually can create multiple resource package in case Some custom apk with specific configuration have been declared in default.properties. --> <target name="-package-resources"> <echo>Packaging resources</echo> <aaptexec executable="${aapt}" command="package" manifest="AndroidManifest.xml" resources="${resource.absolute.dir}" assets="${asset.absolute.dir}" androidjar="${android.jar}" outfolder="${out.absolute.dir}" basename="${ant.project.name}" /> </target> <!-- Packages the application and sign it with a debug key. --> <target name="-package-debug-sign" depends="-dex, -package-resources"> <package-helper sign.package="true" /> </target> <!-- Packages the application without signing it. --> <target name="-package-no-sign" depends="-dex, -package-resources"> <package-helper sign.package="false" /> </target> <target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again"> <subant target="compile"> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <!-- Builds debug output package, provided all the necessary files are already dexed --> <target name="debug" depends="-compile-tested-if-test, -package-debug-sign" description="Builds the application and signs it with a debug key."> <zipalign-helper in.package="${out.debug.unaligned.package}" out.package="${out.debug.package}" /> <echo>Debug Package: ${out.debug.package}</echo> </target> <target name="-release-check"> <condition property="release.sign"> <and> <isset property="key.store" /> <isset property="key.alias" /> </and> </condition> </target> <target name="-release-nosign" depends="-release-check" unless="release.sign"> <echo>No key.store and key.alias properties found in build.properties.</echo> <echo>Please sign ${out.unsigned.package} manually</echo> <echo>and run zipalign from the Android SDK tools.</echo> </target> <target name="release" depends="-package-no-sign, -release-nosign" if="release.sign" description="Builds the application. The generated apk file must be signed before it is published."> <!-- Gets passwords --> <input message="Please enter keystore password (store:${key.store}):" addproperty="key.store.password" /> <input message="Please enter password for alias '${key.alias}':" addproperty="key.alias.password" /> <!-- Signs the APK --> <echo>Signing final apk...</echo> <signjar jar="${out.unsigned.package}" signedjar="${out.unaligned.package}" keystore="${key.store}" storepass="${key.store.password}" alias="${key.alias}" keypass="${key.alias.password}" verbose="${verbose}" /> <!-- Zip aligns the APK --> <zipalign-helper in.package="${out.unaligned.package}" out.package="${out.release.package}" /> <echo>Release Package: ${out.release.package}</echo> </target> <target name="install" depends="debug" description="Installs/reinstalls the debug package onto a running emulator or device. If the application was previously installed, the signatures must match." > <install-helper /> </target> <target name="-uninstall-check"> <condition property="uninstall.run"> <isset property="manifest.package" /> </condition> </target> <target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run"> <echo>Unable to run 'ant uninstall', manifest.package property is not defined. </echo> </target> <!-- Uninstalls the package from the default emulator/device --> <target name="uninstall" depends="-uninstall-error" if="uninstall.run" description="Uninstalls the application from a running emulator or device."> <echo>Uninstalling ${manifest.package} from the default emulator or device...</echo> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="uninstall" /> <arg value="${manifest.package}" /> </exec> </target> <target name="clean" description="Removes output files created by other targets."> <delete dir="${out.absolute.dir}" verbose="${verbose}" /> <delete dir="${gen.absolute.dir}" verbose="${verbose}" /> </target> <!-- Targets for code-coverage measurement purposes, invoked from external file --> <!-- Emma-instruments tested project classes (compiles the tested project if necessary) and writes instrumented classes to ${instrumentation.absolute.dir}/classes --> <target name="-emma-instrument" depends="compile"> <echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo> <!-- It only instruments class files, not any external libs --> <emma enabled="true"> <instr verbosity="${verbosity}" mode="overwrite" instrpath="${out.absolute.dir}/classes" outdir="${out.absolute.dir}/classes"> </instr> <!-- TODO: exclusion filters on R*.class and allowing custom exclusion from user defined file --> </emma> </target> <target name="-dex-instrumented" depends="-emma-instrument"> <dex-helper> <extra-parameters> <arg value="--no-locals" /> </extra-parameters> <external-libs> <fileset file="${emma.dir}/emma_device.jar" /> </external-libs> </dex-helper> </target> <!-- Invoked from external files for code coverage purposes --> <target name="-package-with-emma" depends="-dex-instrumented, -package-resources"> <package-helper sign.package="true"> <extra-jars> <!-- Injected from external file --> <jarfile path="${emma.dir}/emma_device.jar" /> </extra-jars> </package-helper> </target> <target name="-debug-with-emma" depends="-package-with-emma"> <zipalign-helper in.package="${out.debug.unaligned.package}" out.package="${out.debug.package}" /> </target> <target name="-install-with-emma" depends="-debug-with-emma"> <install-helper /> </target> <!-- End of targets for code-coverage measurement purposes --> <target name="help"> <!-- displays starts at col 13 |13 80| --> <echo>Android Ant Build. Available targets:</echo> <echo> help: Displays this help.</echo> <echo> clean: Removes output files created by other targets.</echo> <echo> compile: Compiles project's .java files into .class files.</echo> <echo> debug: Builds the application and signs it with a debug key.</echo> <echo> release: Builds the application. The generated apk file must be</echo> <echo> signed before it is published.</echo> <echo> install: Installs/reinstalls the debug package onto a running</echo> <echo> emulator or device.</echo> <echo> If the application was previously installed, the</echo> <echo> signatures must match.</echo> <echo> uninstall: Uninstalls the application from a running emulator or</echo> <echo> device.</echo> </target> <!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ --> <!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## --> <property name="tested.project.absolute.dir" location="${tested.project.dir}" /> <property name="junit.out.file" value="${tested.project.absolute.dir}\output\junit-result.txt" /> <property name="instrumentation.dir" value="instrumented" /> <property name="instrumentation.absolute.dir" location="${instrumentation.dir}" /> <property name="test.runner" value="android.test.InstrumentationTestRunner" /> <!-- Application package of the tested project extracted from its manifest file --> <xpath input="${tested.project.absolute.dir}/AndroidManifest.xml" expression="/manifest/@package" output="tested.manifest.package" /> <!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated project --> <property name="emma.dump.file" value="/data/data/${tested.manifest.package}/files/coverage.ec" /> <macrodef name="run-tests-helper"> <attribute name="emma.enabled" default="false" /> <element name="extra-instrument-args" optional="yes" /> <sequential> <echo>Running tests with output sent to ${junit.out.file}...</echo> <exec executable="${adb}" failonerror="true" output="${junit.out.file}"> <arg value="shell" /> <arg value="am" /> <arg value="instrument" /> <arg value="-w" /> <arg value="-r" /> <!-- XML output --> <arg value="-e" /> <arg value="coverage" /> <arg value="@{emma.enabled}" /> <extra-instrument-args /> <arg value="${manifest.package}/${test.runner}" /> </exec> <loadfile srcfile="${junit.out.file}" property="result"> <filterchain> <linecontains> <contains value="INSTRUMENTATION_CODE: -1"/> </linecontains> </filterchain> </loadfile> <loadfile srcfile="${junit.out.file}" property="result2"> <filterchain> <linecontains> <contains value="FAILURES"/> </linecontains> </filterchain> </loadfile> <echo>Result ${result} ${result2}</echo> <loadfile property="junit-out-file" srcFile="${junit.out.file}"/> <echo>Junit results...</echo> <echo>${junit-out-file}</echo> <fail unless="result">JUnit tests failed, please look at ${junit.out.file} for more information.</fail> <fail if="result2">JUnit tests failed, please look at ${junit.out.file} for more information.</fail> </sequential> </macrodef> <!-- Invoking this target sets the value of extensible.classpath, which is being added to javac classpath in target 'compile' (android_rules.xml) --> <target name="-set-coverage-classpath"> <property name="extensible.classpath" location="${instrumentation.absolute.dir}/classes" /> </target> <!-- Ensures that tested project is installed on the device before we run the tests. Used for ordinary tests, without coverage measurement --> <target name="-install-tested-project"> <property name="do.not.compile.again" value="true" /> <subant target="install"> <property name="sdk.dir" location="${sdk.dir}"/> <property name="sdk-location" location="${sdk-location}"/> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <target name="run-tests" depends="-install-tested-project, install" description="Runs tests from the package defined in test.package property"> <run-tests-helper /> </target> <target name="-install-instrumented"> <property name="do.not.compile.again" value="true" /> <subant target="-install-with-emma"> <property name="out.absolute.dir" value="${instrumentation.absolute.dir}" /> <property name="sdk.dir" location="${sdk.dir}"/> <property name="sdk-location" location="${sdk-location}"/> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <target name="coverage" depends="-set-coverage-classpath, -install-instrumented, install" description="Runs the tests against the instrumented code and generates code coverage report"> <run-tests-helper emma.enabled="true"> <extra-instrument-args> <arg value="-e" /> <arg value="coverageFile" /> <arg value="${emma.dump.file}" /> </extra-instrument-args> </run-tests-helper> <echo>Downloading coverage file into project directory...</echo> <exec executable="${adb}" failonerror="true"> <arg value="pull" /> <arg value="${emma.dump.file}" /> <arg value="coverage.ec" /> </exec> <echo>#################### INSERTED CODE #####################</echo> <move file="${tested.project.absolute.dir}/coverage.em" tofile="${tested.project.absolute.dir}/tests/coverage.em"/> <echo>#################### INSERTED CODE #####################</echo> <echo>Extracting coverage report...</echo> <emma> <report sourcepath="${tested.project.absolute.dir}/${source.dir}" verbosity="${verbosity}"> <!-- TODO: report.dir or something like should be introduced if necessary --> <infileset dir="."> <include name="coverage.ec" /> <include name="coverage.em" /> </infileset> <!-- TODO: reports in other, indicated by user formats --> <html outfile="coverage.html" /> </report> </emma> <echo>Cleaning up temporary files...</echo> <delete dir="${instrumentation.absolute.dir}" /> <delete file="coverage.ec" /> <delete file="coverage.em" /> <echo>Saving the report file in ${basedir}/coverage/coverage.html</echo> </target> <!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## --> </project> \ No newline at end of file
360/360-Engine-for-Android
c7daca83a637de6e3757c024fa8ebcbabfe72c6b
- once more the build.xml
diff --git a/tests/build.xml b/tests/build.xml index e9dcd87..c73565d 100644 --- a/tests/build.xml +++ b/tests/build.xml @@ -1,695 +1,696 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <project name="tests"> <property environment="env"/> <!-- The build.properties file can be created by you and is never touched by the 'android' tool. This is the place to change some of the default property values used by the Ant rules. Here are some properties you may want to change/update: application.package the name of your application package as defined in the manifest. Used by the 'uninstall' rule. source.dir the name of the source directory. Default is 'src'. out.dir the name of the output directory. Default is 'bin'. Properties related to the SDK location or the project target should be updated using the 'android' tool with the 'update' action. This file is an integral part of the build system for your application and should be checked in in Version Control Systems. --> <property file="build.properties" /> <!-- The default.properties file is created and updated by the 'android' tool, as well as ADT. This file is an integral part of the build system for your application and should be checked in in Version Control Systems. --> <property file="default.properties" /> <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it already on your system, please do so. After setting it, create a new properties file in build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties to it. --> <property file="../build_property_files/${env.USERNAME_360}.properties" /> <echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the XMLTask is found in ${xml.task.dir}...</echo> <!-- Custom Android task to deal with the project target, and import the proper rules. This requires ant 1.6.0 or above. --> <path id="android.antlibs"> <pathelement path="${sdk.dir}/tools/lib/anttasks.jar" /> <pathelement path="${sdk.dir}/tools/lib/sdklib.jar" /> <pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" /> <pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" /> <pathelement path="${sdk.dir}/tools/lib/jarutils.jar" /> </path> <taskdef name="setup" classname="com.android.ant.SetupTask" classpathref="android.antlibs" /> <!-- Execute the Android Setup task that will setup some properties specific to the target, and import the build rules files. The rules file is imported from <SDK>/platforms/<target_platform>/templates/android_rules.xml To customize some build steps for your project: - copy the content of the main node <project> from android_rules.xml - paste it in this build.xml below the <setup /> task. - disable the import by changing the setup task below to <setup import="false" /> This will ensure that the properties are setup correctly but that your customized build steps are used. --> <setup import="false" /> <!-- EMMA Coverage interface for build script --> <target name="emma-coverage-interface"> <echo>EMMA Coverage interface for build script.</echo> <ant target="coverage" /> </target> <!-- JUunit interface for build script --> <target name="run-tests-interface"> <echo>JUunit interface for build script.</echo> <ant target="run-tests" /> </target> <!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############ This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be run inside the build script without path issues. --> <!-- This rules file is meant to be imported by the custom Ant task: com.android.ant.AndroidInitTask The following properties are put in place by the importing task: android.jar, android.aidl, aapt, aidl, and dx Additionnaly, the task sets up the following classpath reference: android.target.classpath This is used by the compiler task as the boot classpath. --> <!-- Custom tasks --> <taskdef name="aaptexec" classname="com.android.ant.AaptExecLoopTask" classpathref="android.antlibs" /> <taskdef name="apkbuilder" classname="com.android.ant.ApkBuilderTask" classpathref="android.antlibs" /> <taskdef name="xpath" classname="com.android.ant.XPathTask" classpathref="android.antlibs" /> <!-- Properties --> <!-- Tells adb which device to target. You can change this from the command line by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for the emulator. --> <property name="adb.device.arg" value="" /> <property name="android.tools.dir" location="${sdk.dir}/tools" /> <!-- Name of the application package extracted from manifest file --> <xpath input="AndroidManifest.xml" expression="/manifest/@package" output="manifest.package" /> <!-- Input directories --> <property name="source.dir" value="src" /> <property name="source.absolute.dir" location="${source.dir}" /> <property name="gen.dir" value="gen" /> <property name="gen.absolute.dir" location="${gen.dir}" /> <property name="resource.dir" value="res" /> <property name="resource.absolute.dir" location="${resource.dir}" /> <property name="asset.dir" value="assets" /> <property name="asset.absolute.dir" location="${asset.dir}" /> <!-- Directory for the third party java libraries --> <property name="external.libs.dir" value="libs" /> <property name="external.libs.absolute.dir" location="${external.libs.dir}" /> <!-- Directory for the native libraries --> <property name="native.libs.dir" value="libs" /> <property name="native.libs.absolute.dir" location="${native.libs.dir}" /> <!-- Output directories --> <property name="out.dir" value="bin" /> <property name="out.absolute.dir" location="${out.dir}" /> <property name="out.classes.dir" value="${out.absolute.dir}/classes" /> <property name="out.classes.absolute.dir" location="${out.classes.dir}" /> <!-- Intermediate files --> <property name="dex.file.name" value="classes.dex" /> <property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" /> <!-- The final package file to generate --> <property name="out.debug.unaligned.package" location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" /> <property name="out.debug.package" location="${out.absolute.dir}/${ant.project.name}-debug.apk" /> <property name="out.unsigned.package" location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" /> <property name="out.unaligned.package" location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" /> <property name="out.release.package" location="${out.absolute.dir}/${ant.project.name}-release.apk" /> <!-- Verbosity --> <property name="verbose" value="false" /> <!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false' The property 'verbosity' is not user configurable and depends exclusively on 'verbose' value.--> <condition property="verbosity" value="verbose" else="quiet"> <istrue value="${verbose}" /> </condition> <!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose' --> <condition property="v.option" value="-v" else=""> <istrue value="${verbose}" /> </condition> <!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' --> <condition property="verbose.option" value="--verbose" else=""> <istrue value="${verbose}" /> </condition> <!-- Tools --> <condition property="exe" value=".exe" else=""><os family="windows" /></condition> <property name="adb" location="${android.tools.dir}/adb${exe}" /> <property name="zipalign" location="${android.tools.dir}/zipalign${exe}" /> <!-- Emma configuration --> <property name="emma.dir" value="${sdk.dir}/tools/lib" /> <path id="emma.lib"> <pathelement location="${emma.dir}/emma.jar" /> <pathelement location="${emma.dir}/emma_ant.jar" /> </path> <taskdef resource="emma_ant.properties" classpathref="emma.lib" /> <!-- End of emma configuration --> <!-- Macros --> <!-- Configurable macro, which allows to pass as parameters output directory, output dex filename and external libraries to dex (optional) --> <macrodef name="dex-helper"> <element name="external-libs" optional="yes" /> <element name="extra-parameters" optional="yes" /> <sequential> <echo>Converting compiled files and external libraries into ${intermediate.dex.file}... </echo> <apply executable="${dx}" failonerror="true" parallel="true"> <arg value="--dex" /> <arg value="--output=${intermediate.dex.file}" /> <extra-parameters /> <arg line="${verbose.option}" /> <arg path="${out.classes.absolute.dir}" /> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> <external-libs /> </apply> </sequential> </macrodef> <!-- This is macro that enable passing variable list of external jar files to ApkBuilder Example of use: <package-helper> <extra-jars> <jarfolder path="my_jars" /> <jarfile path="foo/bar.jar" /> <jarfolder path="your_jars" /> </extra-jars> </package-helper> --> <macrodef name="package-helper"> <attribute name="sign.package" /> <element name="extra-jars" optional="yes" /> <sequential> <apkbuilder outfolder="${out.absolute.dir}" basename="${ant.project.name}" signed="@{sign.package}" verbose="${verbose}"> <file path="${intermediate.dex.file}" /> <sourcefolder path="${source.absolute.dir}" /> <nativefolder path="${native.libs.absolute.dir}" /> <jarfolder path="${external.libs.absolute.dir}" /> <extra-jars/> </apkbuilder> </sequential> </macrodef> <!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets debug, -debug-with-emma and release.--> <macrodef name="zipalign-helper"> <attribute name="in.package" /> <attribute name="out.package" /> <sequential> <echo>Running zip align on final apk...</echo> <exec executable="${zipalign}" failonerror="true"> <arg line="${v.option}" /> <arg value="-f" /> <arg value="4" /> <arg path="@{in.package}" /> <arg path="@{out.package}" /> </exec> </sequential> </macrodef> <!-- This is macro used only for sharing code among two targets, -install and -install-with-emma which do exactly the same but differ in dependencies --> <macrodef name="install-helper"> <sequential> <echo>Installing ${out.debug.package} onto default emulator or device...</echo> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="install" /> <arg value="-r" /> <arg path="${out.debug.package}" /> </exec> </sequential> </macrodef> <!-- Rules --> <!-- Creates the output directories if they don't exist yet. --> <target name="-dirs"> <echo>Creating output directories if needed...</echo> <mkdir dir="${resource.absolute.dir}" /> <mkdir dir="${external.libs.absolute.dir}" /> <mkdir dir="${gen.absolute.dir}" /> <mkdir dir="${out.absolute.dir}" /> <mkdir dir="${out.classes.absolute.dir}" /> </target> <!-- Generates the R.java file for this project's resources. --> <target name="-resource-src" depends="-dirs"> <echo>Generating R.java / Manifest.java from the resources...</echo> <exec executable="${aapt}" failonerror="true"> <arg value="package" /> <arg line="${v.option}" /> <arg value="-m" /> <arg value="-J" /> <arg path="${gen.absolute.dir}" /> <arg value="-M" /> <arg path="AndroidManifest.xml" /> <arg value="-S" /> <arg path="${resource.absolute.dir}" /> <arg value="-I" /> <arg path="${android.jar}" /> </exec> </target> <!-- Generates java classes from .aidl files. --> <target name="-aidl" depends="-dirs"> <echo>Compiling aidl files into Java classes...</echo> <apply executable="${aidl}" failonerror="true"> <arg value="-p${android.aidl}" /> <arg value="-I${source.absolute.dir}" /> <arg value="-o${gen.absolute.dir}" /> <fileset dir="${source.absolute.dir}"> <include name="**/*.aidl" /> </fileset> </apply> </target> <!-- Compiles this project's .java files into .class files. --> <target name="compile" depends="-resource-src, -aidl" description="Compiles project's .java files into .class files"> <!-- If android rules are used for a test project, its classpath should include tested project's location --> <condition property="extensible.classpath" value="${tested.project.absolute.dir}/bin/classes" else="."> <isset property="tested.project.absolute.dir" /> </condition> <echo>extensible.classpath: ${extensible.classpath}</echo> <javac encoding="ascii" target="1.5" debug="true" extdirs="" destdir="${out.classes.absolute.dir}" bootclasspathref="android.target.classpath" verbose="${verbose}" classpath="${extensible.classpath}"> <src path="${source.absolute.dir}" /> + <src path="../../${ui.project}/${source.dir}" /> <src path="${gen.absolute.dir}" /> <classpath> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> </classpath> </javac> </target> <!-- Converts this project's .class files into .dex files --> <target name="-dex" depends="compile"> <dex-helper /> </target> <!-- Puts the project's resources into the output package file This actually can create multiple resource package in case Some custom apk with specific configuration have been declared in default.properties. --> <target name="-package-resources"> <echo>Packaging resources</echo> <aaptexec executable="${aapt}" command="package" manifest="AndroidManifest.xml" resources="${resource.absolute.dir}" assets="${asset.absolute.dir}" androidjar="${android.jar}" outfolder="${out.absolute.dir}" basename="${ant.project.name}" /> </target> <!-- Packages the application and sign it with a debug key. --> <target name="-package-debug-sign" depends="-dex, -package-resources"> <package-helper sign.package="true" /> </target> <!-- Packages the application without signing it. --> <target name="-package-no-sign" depends="-dex, -package-resources"> <package-helper sign.package="false" /> </target> <target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again"> <subant target="compile"> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <!-- Builds debug output package, provided all the necessary files are already dexed --> <target name="debug" depends="-compile-tested-if-test, -package-debug-sign" description="Builds the application and signs it with a debug key."> <zipalign-helper in.package="${out.debug.unaligned.package}" out.package="${out.debug.package}" /> <echo>Debug Package: ${out.debug.package}</echo> </target> <target name="-release-check"> <condition property="release.sign"> <and> <isset property="key.store" /> <isset property="key.alias" /> </and> </condition> </target> <target name="-release-nosign" depends="-release-check" unless="release.sign"> <echo>No key.store and key.alias properties found in build.properties.</echo> <echo>Please sign ${out.unsigned.package} manually</echo> <echo>and run zipalign from the Android SDK tools.</echo> </target> <target name="release" depends="-package-no-sign, -release-nosign" if="release.sign" description="Builds the application. The generated apk file must be signed before it is published."> <!-- Gets passwords --> <input message="Please enter keystore password (store:${key.store}):" addproperty="key.store.password" /> <input message="Please enter password for alias '${key.alias}':" addproperty="key.alias.password" /> <!-- Signs the APK --> <echo>Signing final apk...</echo> <signjar jar="${out.unsigned.package}" signedjar="${out.unaligned.package}" keystore="${key.store}" storepass="${key.store.password}" alias="${key.alias}" keypass="${key.alias.password}" verbose="${verbose}" /> <!-- Zip aligns the APK --> <zipalign-helper in.package="${out.unaligned.package}" out.package="${out.release.package}" /> <echo>Release Package: ${out.release.package}</echo> </target> <target name="install" depends="debug" description="Installs/reinstalls the debug package onto a running emulator or device. If the application was previously installed, the signatures must match." > <install-helper /> </target> <target name="-uninstall-check"> <condition property="uninstall.run"> <isset property="manifest.package" /> </condition> </target> <target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run"> <echo>Unable to run 'ant uninstall', manifest.package property is not defined. </echo> </target> <!-- Uninstalls the package from the default emulator/device --> <target name="uninstall" depends="-uninstall-error" if="uninstall.run" description="Uninstalls the application from a running emulator or device."> <echo>Uninstalling ${manifest.package} from the default emulator or device...</echo> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="uninstall" /> <arg value="${manifest.package}" /> </exec> </target> <target name="clean" description="Removes output files created by other targets."> <delete dir="${out.absolute.dir}" verbose="${verbose}" /> <delete dir="${gen.absolute.dir}" verbose="${verbose}" /> </target> <!-- Targets for code-coverage measurement purposes, invoked from external file --> <!-- Emma-instruments tested project classes (compiles the tested project if necessary) and writes instrumented classes to ${instrumentation.absolute.dir}/classes --> <target name="-emma-instrument" depends="compile"> <echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo> <!-- It only instruments class files, not any external libs --> <emma enabled="true"> <instr verbosity="${verbosity}" mode="overwrite" instrpath="${out.absolute.dir}/classes" outdir="${out.absolute.dir}/classes"> </instr> <!-- TODO: exclusion filters on R*.class and allowing custom exclusion from user defined file --> </emma> </target> <target name="-dex-instrumented" depends="-emma-instrument"> <dex-helper> <extra-parameters> <arg value="--no-locals" /> </extra-parameters> <external-libs> <fileset file="${emma.dir}/emma_device.jar" /> </external-libs> </dex-helper> </target> <!-- Invoked from external files for code coverage purposes --> <target name="-package-with-emma" depends="-dex-instrumented, -package-resources"> <package-helper sign.package="true"> <extra-jars> <!-- Injected from external file --> <jarfile path="${emma.dir}/emma_device.jar" /> </extra-jars> </package-helper> </target> <target name="-debug-with-emma" depends="-package-with-emma"> <zipalign-helper in.package="${out.debug.unaligned.package}" out.package="${out.debug.package}" /> </target> <target name="-install-with-emma" depends="-debug-with-emma"> <install-helper /> </target> <!-- End of targets for code-coverage measurement purposes --> <target name="help"> <!-- displays starts at col 13 |13 80| --> <echo>Android Ant Build. Available targets:</echo> <echo> help: Displays this help.</echo> <echo> clean: Removes output files created by other targets.</echo> <echo> compile: Compiles project's .java files into .class files.</echo> <echo> debug: Builds the application and signs it with a debug key.</echo> <echo> release: Builds the application. The generated apk file must be</echo> <echo> signed before it is published.</echo> <echo> install: Installs/reinstalls the debug package onto a running</echo> <echo> emulator or device.</echo> <echo> If the application was previously installed, the</echo> <echo> signatures must match.</echo> <echo> uninstall: Uninstalls the application from a running emulator or</echo> <echo> device.</echo> </target> <!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ --> <!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## --> <property name="tested.project.absolute.dir" location="${tested.project.dir}" /> <property name="junit.out.file" value="${tested.project.absolute.dir}\output\junit-result.txt" /> <property name="instrumentation.dir" value="instrumented" /> <property name="instrumentation.absolute.dir" location="${instrumentation.dir}" /> <property name="test.runner" value="android.test.InstrumentationTestRunner" /> <!-- Application package of the tested project extracted from its manifest file --> <xpath input="${tested.project.absolute.dir}/AndroidManifest.xml" expression="/manifest/@package" output="tested.manifest.package" /> <!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated project --> <property name="emma.dump.file" value="/data/data/${tested.manifest.package}/files/coverage.ec" /> <macrodef name="run-tests-helper"> <attribute name="emma.enabled" default="false" /> <element name="extra-instrument-args" optional="yes" /> <sequential> <echo>Running tests with output sent to ${junit.out.file}...</echo> <exec executable="${adb}" failonerror="true" output="${junit.out.file}"> <arg value="shell" /> <arg value="am" /> <arg value="instrument" /> <arg value="-w" /> <arg value="-r" /> <!-- XML output --> <arg value="-e" /> <arg value="coverage" /> <arg value="@{emma.enabled}" /> <extra-instrument-args /> <arg value="${manifest.package}/${test.runner}" /> </exec> <loadfile srcfile="${junit.out.file}" property="result"> <filterchain> <linecontains> <contains value="INSTRUMENTATION_CODE: -1"/> </linecontains> </filterchain> </loadfile> <loadfile srcfile="${junit.out.file}" property="result2"> <filterchain> <linecontains> <contains value="FAILURES"/> </linecontains> </filterchain> </loadfile> <echo>Result ${result} ${result2}</echo> <loadfile property="junit-out-file" srcFile="${junit.out.file}"/> <echo>Junit results...</echo> <echo>${junit-out-file}</echo> <fail unless="result">JUnit tests failed, please look at ${junit.out.file} for more information.</fail> <fail if="result2">JUnit tests failed, please look at ${junit.out.file} for more information.</fail> </sequential> </macrodef> <!-- Invoking this target sets the value of extensible.classpath, which is being added to javac classpath in target 'compile' (android_rules.xml) --> <target name="-set-coverage-classpath"> <property name="extensible.classpath" location="${instrumentation.absolute.dir}/classes" /> </target> <!-- Ensures that tested project is installed on the device before we run the tests. Used for ordinary tests, without coverage measurement --> <target name="-install-tested-project"> <property name="do.not.compile.again" value="true" /> <subant target="install"> <property name="sdk.dir" location="${sdk.dir}"/> <property name="sdk-location" location="${sdk-location}"/> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <target name="run-tests" depends="-install-tested-project, install" description="Runs tests from the package defined in test.package property"> <run-tests-helper /> </target> <target name="-install-instrumented"> <property name="do.not.compile.again" value="true" /> <subant target="-install-with-emma"> <property name="out.absolute.dir" value="${instrumentation.absolute.dir}" /> <property name="sdk.dir" location="${sdk.dir}"/> <property name="sdk-location" location="${sdk-location}"/> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <target name="coverage" depends="-set-coverage-classpath, -install-instrumented, install" description="Runs the tests against the instrumented code and generates code coverage report"> <run-tests-helper emma.enabled="true"> <extra-instrument-args> <arg value="-e" /> <arg value="coverageFile" /> <arg value="${emma.dump.file}" /> </extra-instrument-args> </run-tests-helper> <echo>Downloading coverage file into project directory...</echo> <exec executable="${adb}" failonerror="true"> <arg value="pull" /> <arg value="${emma.dump.file}" /> <arg value="coverage.ec" /> </exec> <echo>#################### INSERTED CODE #####################</echo> <move file="${tested.project.absolute.dir}/coverage.em" tofile="${tested.project.absolute.dir}/tests/coverage.em"/> <echo>#################### INSERTED CODE #####################</echo> <echo>Extracting coverage report...</echo> <emma> <report sourcepath="${tested.project.absolute.dir}/${source.dir}" verbosity="${verbosity}"> <!-- TODO: report.dir or something like should be introduced if necessary --> <infileset dir="."> <include name="coverage.ec" /> <include name="coverage.em" /> </infileset> <!-- TODO: reports in other, indicated by user formats --> <html outfile="coverage.html" /> </report> </emma> <echo>Cleaning up temporary files...</echo> <delete dir="${instrumentation.absolute.dir}" /> <delete file="coverage.ec" /> <delete file="coverage.em" /> <echo>Saving the report file in ${basedir}/coverage/coverage.html</echo> </target> <!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## --> </project> \ No newline at end of file
360/360-Engine-for-Android
9cb714564ea14d429f756fbf17bdac49e5b05eaa
- altered build.xml one more time
diff --git a/tests/build.xml b/tests/build.xml index c160cbb..e9dcd87 100644 --- a/tests/build.xml +++ b/tests/build.xml @@ -1,701 +1,695 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <project name="tests"> - - <property environment="env"/> - - <!-- The local.properties file is created and updated by the 'android' tool. - It contains the path to the SDK. It should *NOT* be checked in in Version - Control Systems. --> - <!-- <property file="local.properties" /> Point to the SDK location manually --> + <property environment="env"/> <!-- The build.properties file can be created by you and is never touched by the 'android' tool. This is the place to change some of the default property values used by the Ant rules. Here are some properties you may want to change/update: application.package the name of your application package as defined in the manifest. Used by the 'uninstall' rule. source.dir the name of the source directory. Default is 'src'. out.dir the name of the output directory. Default is 'bin'. Properties related to the SDK location or the project target should be updated using the 'android' tool with the 'update' action. This file is an integral part of the build system for your application and should be checked in in Version Control Systems. --> <property file="build.properties" /> <!-- The default.properties file is created and updated by the 'android' tool, as well as ADT. This file is an integral part of the build system for your application and should be checked in in Version Control Systems. --> <property file="default.properties" /> - <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it - already on your system, please do so. After setting it, create a new properties file in - build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties - to it. --> - <property file="../build_property_files/${env.USERNAME_360}.properties" /> - <echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the - XMLTask is found in ${xml.task.dir}...</echo> + <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it + already on your system, please do so. After setting it, create a new properties file in + build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties + to it. --> + <property file="../build_property_files/${env.USERNAME_360}.properties" /> + <echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the + XMLTask is found in ${xml.task.dir}...</echo> <!-- Custom Android task to deal with the project target, and import the proper rules. This requires ant 1.6.0 or above. --> <path id="android.antlibs"> <pathelement path="${sdk.dir}/tools/lib/anttasks.jar" /> <pathelement path="${sdk.dir}/tools/lib/sdklib.jar" /> <pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" /> <pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" /> <pathelement path="${sdk.dir}/tools/lib/jarutils.jar" /> </path> <taskdef name="setup" classname="com.android.ant.SetupTask" classpathref="android.antlibs" /> <!-- Execute the Android Setup task that will setup some properties specific to the target, and import the build rules files. The rules file is imported from <SDK>/platforms/<target_platform>/templates/android_rules.xml To customize some build steps for your project: - copy the content of the main node <project> from android_rules.xml - paste it in this build.xml below the <setup /> task. - disable the import by changing the setup task below to <setup import="false" /> This will ensure that the properties are setup correctly but that your customized build steps are used. --> <setup import="false" /> <!-- EMMA Coverage interface for build script --> <target name="emma-coverage-interface"> <echo>EMMA Coverage interface for build script.</echo> <ant target="coverage" /> </target> <!-- JUunit interface for build script --> <target name="run-tests-interface"> <echo>JUunit interface for build script.</echo> <ant target="run-tests" /> </target> <!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############ This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be run inside the build script without path issues. --> <!-- This rules file is meant to be imported by the custom Ant task: com.android.ant.AndroidInitTask The following properties are put in place by the importing task: android.jar, android.aidl, aapt, aidl, and dx Additionnaly, the task sets up the following classpath reference: android.target.classpath This is used by the compiler task as the boot classpath. --> <!-- Custom tasks --> <taskdef name="aaptexec" classname="com.android.ant.AaptExecLoopTask" classpathref="android.antlibs" /> <taskdef name="apkbuilder" classname="com.android.ant.ApkBuilderTask" classpathref="android.antlibs" /> <taskdef name="xpath" classname="com.android.ant.XPathTask" classpathref="android.antlibs" /> <!-- Properties --> <!-- Tells adb which device to target. You can change this from the command line by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for the emulator. --> <property name="adb.device.arg" value="" /> <property name="android.tools.dir" location="${sdk.dir}/tools" /> <!-- Name of the application package extracted from manifest file --> <xpath input="AndroidManifest.xml" expression="/manifest/@package" output="manifest.package" /> <!-- Input directories --> <property name="source.dir" value="src" /> <property name="source.absolute.dir" location="${source.dir}" /> <property name="gen.dir" value="gen" /> <property name="gen.absolute.dir" location="${gen.dir}" /> <property name="resource.dir" value="res" /> <property name="resource.absolute.dir" location="${resource.dir}" /> <property name="asset.dir" value="assets" /> <property name="asset.absolute.dir" location="${asset.dir}" /> <!-- Directory for the third party java libraries --> <property name="external.libs.dir" value="libs" /> <property name="external.libs.absolute.dir" location="${external.libs.dir}" /> <!-- Directory for the native libraries --> <property name="native.libs.dir" value="libs" /> <property name="native.libs.absolute.dir" location="${native.libs.dir}" /> <!-- Output directories --> <property name="out.dir" value="bin" /> <property name="out.absolute.dir" location="${out.dir}" /> <property name="out.classes.dir" value="${out.absolute.dir}/classes" /> <property name="out.classes.absolute.dir" location="${out.classes.dir}" /> <!-- Intermediate files --> <property name="dex.file.name" value="classes.dex" /> <property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" /> <!-- The final package file to generate --> <property name="out.debug.unaligned.package" location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" /> <property name="out.debug.package" location="${out.absolute.dir}/${ant.project.name}-debug.apk" /> <property name="out.unsigned.package" location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" /> <property name="out.unaligned.package" location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" /> <property name="out.release.package" location="${out.absolute.dir}/${ant.project.name}-release.apk" /> <!-- Verbosity --> <property name="verbose" value="false" /> <!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false' The property 'verbosity' is not user configurable and depends exclusively on 'verbose' value.--> <condition property="verbosity" value="verbose" else="quiet"> <istrue value="${verbose}" /> </condition> <!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose' --> <condition property="v.option" value="-v" else=""> <istrue value="${verbose}" /> </condition> <!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' --> <condition property="verbose.option" value="--verbose" else=""> <istrue value="${verbose}" /> </condition> <!-- Tools --> <condition property="exe" value=".exe" else=""><os family="windows" /></condition> <property name="adb" location="${android.tools.dir}/adb${exe}" /> <property name="zipalign" location="${android.tools.dir}/zipalign${exe}" /> <!-- Emma configuration --> <property name="emma.dir" value="${sdk.dir}/tools/lib" /> <path id="emma.lib"> <pathelement location="${emma.dir}/emma.jar" /> <pathelement location="${emma.dir}/emma_ant.jar" /> </path> <taskdef resource="emma_ant.properties" classpathref="emma.lib" /> <!-- End of emma configuration --> <!-- Macros --> <!-- Configurable macro, which allows to pass as parameters output directory, output dex filename and external libraries to dex (optional) --> <macrodef name="dex-helper"> <element name="external-libs" optional="yes" /> <element name="extra-parameters" optional="yes" /> <sequential> <echo>Converting compiled files and external libraries into ${intermediate.dex.file}... </echo> <apply executable="${dx}" failonerror="true" parallel="true"> <arg value="--dex" /> <arg value="--output=${intermediate.dex.file}" /> <extra-parameters /> <arg line="${verbose.option}" /> <arg path="${out.classes.absolute.dir}" /> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> <external-libs /> </apply> </sequential> </macrodef> <!-- This is macro that enable passing variable list of external jar files to ApkBuilder Example of use: <package-helper> <extra-jars> <jarfolder path="my_jars" /> <jarfile path="foo/bar.jar" /> <jarfolder path="your_jars" /> </extra-jars> </package-helper> --> <macrodef name="package-helper"> <attribute name="sign.package" /> <element name="extra-jars" optional="yes" /> <sequential> <apkbuilder outfolder="${out.absolute.dir}" basename="${ant.project.name}" signed="@{sign.package}" verbose="${verbose}"> <file path="${intermediate.dex.file}" /> <sourcefolder path="${source.absolute.dir}" /> <nativefolder path="${native.libs.absolute.dir}" /> <jarfolder path="${external.libs.absolute.dir}" /> <extra-jars/> </apkbuilder> </sequential> </macrodef> <!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets debug, -debug-with-emma and release.--> <macrodef name="zipalign-helper"> <attribute name="in.package" /> <attribute name="out.package" /> <sequential> <echo>Running zip align on final apk...</echo> <exec executable="${zipalign}" failonerror="true"> <arg line="${v.option}" /> <arg value="-f" /> <arg value="4" /> <arg path="@{in.package}" /> <arg path="@{out.package}" /> </exec> </sequential> </macrodef> <!-- This is macro used only for sharing code among two targets, -install and -install-with-emma which do exactly the same but differ in dependencies --> <macrodef name="install-helper"> <sequential> <echo>Installing ${out.debug.package} onto default emulator or device...</echo> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="install" /> <arg value="-r" /> <arg path="${out.debug.package}" /> </exec> </sequential> </macrodef> <!-- Rules --> <!-- Creates the output directories if they don't exist yet. --> <target name="-dirs"> <echo>Creating output directories if needed...</echo> <mkdir dir="${resource.absolute.dir}" /> <mkdir dir="${external.libs.absolute.dir}" /> <mkdir dir="${gen.absolute.dir}" /> <mkdir dir="${out.absolute.dir}" /> <mkdir dir="${out.classes.absolute.dir}" /> </target> <!-- Generates the R.java file for this project's resources. --> <target name="-resource-src" depends="-dirs"> <echo>Generating R.java / Manifest.java from the resources...</echo> <exec executable="${aapt}" failonerror="true"> <arg value="package" /> <arg line="${v.option}" /> <arg value="-m" /> <arg value="-J" /> <arg path="${gen.absolute.dir}" /> <arg value="-M" /> <arg path="AndroidManifest.xml" /> <arg value="-S" /> <arg path="${resource.absolute.dir}" /> <arg value="-I" /> <arg path="${android.jar}" /> </exec> </target> <!-- Generates java classes from .aidl files. --> <target name="-aidl" depends="-dirs"> <echo>Compiling aidl files into Java classes...</echo> <apply executable="${aidl}" failonerror="true"> <arg value="-p${android.aidl}" /> <arg value="-I${source.absolute.dir}" /> <arg value="-o${gen.absolute.dir}" /> <fileset dir="${source.absolute.dir}"> <include name="**/*.aidl" /> </fileset> </apply> </target> <!-- Compiles this project's .java files into .class files. --> <target name="compile" depends="-resource-src, -aidl" description="Compiles project's .java files into .class files"> <!-- If android rules are used for a test project, its classpath should include tested project's location --> <condition property="extensible.classpath" value="${tested.project.absolute.dir}/bin/classes" else="."> <isset property="tested.project.absolute.dir" /> </condition> <echo>extensible.classpath: ${extensible.classpath}</echo> <javac encoding="ascii" target="1.5" debug="true" extdirs="" destdir="${out.classes.absolute.dir}" bootclasspathref="android.target.classpath" verbose="${verbose}" classpath="${extensible.classpath}"> <src path="${source.absolute.dir}" /> <src path="${gen.absolute.dir}" /> <classpath> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> </classpath> </javac> </target> <!-- Converts this project's .class files into .dex files --> <target name="-dex" depends="compile"> <dex-helper /> </target> <!-- Puts the project's resources into the output package file This actually can create multiple resource package in case Some custom apk with specific configuration have been declared in default.properties. --> <target name="-package-resources"> <echo>Packaging resources</echo> <aaptexec executable="${aapt}" command="package" manifest="AndroidManifest.xml" resources="${resource.absolute.dir}" assets="${asset.absolute.dir}" androidjar="${android.jar}" outfolder="${out.absolute.dir}" basename="${ant.project.name}" /> </target> <!-- Packages the application and sign it with a debug key. --> <target name="-package-debug-sign" depends="-dex, -package-resources"> <package-helper sign.package="true" /> </target> <!-- Packages the application without signing it. --> <target name="-package-no-sign" depends="-dex, -package-resources"> <package-helper sign.package="false" /> </target> <target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again"> <subant target="compile"> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <!-- Builds debug output package, provided all the necessary files are already dexed --> <target name="debug" depends="-compile-tested-if-test, -package-debug-sign" description="Builds the application and signs it with a debug key."> <zipalign-helper in.package="${out.debug.unaligned.package}" out.package="${out.debug.package}" /> <echo>Debug Package: ${out.debug.package}</echo> </target> <target name="-release-check"> <condition property="release.sign"> <and> <isset property="key.store" /> <isset property="key.alias" /> </and> </condition> </target> <target name="-release-nosign" depends="-release-check" unless="release.sign"> <echo>No key.store and key.alias properties found in build.properties.</echo> <echo>Please sign ${out.unsigned.package} manually</echo> <echo>and run zipalign from the Android SDK tools.</echo> </target> <target name="release" depends="-package-no-sign, -release-nosign" if="release.sign" description="Builds the application. The generated apk file must be signed before it is published."> <!-- Gets passwords --> <input message="Please enter keystore password (store:${key.store}):" addproperty="key.store.password" /> <input message="Please enter password for alias '${key.alias}':" addproperty="key.alias.password" /> <!-- Signs the APK --> <echo>Signing final apk...</echo> <signjar jar="${out.unsigned.package}" signedjar="${out.unaligned.package}" keystore="${key.store}" storepass="${key.store.password}" alias="${key.alias}" keypass="${key.alias.password}" verbose="${verbose}" /> <!-- Zip aligns the APK --> <zipalign-helper in.package="${out.unaligned.package}" out.package="${out.release.package}" /> <echo>Release Package: ${out.release.package}</echo> </target> <target name="install" depends="debug" description="Installs/reinstalls the debug package onto a running emulator or device. If the application was previously installed, the signatures must match." > <install-helper /> </target> <target name="-uninstall-check"> <condition property="uninstall.run"> <isset property="manifest.package" /> </condition> </target> <target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run"> <echo>Unable to run 'ant uninstall', manifest.package property is not defined. </echo> </target> <!-- Uninstalls the package from the default emulator/device --> <target name="uninstall" depends="-uninstall-error" if="uninstall.run" description="Uninstalls the application from a running emulator or device."> <echo>Uninstalling ${manifest.package} from the default emulator or device...</echo> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="uninstall" /> <arg value="${manifest.package}" /> </exec> </target> <target name="clean" description="Removes output files created by other targets."> <delete dir="${out.absolute.dir}" verbose="${verbose}" /> <delete dir="${gen.absolute.dir}" verbose="${verbose}" /> </target> <!-- Targets for code-coverage measurement purposes, invoked from external file --> <!-- Emma-instruments tested project classes (compiles the tested project if necessary) and writes instrumented classes to ${instrumentation.absolute.dir}/classes --> <target name="-emma-instrument" depends="compile"> <echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo> <!-- It only instruments class files, not any external libs --> <emma enabled="true"> <instr verbosity="${verbosity}" mode="overwrite" instrpath="${out.absolute.dir}/classes" outdir="${out.absolute.dir}/classes"> </instr> <!-- TODO: exclusion filters on R*.class and allowing custom exclusion from user defined file --> </emma> </target> <target name="-dex-instrumented" depends="-emma-instrument"> <dex-helper> <extra-parameters> <arg value="--no-locals" /> </extra-parameters> <external-libs> <fileset file="${emma.dir}/emma_device.jar" /> </external-libs> </dex-helper> </target> <!-- Invoked from external files for code coverage purposes --> <target name="-package-with-emma" depends="-dex-instrumented, -package-resources"> <package-helper sign.package="true"> <extra-jars> <!-- Injected from external file --> <jarfile path="${emma.dir}/emma_device.jar" /> </extra-jars> </package-helper> </target> <target name="-debug-with-emma" depends="-package-with-emma"> <zipalign-helper in.package="${out.debug.unaligned.package}" out.package="${out.debug.package}" /> </target> <target name="-install-with-emma" depends="-debug-with-emma"> <install-helper /> </target> <!-- End of targets for code-coverage measurement purposes --> <target name="help"> <!-- displays starts at col 13 |13 80| --> <echo>Android Ant Build. Available targets:</echo> <echo> help: Displays this help.</echo> <echo> clean: Removes output files created by other targets.</echo> <echo> compile: Compiles project's .java files into .class files.</echo> <echo> debug: Builds the application and signs it with a debug key.</echo> <echo> release: Builds the application. The generated apk file must be</echo> <echo> signed before it is published.</echo> <echo> install: Installs/reinstalls the debug package onto a running</echo> <echo> emulator or device.</echo> <echo> If the application was previously installed, the</echo> <echo> signatures must match.</echo> <echo> uninstall: Uninstalls the application from a running emulator or</echo> <echo> device.</echo> </target> <!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ --> <!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## --> <property name="tested.project.absolute.dir" location="${tested.project.dir}" /> <property name="junit.out.file" value="${tested.project.absolute.dir}\output\junit-result.txt" /> <property name="instrumentation.dir" value="instrumented" /> <property name="instrumentation.absolute.dir" location="${instrumentation.dir}" /> <property name="test.runner" value="android.test.InstrumentationTestRunner" /> <!-- Application package of the tested project extracted from its manifest file --> <xpath input="${tested.project.absolute.dir}/AndroidManifest.xml" expression="/manifest/@package" output="tested.manifest.package" /> <!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated project --> <property name="emma.dump.file" value="/data/data/${tested.manifest.package}/files/coverage.ec" /> <macrodef name="run-tests-helper"> <attribute name="emma.enabled" default="false" /> <element name="extra-instrument-args" optional="yes" /> <sequential> <echo>Running tests with output sent to ${junit.out.file}...</echo> <exec executable="${adb}" failonerror="true" output="${junit.out.file}"> <arg value="shell" /> <arg value="am" /> <arg value="instrument" /> <arg value="-w" /> <arg value="-r" /> <!-- XML output --> <arg value="-e" /> <arg value="coverage" /> <arg value="@{emma.enabled}" /> <extra-instrument-args /> <arg value="${manifest.package}/${test.runner}" /> </exec> <loadfile srcfile="${junit.out.file}" property="result"> <filterchain> <linecontains> <contains value="INSTRUMENTATION_CODE: -1"/> </linecontains> </filterchain> </loadfile> <loadfile srcfile="${junit.out.file}" property="result2"> <filterchain> <linecontains> <contains value="FAILURES"/> </linecontains> </filterchain> </loadfile> <echo>Result ${result} ${result2}</echo> <loadfile property="junit-out-file" srcFile="${junit.out.file}"/> <echo>Junit results...</echo> <echo>${junit-out-file}</echo> <fail unless="result">JUnit tests failed, please look at ${junit.out.file} for more information.</fail> <fail if="result2">JUnit tests failed, please look at ${junit.out.file} for more information.</fail> </sequential> </macrodef> <!-- Invoking this target sets the value of extensible.classpath, which is being added to javac classpath in target 'compile' (android_rules.xml) --> <target name="-set-coverage-classpath"> <property name="extensible.classpath" location="${instrumentation.absolute.dir}/classes" /> </target> <!-- Ensures that tested project is installed on the device before we run the tests. Used for ordinary tests, without coverage measurement --> <target name="-install-tested-project"> <property name="do.not.compile.again" value="true" /> <subant target="install"> <property name="sdk.dir" location="${sdk.dir}"/> <property name="sdk-location" location="${sdk-location}"/> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <target name="run-tests" depends="-install-tested-project, install" description="Runs tests from the package defined in test.package property"> <run-tests-helper /> </target> <target name="-install-instrumented"> <property name="do.not.compile.again" value="true" /> <subant target="-install-with-emma"> <property name="out.absolute.dir" value="${instrumentation.absolute.dir}" /> <property name="sdk.dir" location="${sdk.dir}"/> <property name="sdk-location" location="${sdk-location}"/> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <target name="coverage" depends="-set-coverage-classpath, -install-instrumented, install" description="Runs the tests against the instrumented code and generates code coverage report"> <run-tests-helper emma.enabled="true"> <extra-instrument-args> <arg value="-e" /> <arg value="coverageFile" /> <arg value="${emma.dump.file}" /> </extra-instrument-args> </run-tests-helper> <echo>Downloading coverage file into project directory...</echo> <exec executable="${adb}" failonerror="true"> <arg value="pull" /> <arg value="${emma.dump.file}" /> <arg value="coverage.ec" /> </exec> <echo>#################### INSERTED CODE #####################</echo> <move file="${tested.project.absolute.dir}/coverage.em" tofile="${tested.project.absolute.dir}/tests/coverage.em"/> <echo>#################### INSERTED CODE #####################</echo> <echo>Extracting coverage report...</echo> <emma> <report sourcepath="${tested.project.absolute.dir}/${source.dir}" verbosity="${verbosity}"> <!-- TODO: report.dir or something like should be introduced if necessary --> <infileset dir="."> <include name="coverage.ec" /> <include name="coverage.em" /> </infileset> <!-- TODO: reports in other, indicated by user formats --> <html outfile="coverage.html" /> </report> </emma> <echo>Cleaning up temporary files...</echo> <delete dir="${instrumentation.absolute.dir}" /> <delete file="coverage.ec" /> <delete file="coverage.em" /> <echo>Saving the report file in ${basedir}/coverage/coverage.html</echo> </target> <!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## --> -</project> +</project> \ No newline at end of file
360/360-Engine-for-Android
708decfe057c1286f5028d149e8efa7923a34f75
-fixed build script for the tests
diff --git a/tests/build.xml b/tests/build.xml index a63ee4b..c160cbb 100644 --- a/tests/build.xml +++ b/tests/build.xml @@ -1,693 +1,701 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <project name="tests"> + <property environment="env"/> + <!-- The local.properties file is created and updated by the 'android' tool. It contains the path to the SDK. It should *NOT* be checked in in Version Control Systems. --> <!-- <property file="local.properties" /> Point to the SDK location manually --> - <property name="sdk.dir" value="C:\\tools\\android-sdk-windows" /> - <property name="sdk-location" value="C:\\tools\\android-sdk-windows" /> <!-- The build.properties file can be created by you and is never touched by the 'android' tool. This is the place to change some of the default property values used by the Ant rules. Here are some properties you may want to change/update: application.package the name of your application package as defined in the manifest. Used by the 'uninstall' rule. source.dir the name of the source directory. Default is 'src'. out.dir the name of the output directory. Default is 'bin'. Properties related to the SDK location or the project target should be updated using the 'android' tool with the 'update' action. This file is an integral part of the build system for your application and should be checked in in Version Control Systems. --> <property file="build.properties" /> <!-- The default.properties file is created and updated by the 'android' tool, as well as ADT. This file is an integral part of the build system for your application and should be checked in in Version Control Systems. --> <property file="default.properties" /> + <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it + already on your system, please do so. After setting it, create a new properties file in + build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties + to it. --> + <property file="../build_property_files/${env.USERNAME_360}.properties" /> + <echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the + XMLTask is found in ${xml.task.dir}...</echo> + <!-- Custom Android task to deal with the project target, and import the proper rules. This requires ant 1.6.0 or above. --> <path id="android.antlibs"> <pathelement path="${sdk.dir}/tools/lib/anttasks.jar" /> <pathelement path="${sdk.dir}/tools/lib/sdklib.jar" /> <pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" /> <pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" /> <pathelement path="${sdk.dir}/tools/lib/jarutils.jar" /> </path> <taskdef name="setup" classname="com.android.ant.SetupTask" classpathref="android.antlibs" /> <!-- Execute the Android Setup task that will setup some properties specific to the target, and import the build rules files. The rules file is imported from <SDK>/platforms/<target_platform>/templates/android_rules.xml To customize some build steps for your project: - copy the content of the main node <project> from android_rules.xml - paste it in this build.xml below the <setup /> task. - disable the import by changing the setup task below to <setup import="false" /> This will ensure that the properties are setup correctly but that your customized build steps are used. --> <setup import="false" /> <!-- EMMA Coverage interface for build script --> <target name="emma-coverage-interface"> <echo>EMMA Coverage interface for build script.</echo> <ant target="coverage" /> </target> <!-- JUunit interface for build script --> <target name="run-tests-interface"> <echo>JUunit interface for build script.</echo> <ant target="run-tests" /> </target> <!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############ This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be run inside the build script without path issues. --> <!-- This rules file is meant to be imported by the custom Ant task: com.android.ant.AndroidInitTask The following properties are put in place by the importing task: android.jar, android.aidl, aapt, aidl, and dx Additionnaly, the task sets up the following classpath reference: android.target.classpath This is used by the compiler task as the boot classpath. --> <!-- Custom tasks --> <taskdef name="aaptexec" classname="com.android.ant.AaptExecLoopTask" classpathref="android.antlibs" /> <taskdef name="apkbuilder" classname="com.android.ant.ApkBuilderTask" classpathref="android.antlibs" /> <taskdef name="xpath" classname="com.android.ant.XPathTask" classpathref="android.antlibs" /> <!-- Properties --> <!-- Tells adb which device to target. You can change this from the command line by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for the emulator. --> <property name="adb.device.arg" value="" /> <property name="android.tools.dir" location="${sdk.dir}/tools" /> <!-- Name of the application package extracted from manifest file --> <xpath input="AndroidManifest.xml" expression="/manifest/@package" output="manifest.package" /> <!-- Input directories --> <property name="source.dir" value="src" /> <property name="source.absolute.dir" location="${source.dir}" /> <property name="gen.dir" value="gen" /> <property name="gen.absolute.dir" location="${gen.dir}" /> <property name="resource.dir" value="res" /> <property name="resource.absolute.dir" location="${resource.dir}" /> <property name="asset.dir" value="assets" /> <property name="asset.absolute.dir" location="${asset.dir}" /> <!-- Directory for the third party java libraries --> <property name="external.libs.dir" value="libs" /> <property name="external.libs.absolute.dir" location="${external.libs.dir}" /> <!-- Directory for the native libraries --> <property name="native.libs.dir" value="libs" /> <property name="native.libs.absolute.dir" location="${native.libs.dir}" /> <!-- Output directories --> <property name="out.dir" value="bin" /> <property name="out.absolute.dir" location="${out.dir}" /> <property name="out.classes.dir" value="${out.absolute.dir}/classes" /> <property name="out.classes.absolute.dir" location="${out.classes.dir}" /> <!-- Intermediate files --> <property name="dex.file.name" value="classes.dex" /> <property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" /> <!-- The final package file to generate --> <property name="out.debug.unaligned.package" location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" /> <property name="out.debug.package" location="${out.absolute.dir}/${ant.project.name}-debug.apk" /> <property name="out.unsigned.package" location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" /> <property name="out.unaligned.package" location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" /> <property name="out.release.package" location="${out.absolute.dir}/${ant.project.name}-release.apk" /> <!-- Verbosity --> <property name="verbose" value="false" /> <!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false' The property 'verbosity' is not user configurable and depends exclusively on 'verbose' value.--> <condition property="verbosity" value="verbose" else="quiet"> <istrue value="${verbose}" /> </condition> <!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose' --> <condition property="v.option" value="-v" else=""> <istrue value="${verbose}" /> </condition> <!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' --> <condition property="verbose.option" value="--verbose" else=""> <istrue value="${verbose}" /> </condition> <!-- Tools --> <condition property="exe" value=".exe" else=""><os family="windows" /></condition> <property name="adb" location="${android.tools.dir}/adb${exe}" /> <property name="zipalign" location="${android.tools.dir}/zipalign${exe}" /> <!-- Emma configuration --> <property name="emma.dir" value="${sdk.dir}/tools/lib" /> <path id="emma.lib"> <pathelement location="${emma.dir}/emma.jar" /> <pathelement location="${emma.dir}/emma_ant.jar" /> </path> <taskdef resource="emma_ant.properties" classpathref="emma.lib" /> <!-- End of emma configuration --> <!-- Macros --> <!-- Configurable macro, which allows to pass as parameters output directory, output dex filename and external libraries to dex (optional) --> <macrodef name="dex-helper"> <element name="external-libs" optional="yes" /> <element name="extra-parameters" optional="yes" /> <sequential> <echo>Converting compiled files and external libraries into ${intermediate.dex.file}... </echo> <apply executable="${dx}" failonerror="true" parallel="true"> <arg value="--dex" /> <arg value="--output=${intermediate.dex.file}" /> <extra-parameters /> <arg line="${verbose.option}" /> <arg path="${out.classes.absolute.dir}" /> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> <external-libs /> </apply> </sequential> </macrodef> <!-- This is macro that enable passing variable list of external jar files to ApkBuilder Example of use: <package-helper> <extra-jars> <jarfolder path="my_jars" /> <jarfile path="foo/bar.jar" /> <jarfolder path="your_jars" /> </extra-jars> </package-helper> --> <macrodef name="package-helper"> <attribute name="sign.package" /> <element name="extra-jars" optional="yes" /> <sequential> <apkbuilder outfolder="${out.absolute.dir}" basename="${ant.project.name}" signed="@{sign.package}" verbose="${verbose}"> <file path="${intermediate.dex.file}" /> <sourcefolder path="${source.absolute.dir}" /> <nativefolder path="${native.libs.absolute.dir}" /> <jarfolder path="${external.libs.absolute.dir}" /> <extra-jars/> </apkbuilder> </sequential> </macrodef> <!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets debug, -debug-with-emma and release.--> <macrodef name="zipalign-helper"> <attribute name="in.package" /> <attribute name="out.package" /> <sequential> <echo>Running zip align on final apk...</echo> <exec executable="${zipalign}" failonerror="true"> <arg line="${v.option}" /> <arg value="-f" /> <arg value="4" /> <arg path="@{in.package}" /> <arg path="@{out.package}" /> </exec> </sequential> </macrodef> <!-- This is macro used only for sharing code among two targets, -install and -install-with-emma which do exactly the same but differ in dependencies --> <macrodef name="install-helper"> <sequential> <echo>Installing ${out.debug.package} onto default emulator or device...</echo> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="install" /> <arg value="-r" /> <arg path="${out.debug.package}" /> </exec> </sequential> </macrodef> <!-- Rules --> <!-- Creates the output directories if they don't exist yet. --> <target name="-dirs"> <echo>Creating output directories if needed...</echo> <mkdir dir="${resource.absolute.dir}" /> <mkdir dir="${external.libs.absolute.dir}" /> <mkdir dir="${gen.absolute.dir}" /> <mkdir dir="${out.absolute.dir}" /> <mkdir dir="${out.classes.absolute.dir}" /> </target> <!-- Generates the R.java file for this project's resources. --> <target name="-resource-src" depends="-dirs"> <echo>Generating R.java / Manifest.java from the resources...</echo> <exec executable="${aapt}" failonerror="true"> <arg value="package" /> <arg line="${v.option}" /> <arg value="-m" /> <arg value="-J" /> <arg path="${gen.absolute.dir}" /> <arg value="-M" /> <arg path="AndroidManifest.xml" /> <arg value="-S" /> <arg path="${resource.absolute.dir}" /> <arg value="-I" /> <arg path="${android.jar}" /> </exec> </target> <!-- Generates java classes from .aidl files. --> <target name="-aidl" depends="-dirs"> <echo>Compiling aidl files into Java classes...</echo> <apply executable="${aidl}" failonerror="true"> <arg value="-p${android.aidl}" /> <arg value="-I${source.absolute.dir}" /> <arg value="-o${gen.absolute.dir}" /> <fileset dir="${source.absolute.dir}"> <include name="**/*.aidl" /> </fileset> </apply> </target> <!-- Compiles this project's .java files into .class files. --> <target name="compile" depends="-resource-src, -aidl" description="Compiles project's .java files into .class files"> <!-- If android rules are used for a test project, its classpath should include tested project's location --> <condition property="extensible.classpath" value="${tested.project.absolute.dir}/bin/classes" else="."> <isset property="tested.project.absolute.dir" /> </condition> <echo>extensible.classpath: ${extensible.classpath}</echo> <javac encoding="ascii" target="1.5" debug="true" extdirs="" destdir="${out.classes.absolute.dir}" bootclasspathref="android.target.classpath" verbose="${verbose}" classpath="${extensible.classpath}"> <src path="${source.absolute.dir}" /> <src path="${gen.absolute.dir}" /> <classpath> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> </classpath> </javac> </target> <!-- Converts this project's .class files into .dex files --> <target name="-dex" depends="compile"> <dex-helper /> </target> <!-- Puts the project's resources into the output package file This actually can create multiple resource package in case Some custom apk with specific configuration have been declared in default.properties. --> <target name="-package-resources"> <echo>Packaging resources</echo> <aaptexec executable="${aapt}" command="package" manifest="AndroidManifest.xml" resources="${resource.absolute.dir}" assets="${asset.absolute.dir}" androidjar="${android.jar}" outfolder="${out.absolute.dir}" basename="${ant.project.name}" /> </target> <!-- Packages the application and sign it with a debug key. --> <target name="-package-debug-sign" depends="-dex, -package-resources"> <package-helper sign.package="true" /> </target> <!-- Packages the application without signing it. --> <target name="-package-no-sign" depends="-dex, -package-resources"> <package-helper sign.package="false" /> </target> <target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again"> <subant target="compile"> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <!-- Builds debug output package, provided all the necessary files are already dexed --> <target name="debug" depends="-compile-tested-if-test, -package-debug-sign" description="Builds the application and signs it with a debug key."> <zipalign-helper in.package="${out.debug.unaligned.package}" out.package="${out.debug.package}" /> <echo>Debug Package: ${out.debug.package}</echo> </target> <target name="-release-check"> <condition property="release.sign"> <and> <isset property="key.store" /> <isset property="key.alias" /> </and> </condition> </target> <target name="-release-nosign" depends="-release-check" unless="release.sign"> <echo>No key.store and key.alias properties found in build.properties.</echo> <echo>Please sign ${out.unsigned.package} manually</echo> <echo>and run zipalign from the Android SDK tools.</echo> </target> <target name="release" depends="-package-no-sign, -release-nosign" if="release.sign" description="Builds the application. The generated apk file must be signed before it is published."> <!-- Gets passwords --> <input message="Please enter keystore password (store:${key.store}):" addproperty="key.store.password" /> <input message="Please enter password for alias '${key.alias}':" addproperty="key.alias.password" /> <!-- Signs the APK --> <echo>Signing final apk...</echo> <signjar jar="${out.unsigned.package}" signedjar="${out.unaligned.package}" keystore="${key.store}" storepass="${key.store.password}" alias="${key.alias}" keypass="${key.alias.password}" verbose="${verbose}" /> <!-- Zip aligns the APK --> <zipalign-helper in.package="${out.unaligned.package}" out.package="${out.release.package}" /> <echo>Release Package: ${out.release.package}</echo> </target> <target name="install" depends="debug" description="Installs/reinstalls the debug package onto a running emulator or device. If the application was previously installed, the signatures must match." > <install-helper /> </target> <target name="-uninstall-check"> <condition property="uninstall.run"> <isset property="manifest.package" /> </condition> </target> <target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run"> <echo>Unable to run 'ant uninstall', manifest.package property is not defined. </echo> </target> <!-- Uninstalls the package from the default emulator/device --> <target name="uninstall" depends="-uninstall-error" if="uninstall.run" description="Uninstalls the application from a running emulator or device."> <echo>Uninstalling ${manifest.package} from the default emulator or device...</echo> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="uninstall" /> <arg value="${manifest.package}" /> </exec> </target> <target name="clean" description="Removes output files created by other targets."> <delete dir="${out.absolute.dir}" verbose="${verbose}" /> <delete dir="${gen.absolute.dir}" verbose="${verbose}" /> </target> <!-- Targets for code-coverage measurement purposes, invoked from external file --> <!-- Emma-instruments tested project classes (compiles the tested project if necessary) and writes instrumented classes to ${instrumentation.absolute.dir}/classes --> <target name="-emma-instrument" depends="compile"> <echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo> <!-- It only instruments class files, not any external libs --> <emma enabled="true"> <instr verbosity="${verbosity}" mode="overwrite" instrpath="${out.absolute.dir}/classes" outdir="${out.absolute.dir}/classes"> </instr> <!-- TODO: exclusion filters on R*.class and allowing custom exclusion from user defined file --> </emma> </target> <target name="-dex-instrumented" depends="-emma-instrument"> <dex-helper> <extra-parameters> <arg value="--no-locals" /> </extra-parameters> <external-libs> <fileset file="${emma.dir}/emma_device.jar" /> </external-libs> </dex-helper> </target> <!-- Invoked from external files for code coverage purposes --> <target name="-package-with-emma" depends="-dex-instrumented, -package-resources"> <package-helper sign.package="true"> <extra-jars> <!-- Injected from external file --> <jarfile path="${emma.dir}/emma_device.jar" /> </extra-jars> </package-helper> </target> <target name="-debug-with-emma" depends="-package-with-emma"> <zipalign-helper in.package="${out.debug.unaligned.package}" out.package="${out.debug.package}" /> </target> <target name="-install-with-emma" depends="-debug-with-emma"> <install-helper /> </target> <!-- End of targets for code-coverage measurement purposes --> <target name="help"> <!-- displays starts at col 13 |13 80| --> <echo>Android Ant Build. Available targets:</echo> <echo> help: Displays this help.</echo> <echo> clean: Removes output files created by other targets.</echo> <echo> compile: Compiles project's .java files into .class files.</echo> <echo> debug: Builds the application and signs it with a debug key.</echo> <echo> release: Builds the application. The generated apk file must be</echo> <echo> signed before it is published.</echo> <echo> install: Installs/reinstalls the debug package onto a running</echo> <echo> emulator or device.</echo> <echo> If the application was previously installed, the</echo> <echo> signatures must match.</echo> <echo> uninstall: Uninstalls the application from a running emulator or</echo> <echo> device.</echo> </target> <!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ --> <!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## --> <property name="tested.project.absolute.dir" location="${tested.project.dir}" /> <property name="junit.out.file" value="${tested.project.absolute.dir}\output\junit-result.txt" /> <property name="instrumentation.dir" value="instrumented" /> <property name="instrumentation.absolute.dir" location="${instrumentation.dir}" /> <property name="test.runner" value="android.test.InstrumentationTestRunner" /> <!-- Application package of the tested project extracted from its manifest file --> <xpath input="${tested.project.absolute.dir}/AndroidManifest.xml" expression="/manifest/@package" output="tested.manifest.package" /> <!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated project --> <property name="emma.dump.file" value="/data/data/${tested.manifest.package}/files/coverage.ec" /> <macrodef name="run-tests-helper"> <attribute name="emma.enabled" default="false" /> <element name="extra-instrument-args" optional="yes" /> <sequential> <echo>Running tests with output sent to ${junit.out.file}...</echo> <exec executable="${adb}" failonerror="true" output="${junit.out.file}"> <arg value="shell" /> <arg value="am" /> <arg value="instrument" /> <arg value="-w" /> <arg value="-r" /> <!-- XML output --> <arg value="-e" /> <arg value="coverage" /> <arg value="@{emma.enabled}" /> <extra-instrument-args /> <arg value="${manifest.package}/${test.runner}" /> </exec> <loadfile srcfile="${junit.out.file}" property="result"> <filterchain> <linecontains> <contains value="INSTRUMENTATION_CODE: -1"/> </linecontains> </filterchain> </loadfile> <loadfile srcfile="${junit.out.file}" property="result2"> <filterchain> <linecontains> <contains value="FAILURES"/> </linecontains> </filterchain> </loadfile> <echo>Result ${result} ${result2}</echo> <loadfile property="junit-out-file" srcFile="${junit.out.file}"/> <echo>Junit results...</echo> <echo>${junit-out-file}</echo> <fail unless="result">JUnit tests failed, please look at ${junit.out.file} for more information.</fail> <fail if="result2">JUnit tests failed, please look at ${junit.out.file} for more information.</fail> </sequential> </macrodef> <!-- Invoking this target sets the value of extensible.classpath, which is being added to javac classpath in target 'compile' (android_rules.xml) --> <target name="-set-coverage-classpath"> <property name="extensible.classpath" location="${instrumentation.absolute.dir}/classes" /> </target> <!-- Ensures that tested project is installed on the device before we run the tests. Used for ordinary tests, without coverage measurement --> <target name="-install-tested-project"> <property name="do.not.compile.again" value="true" /> <subant target="install"> <property name="sdk.dir" location="${sdk.dir}"/> <property name="sdk-location" location="${sdk-location}"/> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <target name="run-tests" depends="-install-tested-project, install" description="Runs tests from the package defined in test.package property"> <run-tests-helper /> </target> <target name="-install-instrumented"> <property name="do.not.compile.again" value="true" /> <subant target="-install-with-emma"> <property name="out.absolute.dir" value="${instrumentation.absolute.dir}" /> <property name="sdk.dir" location="${sdk.dir}"/> <property name="sdk-location" location="${sdk-location}"/> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <target name="coverage" depends="-set-coverage-classpath, -install-instrumented, install" description="Runs the tests against the instrumented code and generates code coverage report"> <run-tests-helper emma.enabled="true"> <extra-instrument-args> <arg value="-e" /> <arg value="coverageFile" /> <arg value="${emma.dump.file}" /> </extra-instrument-args> </run-tests-helper> <echo>Downloading coverage file into project directory...</echo> <exec executable="${adb}" failonerror="true"> <arg value="pull" /> <arg value="${emma.dump.file}" /> <arg value="coverage.ec" /> </exec> <echo>#################### INSERTED CODE #####################</echo> <move file="${tested.project.absolute.dir}/coverage.em" tofile="${tested.project.absolute.dir}/tests/coverage.em"/> <echo>#################### INSERTED CODE #####################</echo> <echo>Extracting coverage report...</echo> <emma> <report sourcepath="${tested.project.absolute.dir}/${source.dir}" verbosity="${verbosity}"> <!-- TODO: report.dir or something like should be introduced if necessary --> <infileset dir="."> <include name="coverage.ec" /> <include name="coverage.em" /> </infileset> <!-- TODO: reports in other, indicated by user formats --> <html outfile="coverage.html" /> </report> </emma> <echo>Cleaning up temporary files...</echo> <delete dir="${instrumentation.absolute.dir}" /> <delete file="coverage.ec" /> <delete file="coverage.em" /> <echo>Saving the report file in ${basedir}/coverage/coverage.html</echo> </target> <!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## --> -</project> \ No newline at end of file +</project>
360/360-Engine-for-Android
4e30c071f36487795011705216bcb873172e8399
fix for bug 1583/1464
diff --git a/src/com/vodafone360/people/database/tables/ContactSummaryTable.java b/src/com/vodafone360/people/database/tables/ContactSummaryTable.java index 8290a8e..5eaadee 100644 --- a/src/com/vodafone360/people/database/tables/ContactSummaryTable.java +++ b/src/com/vodafone360/people/database/tables/ContactSummaryTable.java @@ -1,1369 +1,1386 @@ /* * 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.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Map.Entry; import android.content.ContentValues; 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 com.vodafone360.people.Settings; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.tables.ContactsTable.ContactIdInfo; import com.vodafone360.people.datatypes.Contact; 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.datatypes.ContactSummary.AltFieldType; import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.User; import com.vodafone360.people.service.ServiceStatus; import com.vodafone360.people.utils.CloseUtils; import com.vodafone360.people.utils.LogUtils; /** * The ContactSummaryTable contains a summary of important contact details for * each contact such as name, status and Avatar availability. This data is * duplicated here to improve the performance of the main contact list in the UI * (otherwise the a costly inner join between the contact and contact details * table would be needed). This class is never instantiated hence all methods * must be static. * * @version %I%, %G% */ public abstract class ContactSummaryTable { /** * The name of the table as it appears in the database. */ public static final String TABLE_NAME = "ContactSummary"; public static final String TABLE_INDEX_NAME = "ContactSummaryIndex"; /** * This holds the presence information for each contact in the ContactSummaryTable */ private static HashMap<Long, Integer> sPresenceMap = new HashMap<Long, Integer>(); /** * An enumeration of all the field names in the database. */ public static enum Field { SUMMARYID("_id"), LOCALCONTACTID("LocalContactId"), DISPLAYNAME("DisplayName"), STATUSTEXT("StatusText"), ALTFIELDTYPE("AltFieldType"), ALTDETAILTYPE("AltDetailType"), ONLINESTATUS("OnlineStatus"), NATIVEID("NativeId"), FRIENDOFMINE("FriendOfMine"), PICTURELOADED("PictureLoaded"), SNS("Sns"), SYNCTOPHONE("Synctophone"); /** * The 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(String field) { mField = field; } /** * @return the name of the field as it appears in the database. */ public String toString() { return mField; } } /** * Creates ContactSummary Table. * * @param writeableDb A writable SQLite database * @throws SQLException If an SQL compilation error occurs */ public static void create(SQLiteDatabase writeableDb) throws SQLException { DatabaseHelper.trace(true, "ContactSummaryTable.create()"); //TODO: As of now kept the onlinestatus field in table. Would remove it later on writeableDb.execSQL("CREATE TABLE " + TABLE_NAME + " (" + Field.SUMMARYID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.LOCALCONTACTID + " LONG, " + Field.DISPLAYNAME + " TEXT, " + Field.STATUSTEXT + " TEXT, " + Field.ALTFIELDTYPE + " INTEGER, " + Field.ALTDETAILTYPE + " INTEGER, " + Field.ONLINESTATUS + " INTEGER, " + Field.NATIVEID + " INTEGER, " + Field.FRIENDOFMINE + " BOOLEAN, " + Field.PICTURELOADED + " BOOLEAN, " + Field.SNS + " STRING, " + Field.SYNCTOPHONE + " BOOLEAN);"); writeableDb.execSQL("CREATE INDEX " + TABLE_INDEX_NAME + " ON " + TABLE_NAME + " ( " + Field.LOCALCONTACTID + ", " + Field.DISPLAYNAME + " )"); clearPresenceMap(); } /** * Fetches the list of table fields that can be injected into an SQL query * statement. The {@link #getQueryData(Cursor)} method can be used to obtain * the data from the query. * * @return The query string * @see #getQueryData(Cursor). */ private static String getFullQueryList() { return Field.SUMMARYID + ", " + TABLE_NAME + "." + Field.LOCALCONTACTID + ", " + Field.DISPLAYNAME + ", " + Field.STATUSTEXT + ", " + Field.ONLINESTATUS + ", " + Field.NATIVEID + ", " + Field.FRIENDOFMINE + ", " + Field.PICTURELOADED + ", " + Field.SNS + ", " + Field.SYNCTOPHONE + ", " + Field.ALTFIELDTYPE + ", " + Field.ALTDETAILTYPE; } /** * Returns a full SQL query statement to fetch the contact summary * information. The {@link #getQueryData(Cursor)} method can be used to * obtain the data from the query. * * @return The query string * @see #getQueryData(Cursor). */ private static String getOrderedQueryStringSql() { return "SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " ORDER BY LOWER(" + Field.DISPLAYNAME + ")"; } /** * Returns a full SQL query statement to fetch the contact summary * information. The {@link #getQueryData(Cursor)} method can be used to * obtain the data from the query. * * @param whereClause An SQL where clause (without the "WHERE"). Cannot be * null. * @return The query string * @see #getQueryData(Cursor). */ private static String getQueryStringSql(String whereClause) { return "SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE " + whereClause; } /** * Returns a full SQL query statement to fetch the contact summary * information in alphabetical order of contact name. The * {@link #getQueryData(Cursor)} method can be used to obtain the data from * the query. * * @param whereClause An SQL where clause (without the "WHERE"). Cannot be * null. * @return The query string * @see #getQueryData(Cursor). */ private static String getOrderedQueryStringSql(String whereClause) { return "SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE " + whereClause + " ORDER BY LOWER(" + Field.DISPLAYNAME + ")"; } /** * UPDATE ContactSummary SET * NativeId = ? * WHERE LocalContactId = ? */ private static final String UPDATE_NATIVE_ID_BY_LOCAL_CONTACT_ID = "UPDATE " + TABLE_NAME + " SET " + Field.NATIVEID + "=? WHERE " + Field.LOCALCONTACTID + "=?"; /** * Column indices which match the query string returned by * {@link #getFullQueryList()}. */ private static final int SUMMARY_ID = 0; private static final int LOCALCONTACT_ID = 1; private static final int FORMATTED_NAME = 2; private static final int STATUS_TEXT = 3; @SuppressWarnings("unused") @Deprecated private static final int ONLINE_STATUS = 4; private static final int NATIVE_CONTACTID = 5; private static final int FRIEND_MINE = 6; private static final int PICTURE_LOADED = 7; private static final int SNS = 8; private static final int SYNCTOPHONE = 9; private static final int ALTFIELD_TYPE = 10; private static final int ALTDETAIL_TYPE = 11; /** * Fetches the contact summary data from the current record of the given * cursor. * * @param c Cursor returned by one of the {@link #getFullQueryList()} based * query methods. * @return Filled in ContactSummary object */ public static ContactSummary getQueryData(Cursor c) { ContactSummary contactSummary = new ContactSummary(); if (!c.isNull(SUMMARY_ID)) { contactSummary.summaryID = c.getLong(SUMMARY_ID); } if (!c.isNull(LOCALCONTACT_ID)) { contactSummary.localContactID = c.getLong(LOCALCONTACT_ID); } contactSummary.formattedName = c.getString(FORMATTED_NAME); contactSummary.statusText = c.getString(STATUS_TEXT); contactSummary.onlineStatus = getPresence(contactSummary.localContactID); if (!c.isNull(NATIVE_CONTACTID)) { contactSummary.nativeContactId = c.getInt(NATIVE_CONTACTID); } if (!c.isNull(FRIEND_MINE)) { contactSummary.friendOfMine = (c.getInt(FRIEND_MINE) == 0 ? false : true); } if (!c.isNull(PICTURE_LOADED)) { contactSummary.pictureLoaded = (c.getInt(PICTURE_LOADED) == 0 ? false : true); } if (!c.isNull(SNS)) { contactSummary.sns = c.getString(SNS); } if (!c.isNull(SYNCTOPHONE)) { contactSummary.synctophone = (c.getInt(SYNCTOPHONE) == 0 ? false : true); } if (!c.isNull(ALTFIELD_TYPE)) { int val = c.getInt(ALTFIELD_TYPE); if (val < AltFieldType.values().length) { contactSummary.altFieldType = AltFieldType.values()[val]; } } if (!c.isNull(ALTDETAIL_TYPE)) { int val = c.getInt(ALTDETAIL_TYPE); if (val < ContactDetail.DetailKeys.values().length) { contactSummary.altDetailType = ContactDetail.DetailKeyTypes.values()[val]; } } return contactSummary; } /** * Fetches the contact summary for a particular contact * * @param localContactID The primary key ID of the contact to find * @param summary A new ContactSummary object to be filled in * @param readableDb Readable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus fetchSummaryItem(long localContactId, ContactSummary summary, SQLiteDatabase readableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(false, "ContactSummeryTable.fetchSummaryItem() localContactId[" + localContactId + "]"); } Cursor c1 = null; try { c1 = readableDb.rawQuery( getQueryStringSql(Field.LOCALCONTACTID + "=" + localContactId), null); if (!c1.moveToFirst()) { LogUtils.logW("ContactSummeryTable.fetchSummaryItem() localContactId[" + localContactId + "] not found in ContactSummeryTable."); return ServiceStatus.ERROR_NOT_FOUND; } summary.copy(getQueryData(c1)); return ServiceStatus.SUCCESS; } catch (SQLiteException e) { LogUtils .logE( "ContactSummeryTable.fetchSummaryItem() Exception - Unable to fetch contact summary", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } finally { CloseUtils.close(c1); c1 = null; } } /** * Processes a ContentValues object to handle a missing name or missing * status. * <ol> * <li>If the name is missing it will be replaced using the alternative * detail.</li> * <li>If the name is present, but status is missing the status will be * replaced using the alternative detail</li> * <li>Otherwise, the althernative detail is not used</li> * </ol> * In any case the {@link Field#ALTFIELDTYPE} value will be updated to * reflect how the alternative detail is being used. * * @param values The ContentValues object to be updated * @param altDetail The must suitable alternative detail (see * {@link #fetchNewAltDetail(long, ContactDetail, SQLiteDatabase)} */ private static void updateAltValues(ContentValues values, ContactDetail altDetail) { if (!values.containsKey(Field.DISPLAYNAME.toString())) { values.put(Field.DISPLAYNAME.toString(), altDetail.getValue()); values.put(Field.ALTFIELDTYPE.toString(), ContactSummary.AltFieldType.NAME.ordinal()); } else if (!values.containsKey(Field.STATUSTEXT.toString())) { values.put(Field.STATUSTEXT.toString(), altDetail.getValue()); values.put(Field.ALTFIELDTYPE.toString(), ContactSummary.AltFieldType.STATUS.ordinal()); } else { values.put(Field.ALTFIELDTYPE.toString(), ContactSummary.AltFieldType.UNUSED.ordinal()); } if (altDetail.keyType != null) { values.put(Field.ALTDETAILTYPE.toString(), altDetail.keyType.ordinal()); } } /** * Processes a ContentValues object to handle a missing name or missing * status. * <ol> * <li>If type is NAME, the name will be set to the alternative detail.</li> * <li>If type is STATUS, the status will be set to the alternative detail</li> * <li>Otherwise, the alternative detail is not used</li> * </ol> * In any case the {@link Field#ALTFIELDTYPE} value will be updated to * reflect how the alternative detail is being used. * * @param values The ContentValues object to be updated * @param altDetail The must suitable alternative detail (see * {@link #fetchNewAltDetail(long, ContactDetail, SQLiteDatabase)} * @param type Specifies how the alternative detail should be used */ /* * private static void updateAltValues(ContentValues values, ContactDetail * altDetail, ContactSummary.AltFieldType type) { switch (type) { case NAME: * values.put(Field.DISPLAYNAME.toString(), altDetail.getValue()); * values.put(Field.ALTFIELDTYPE.toString(), * ContactSummary.AltFieldType.NAME .ordinal()); break; case STATUS: * values.put(Field.STATUSTEXT.toString(), altDetail.getValue()); * values.put(Field.ALTFIELDTYPE.toString(), * ContactSummary.AltFieldType.STATUS .ordinal()); break; default: * values.put(Field.ALTFIELDTYPE.toString(), * ContactSummary.AltFieldType.UNUSED .ordinal()); } if (altDetail.keyType * != null) { values.put(Field.ALTDETAILTYPE.toString(), * altDetail.keyType.ordinal()); } } */ /** * Adds contact summary information to the table for a new contact. If the * contact has no name or no status, an alternative detail will be used such * as telephone number or email address. * * @param contact The new contact * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus addContact(Contact contact, SQLiteDatabase writableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(true, "ContactSummeryTable.addContact() contactID[" + contact.contactID + "]"); } if (contact.localContactID == null) { LogUtils.logE("ContactSummeryTable.addContact() Invalid parameters"); return ServiceStatus.ERROR_NOT_FOUND; } try { final ContentValues values = new ContentValues(); values.put(Field.LOCALCONTACTID.toString(), contact.localContactID); values.put(Field.NATIVEID.toString(), contact.nativeContactId); values.put(Field.FRIENDOFMINE.toString(), contact.friendOfMine); values.put(Field.SYNCTOPHONE.toString(), contact.synctophone); ContactDetail altDetail = findAlternativeNameContactDetail(values, contact.details); updateAltValues(values, altDetail); addToPresenceMap(contact.localContactID); if (writableDb.insertOrThrow(TABLE_NAME, null, values) < 0) { LogUtils.logE("ContactSummeryTable.addContact() " + "Unable to insert new contact summary"); return ServiceStatus.ERROR_NOT_FOUND; } return ServiceStatus.SUCCESS; } catch (SQLException e) { LogUtils.logE("ContactSummeryTable.addContact() SQLException - " + "Unable to insert new contact summary", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } /** * This method returns the most preferred contact detail to be displayed * instead of the contact name when vcard.name is missing. * * @param values - ContentValues to be stored in the DB for the added * contact * @param details - the list of all contact details for the contact being * added * @return the contact detail most suitable to replace the missing * vcard.name. "Value" field may be empty if no suitable contact * detail was found. */ private static ContactDetail findAlternativeNameContactDetail(ContentValues values, List<ContactDetail> details) { ContactDetail altDetail = new ContactDetail(); for (ContactDetail detail : details) { getContactValuesFromDetail(values, detail); if (isPreferredAltDetail(detail, altDetail)) { altDetail.copy(detail); } } return altDetail; } /** * Deletes a contact summary record * * @param localContactID The primary key ID of the contact to delete * @param writableDb Writeable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus deleteContact(Long localContactId, SQLiteDatabase writableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(true, "ContactSummeryTable.deleteContact() localContactId[" + localContactId + "]"); } if (localContactId == null) { LogUtils.logE("ContactSummeryTable.deleteContact() Invalid parameters"); return ServiceStatus.ERROR_NOT_FOUND; } try { if (writableDb.delete(TABLE_NAME, Field.LOCALCONTACTID + "=" + localContactId, null) <= 0) { LogUtils.logE("ContactSummeryTable.deleteContact() " + "Unable to delete contact summary"); return ServiceStatus.ERROR_NOT_FOUND; } deleteFromPresenceMap(localContactId); return ServiceStatus.SUCCESS; } catch (SQLException e) { LogUtils.logE("ContactSummeryTable.deleteContact() SQLException - " + "Unable to delete contact summary", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } /** * Modifies contact parameters. Called when fields in the Contacts table * have been changed. * * @param contact The modified contact * @param writableDb Writable SQLite database * @return SUCCESS or a suitable error code */ public static ServiceStatus modifyContact(Contact contact, SQLiteDatabase writableDb) { if (Settings.ENABLED_DATABASE_TRACE) { DatabaseHelper.trace(true, "ContactSummeryTable.modifyContact() contactID[" + contact.contactID + "]"); } if (contact.localContactID == null) { LogUtils.logE("ContactSummeryTable.modifyContact() Invalid parameters"); return ServiceStatus.ERROR_NOT_FOUND; } try { final ContentValues values = new ContentValues(); values.put(Field.LOCALCONTACTID.toString(), contact.localContactID); values.put(Field.NATIVEID.toString(), contact.nativeContactId); values.put(Field.FRIENDOFMINE.toString(), contact.friendOfMine); values.put(Field.SYNCTOPHONE.toString(), contact.synctophone); String[] args = { String.format("%d", contact.localContactID) }; if (writableDb.update(TABLE_NAME, values, Field.LOCALCONTACTID + "=?", args) < 0) { LogUtils.logE("ContactSummeryTable.modifyContact() " + "Unable to update contact summary"); return ServiceStatus.ERROR_NOT_FOUND; } return ServiceStatus.SUCCESS; } catch (SQLException e) { LogUtils.logE("ContactSummeryTable.modifyContact() " + "SQLException - Unable to update contact summary", e); return ServiceStatus.ERROR_DATABASE_CORRUPT; } } /** * Adds suitable entries to a ContentValues objects for inserting or * updating the contact summary table, from a contact detail. * * @param contactValues The content values object to update * @param newDetail The new or modified detail * @return true if the summary table has been updated, false otherwise */ private static boolean getContactValuesFromDetail(ContentValues contactValues, ContactDetail newDetail) { switch (newDetail.key) { case VCARD_NAME: if (newDetail.value != null) { VCardHelper.Name name = newDetail.getName(); if (name != null) { String nameStr = name.toString(); // this is what we do to display names of contacts // coming from server if (nameStr.length() > 0) { contactValues.put(Field.DISPLAYNAME.toString(), name.toString()); } } } return true; case PRESENCE_TEXT: if (newDetail.value != null && newDetail.value.length() > 0) { contactValues.put(Field.STATUSTEXT.toString(), newDetail.value); contactValues.put(Field.SNS.toString(), newDetail.alt); } return true; case PHOTO: if (newDetail.value == null) { contactValues.put(Field.PICTURELOADED.toString(), (Boolean)null); } else { contactValues.put(Field.PICTURELOADED.toString(), false); } return true; default: // Do Nothing. } return false; } /** * Determines if a contact detail should be used in preference to the * current alternative detail (the alternative detail is one that is shown * when a contact has no name or no status). * * @param newDetail The new detail * @param currentDetail The current alternative detail * @return true if the new detail should be used, false otherwise */ private static boolean isPreferredAltDetail(ContactDetail newDetail, ContactDetail currentDetail) { // this means we'll update the detail if (currentDetail.key == null || (currentDetail.key == DetailKeys.UNKNOWN)) { return true; } switch (newDetail.key) { case VCARD_PHONE: // AA:EMAIL,IMADDRESS,ORG will not be updated, PHONE will // consider "preferred" detail check switch (currentDetail.key) { case VCARD_EMAIL: case VCARD_IMADDRESS: case VCARD_ORG: case VCARD_ADDRESS: case VCARD_BUSINESS: case VCARD_TITLE: case VCARD_ROLE: return false; case VCARD_PHONE: break; default: return true; } break; case VCARD_IMADDRESS: // AA:will be updating everything, except for EMAIL and ORG, and // IMADDRESS, when preferred details needs to be considered // first switch (currentDetail.key) { case VCARD_IMADDRESS: break; case VCARD_EMAIL: case VCARD_ORG: case VCARD_ROLE: case VCARD_TITLE: return false; default: return true; } break; case VCARD_ADDRESS: case VCARD_BUSINESS: // AA:will be updating everything, except for EMAIL and ORG, // when preferred details needs to be considered first switch (currentDetail.key) { case VCARD_EMAIL: case VCARD_ORG: case VCARD_ROLE: case VCARD_TITLE: return false; case VCARD_ADDRESS: case VCARD_BUSINESS: break; default: return true; } break; case VCARD_ROLE: case VCARD_TITLE: // AA:will be updating everything, except for EMAIL and ORG, // when preferred details needs to be considered first switch (currentDetail.key) { case VCARD_EMAIL: case VCARD_ORG: 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 updateNameAndStatus(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.DetailKeys prefferredStatusDetails[] = { ContactDetail.DetailKeys.PRESENCE_TEXT, ContactDetail.DetailKeys.VCARD_PHONE, ContactDetail.DetailKeys.VCARD_EMAIL }; ContactDetail name = null; ContactDetail status = 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; } } // Query the details for status field for (ContactDetail.DetailKeys key : prefferredStatusDetails) { if ((status = contact.getContactDetail(key)) != null) { // Some contacts have only email but the name detail!=null // (gmail for example) if (key == ContactDetail.DetailKeys.VCARD_NAME && status.getName() == null) continue; if (key != ContactDetail.DetailKeys.VCARD_NAME && isEmpty(status.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(); // Build the status String statusString = status != null ? status.getValue() : null; if (statusString == null) statusString = ""; if (status != null && status.key == ContactDetail.DetailKeys.VCARD_NAME) statusString = status.getName().toString(); int altFieldType = AltFieldType.STATUS.ordinal(); int altDetailType = (status != null && status.keyType != null) ? status.keyType.ordinal() : ContactDetail.DetailKeyTypes.UNKNOWN.ordinal(); // This has to be done in order to set presence text. altFieldType and // altDetailType have to be 0, SNS has to be set String sns = ""; if (status != null && status.key == ContactDetail.DetailKeys.PRESENCE_TEXT) { altFieldType = AltFieldType.UNUSED.ordinal(); altDetailType = 0; sns = status.alt; } // If no status is present, display nothing if (isEmpty(statusString)) { altFieldType = AltFieldType.UNUSED.ordinal(); altDetailType = 0; } // Start updating the table SQLiteStatement statement = null; try { statement = writableDb.compileStatement("UPDATE " + TABLE_NAME + " SET " + Field.DISPLAYNAME + "=?," + Field.STATUSTEXT + "=?," + Field.ALTDETAILTYPE + "=?," + Field.ALTFIELDTYPE + "=?," + Field.SNS + "=? WHERE " + Field.LOCALCONTACTID + "=?"); writableDb.beginTransaction(); statement.bindString(1, nameString); statement.bindString(2, statusString); statement.bindLong(3, altDetailType); statement.bindLong(4, altFieldType); statement.bindString(5, sns); statement.bindLong(6, 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 */ private 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; } } } diff --git a/src/com/vodafone360/people/database/tables/PresenceTable.java b/src/com/vodafone360/people/database/tables/PresenceTable.java index 8238a79..41e0a11 100644 --- a/src/com/vodafone360/people/database/tables/PresenceTable.java +++ b/src/com/vodafone360/people/database/tables/PresenceTable.java @@ -1,316 +1,414 @@ /* * 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.Iterator; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import com.vodafone360.people.database.DatabaseHelper; import com.vodafone360.people.database.SQLKeys; - import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; import com.vodafone360.people.engine.presence.NetworkPresence; import com.vodafone360.people.engine.presence.User; import com.vodafone360.people.utils.CloseUtils; import com.vodafone360.people.utils.LogUtils; import com.vodafone360.people.utils.StringBufferPool; /** * PresenceTable... The table for storing the presence states of contacts. * * @throws SQLException is thrown when request to create a table fails with an * SQLException * @throws NullPointerException if the passed in database instance is null */ public abstract class PresenceTable { /*** * The name of the table as it appears in the database. */ public static final String TABLE_NAME = "Presence"; // it is used in the // tests /** * The return types for the add/update method: if a new record was added. */ public static final int USER_ADDED = 0; /** * The return types for the add/update method: if an existing record was * updated. */ public static final int USER_UPDATED = 1; /** * The return types for the add/update method: if an error happened and * prevented the record from being added or updated. */ public static final int USER_NOTADDED = 2; /** * An enumeration of all the field names in the database, containing ID, * LOCAL_CONTACT_ID, USER_ID, NETWORK_ID, NETWORK_STATUS. */ private static enum Field { /** * The primary key. */ ID("id"), /** * The internal representation of the serverId for this account. */ LOCAL_CONTACT_ID("LocalContactId"), /** * This is contact list id: gmail, facebook, nowplus or other account, * STRING. */ USER_ID("ImAddress"), /** * The SocialNetwork id, INT. */ NETWORK_ID("NetworkId"), /** * The presence status id, INT. */ NETWORK_STATUS("Status"); /** * The name of the field as it appears in the database. */ private String mField; /** * Constructor. * * @param field - Field name */ private Field(String field) { mField = field; } /* * This implementation returns the field name. (non-Javadoc) * @see java.lang.Enum#toString() */ public String toString() { return mField; } } /** * The constants for column indexes in the table: LocalContactId */ private static final int LOCAL_CONTACT_ID = 1; /** * The constants for column indexes in the table: ImAddress */ private static final int USER_ID = 2; /** * The constants for column indexes in the table: NetworkId */ private static final int NETWORK_ID = 3; /** * The constants for column indexes in the table: Status */ private static final int NETWORK_STATUS = 4; /** * The default message for the NullPointerException caused by the null * instance of database passed into PresenceTable methods. */ private static final String DEFAULT_ERROR_MESSAGE = "PresenceTable: the passed in database is null!"; /** * This method creates the PresenceTable. * * @param writableDb - the writable database * @throws SQLException is thrown when request to create a table fails with * an SQLException * @throws NullPointerException if the passed in database instance is null */ public static void create(SQLiteDatabase writableDb) throws SQLException, NullPointerException { DatabaseHelper.trace(true, "PresenceTable.create()"); if (writableDb == null) { throw new NullPointerException(DEFAULT_ERROR_MESSAGE); } String createSql = "CREATE TABLE IF NOT EXISTS " + DatabaseHelper.DATABASE_PRESENCE + "." + TABLE_NAME + " (" + Field.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.LOCAL_CONTACT_ID + " LONG, " + Field.USER_ID + " STRING, " + Field.NETWORK_ID + " INT, " + Field.NETWORK_STATUS + " INT);"; writableDb.execSQL(createSql); } /** * This method updates the user with the information from the User wrapper. * * @param user2Update - User info to update + * @param ignoredNetworkIds - ArrayList of integer network ids presence state for which must be ignored. * @param writableDatabase - writable database * @return USER_ADDED if no user with user id like the one in user2Update * payload "status.getUserId()" ever existed in this table, * USER_UPDATED if the user already existed in the table and has * been successfully added, USER_NOT_ADDED - if user was not added. * @throws SQLException if the database layer throws this exception. * @throws NullPointerException if the passed in database instance is null. */ - public static int updateUser(User user2Update, SQLiteDatabase writableDatabase) + public static int updateUser(User user2Update, ArrayList<Integer> ignoredNetworkIds, SQLiteDatabase writableDatabase) throws SQLException, NullPointerException { int ret = USER_NOTADDED; if (writableDatabase == null) { throw new NullPointerException(DEFAULT_ERROR_MESSAGE); } if (user2Update != null) { + ArrayList<NetworkPresence> statusesOnNetworks = user2Update.getPayload(); if (!statusesOnNetworks.isEmpty()) { ContentValues values = new ContentValues(); StringBuffer where = null; - for (NetworkPresence status : statusesOnNetworks) { - values.put(Field.LOCAL_CONTACT_ID.toString(), user2Update.getLocalContactId()); - values.put(Field.USER_ID.toString(), status.getUserId()); - values.put(Field.NETWORK_ID.toString(), status.getNetworkId()); - values.put(Field.NETWORK_STATUS.toString(), status.getOnlineStatusId()); + Iterator<NetworkPresence> itr = statusesOnNetworks.iterator(); + NetworkPresence status = null; + while (itr.hasNext()) { + status = itr.next(); + if (ignoredNetworkIds == null || !ignoredNetworkIds.contains(status.getNetworkId())) { + values.put(Field.LOCAL_CONTACT_ID.toString(), user2Update.getLocalContactId()); + values.put(Field.USER_ID.toString(), status.getUserId()); + values.put(Field.NETWORK_ID.toString(), status.getNetworkId()); + values.put(Field.NETWORK_STATUS.toString(), status.getOnlineStatusId()); - where = StringBufferPool.getStringBuffer(Field.LOCAL_CONTACT_ID.toString()); - - where.append(SQLKeys.EQUALS).append(user2Update.getLocalContactId()). - append(SQLKeys.AND).append(Field.NETWORK_ID).append(SQLKeys.EQUALS).append(status.getNetworkId()); - - int numberOfAffectedRows = writableDatabase.update(TABLE_NAME, values, StringBufferPool.toStringThenRelease(where), - null); - if (numberOfAffectedRows == 0) { - if (writableDatabase.insert(TABLE_NAME, null, values) != -1) { - ret = USER_ADDED; + where = StringBufferPool.getStringBuffer(Field.LOCAL_CONTACT_ID.toString()); + + where.append(SQLKeys.EQUALS).append(user2Update.getLocalContactId()). + append(SQLKeys.AND).append(Field.NETWORK_ID).append(SQLKeys.EQUALS).append(status.getNetworkId()); + + int numberOfAffectedRows = writableDatabase.update(TABLE_NAME, values, StringBufferPool.toStringThenRelease(where), + null); + if (numberOfAffectedRows == 0) { + if (writableDatabase.insert(TABLE_NAME, null, values) != -1) { + ret = USER_ADDED; + } else { + LogUtils.logE("PresenceTable updateUser(): could not add new user!"); + } } else { - LogUtils.logE("PresenceTable updateUser(): could not add new user!"); - } - } else { - if (ret == USER_NOTADDED) { - ret = USER_UPDATED; + if (ret == USER_NOTADDED) { + ret = USER_UPDATED; + } } + values.clear(); + } else if (ignoredNetworkIds != null) { // presence information from this network needs to be ignored + itr.remove(); } - values.clear(); } } } return ret; } /** + * This method fills the provided user object with presence information. + * + * @param user User - the user with a localContactId != -1 + * @param readableDatabase - the database to read from + * @return user/me profile presence state wrapped in "User" wrapper class, + * or NULL if the specified localContactId doesn't exist + * @throws SQLException if the database layer throws this exception. + * @throws NullPointerException if the passed in database instance is null. + */ + public static void getUserPresence(User user, + SQLiteDatabase readableDatabase) throws SQLException, NullPointerException { + if (readableDatabase == null) { + throw new NullPointerException(DEFAULT_ERROR_MESSAGE); + } + if (user.getLocalContactId() < 0) { + LogUtils.logE("PresenceTable.getUserPresenceByLocalContactId(): " + + "#localContactId# parameter is -1 "); + return; + } + Cursor c = null; + try { + c = readableDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + + Field.LOCAL_CONTACT_ID + "=" + user.getLocalContactId(), null); + + int onlineStatus = OnlineStatus.OFFLINE.ordinal(); // i.e. 0 + + user.getPayload().clear(); + + while (c.moveToNext()) { + String userId = c.getString(USER_ID); + int networkId = c.getInt(NETWORK_ID); + int statusId = c.getInt(NETWORK_STATUS); + if (statusId > onlineStatus) { + onlineStatus = statusId; + } + user.getPayload().add(new NetworkPresence(userId, networkId, statusId)); + } + user.setOverallOnline(onlineStatus); + } finally { + CloseUtils.close(c); + c = null; + } + } + + /** * This method returns user/me profile presence state. * * @param localContactId - me profile localContactId * @param readableDatabase - the database to read from * @return user/me profile presence state wrapped in "User" wrapper class, * or NULL if the specified localContactId doesn't exist * @throws SQLException if the database layer throws this exception. * @throws NullPointerException if the passed in database instance is null. + * @return user - User object filled with presence information. */ public static User getUserPresenceByLocalContactId(long localContactId, SQLiteDatabase readableDatabase) throws SQLException, NullPointerException { if (readableDatabase == null) { throw new NullPointerException(DEFAULT_ERROR_MESSAGE); } User user = null; if (localContactId < 0) { LogUtils.logE("PresenceTable.getUserPresenceByLocalContactId(): " + "#localContactId# parameter is -1 "); return user; } Cursor c = null; try { c = readableDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + Field.LOCAL_CONTACT_ID + "=" + localContactId, null); ArrayList<NetworkPresence> networkPresence = new ArrayList<NetworkPresence>(); user = new User(); int onlineStatus = OnlineStatus.OFFLINE.ordinal(); // i.e. 0 while (c.moveToNext()) { user.setLocalContactId(c.getLong(LOCAL_CONTACT_ID)); String userId = c.getString(USER_ID); int networkId = c.getInt(NETWORK_ID); int statusId = c.getInt(NETWORK_STATUS); if (statusId > onlineStatus) { onlineStatus = statusId; } networkPresence.add(new NetworkPresence(userId, networkId, statusId)); } if (!networkPresence.isEmpty()) { user.setOverallOnline(onlineStatus); user.setPayload(networkPresence); } - // this finally part should always run, while the exception is still - // thrown } finally { CloseUtils.close(c); c = null; } return user; } /** * The method cleans the presence table: deletes all the rows. * * @param writableDatabase - database to write to. * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. * @throws NullPointerException if the passed in database instance is null. */ public static int setAllUsersOffline(SQLiteDatabase writableDatabase) throws NullPointerException { if (writableDatabase == null) { throw new NullPointerException(DEFAULT_ERROR_MESSAGE); } // To remove all rows and get a count pass "1" as the whereClause return writableDatabase.delete(TABLE_NAME, "1", null); } - + + /** * The method cleans the presence table: deletes all the rows, except for * the given user localContactId ("Me Profile" localContactId) * * @param localContactIdOfMe - the localContactId of the user (long), whose * info should not be deleted * @param writableDatabase - database to write to. * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. * @throws NullPointerException if the passed in database instance is null. */ public static int setAllUsersOfflineExceptForMe(long localContactIdOfMe, SQLiteDatabase writableDatabase) throws NullPointerException { if (writableDatabase == null) { throw new NullPointerException(DEFAULT_ERROR_MESSAGE); } return writableDatabase.delete(TABLE_NAME, Field.LOCAL_CONTACT_ID + " != " + localContactIdOfMe, null); } + + /** + * This method returns the array of distinct user local contact ids in this table. + * @param readableDatabase - database. + * @return ArrayList of Long distinct local contact ids from this table. + */ + public static ArrayList<Long> getLocalContactIds(SQLiteDatabase readableDatabase) { + Cursor c = null; + ArrayList<Long> ids = new ArrayList<Long>(); + c = readableDatabase.rawQuery("SELECT DISTINCT " +Field.LOCAL_CONTACT_ID+ " FROM " + TABLE_NAME, null); + try { + while (c.moveToNext()) { + ids.add(c.getLong(0)); + } + } finally { + c.close(); + c = null; + } + return ids; + } + /** + * This method deletes information about the user presence states on the provided networks. + * @param networksToDelete - ArrayList of integer network ids. + * @param writableDatabase - writable database. + * @throws NullPointerException is thrown when the provided database is null. + */ + public static void setTPCNetworksOffline(ArrayList<Integer> networksToDelete, + SQLiteDatabase writableDatabase) throws NullPointerException { + if (writableDatabase == null) { + throw new NullPointerException(DEFAULT_ERROR_MESSAGE); + } + StringBuffer networks = StringBufferPool.getStringBuffer(); + final String COMMA = ","; + for (Integer network : networksToDelete) { + networks.append(network).append(COMMA); + } + if (networks.length() > 0) { + networks.deleteCharAt(networks.lastIndexOf(COMMA)); + } + StringBuilder where = new StringBuilder(Field.NETWORK_ID.toString()); + where.append(" IN (").append(StringBufferPool.toStringThenRelease(networks)).append(")"); + + writableDatabase.delete(TABLE_NAME, where.toString(), null); + } } diff --git a/src/com/vodafone360/people/datatypes/SystemNotification.java b/src/com/vodafone360/people/datatypes/SystemNotification.java index 6b60832..db28b4d 100644 --- a/src/com/vodafone360/people/datatypes/SystemNotification.java +++ b/src/com/vodafone360/people/datatypes/SystemNotification.java @@ -1,316 +1,325 @@ /* * 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 java.util.Vector; import com.vodafone360.people.engine.EngineManager.EngineId; import com.vodafone360.people.utils.LogUtils; /** * BaseDataType encapsulating a System notification message received from server * This message contains a code and error test and should be routed to the * approproate engine(s). */ public class SystemNotification extends PushEvent { /** * <String> "code" / <String> message code <String> "message" / <String> * message to the user Note: Currently not in scope but should be discussed, * system notifications would provide system messages, error conditions, etc */ /** * Enumeration of System Notification codes that can be returned from * Server. */ public enum SysNotificationCode { AUTH_INVALID("101"), COMMUNITY_AUTH_INVALID("102"), COMMUNITY_AUTH_VALID("103"), COMMUNITY_LOGOUT_FAILED("110"), COMMUNITY_LOGOUT_SUCCESSFUL("111"), COMMUNITY_NETWORK_LOGOUT("112"), SEND_MESSAGE_FAILED("201"), GENERIC("1000"), UNKNOWN("1001"), UNKNOWN_USER("1002"), FRIENDS_LIST_NULL("1003"), UNKNOWN_EVENT("1004"), UNKNOWN_MESSAGE_TYPE("1005"), CONVERSATION_NULL("1006"), SEND_MESSAGE_PARAMS_INVALID("1007"), SET_AVAILABILITY_PARAMS_INVALID("1008"), TOS_NULL("1009"), SMS_WAKEUP_FAILED("1010"), SMS_FAILED("1011"), UNKNOWN_CHANNEL("1012"), INVITATIONS_ACCEPT_ERROR("1013"), INVITATIONS_DENY_ERROR("1014"), CONTACTS_UPDATE_FAILED("1015"), MOBILE_REQUEST_PAYLOAD_PARSE_ERROR("1101"), EXTERNAL_HTTP_ERROR("1102"), MOBILE_EXTERNAL_PROXY("1103"), MOBILE_INTERNAL_PROXY("1104"), CHAT_HISTORY_NULL("1900"), CHAT_SUMMARY_NULL("1901"); private final String tag; /** * Constructor creating SysNotificationCode item for specified String. * * @param s String value for Tags item. */ private SysNotificationCode(String s) { tag = s; } /** * String value associated with SysNotificationCode item. * * @return String value for SysNotificationCode item. */ private String tag() { return tag; } /** * Find SysNotificationCode item for specified String. * * @param tag String value to find Tags item for. * @return SysNotificationCode item for specified String, null * otherwise. */ private static SysNotificationCode findTag(String tag) { for (SysNotificationCode tags : SysNotificationCode.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } return null; } } /** * Tags associated with SystemNotification item. */ public enum Tags { /** * The type ofthe notification. */ CODE("code"), /** * The message in the notification. */ MESSAGE("message"), /** * The message recipients address (for messages 201, 1006) */ TOS("tos"), /** * The message conversation id (for messages 201, 1006) */ - CONVERSATION("conversation"); + CONVERSATION("conversation"), + /** + * service name (for messages 111) + */ + SERVICE("service"); + private final String tag; /** * String value associated with Tags item. * * @return String value for Tags item. */ private Tags(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(String tag) { for (Tags tags : Tags.values()) { if (tag.compareTo(tags.tag()) == 0) { return tags; } } return null; } } private String code = null; private String message = null; /** * The hash of optional data, can be empty. */ private Hashtable<String, String> info = new Hashtable<String, String>(); private SysNotificationCode mSysCode; /** {@inheritDoc} */ @Override public String name() { return "SystemNotification"; } /** * Create SystemNotification message from hashtable generated by * Hessian-decoder. * * @param hash Hashtable containing SystemNotification parameters. * @param engId ID for engine this message should be routed to. * @return SystemNotification created from hashtable. */ static public SystemNotification createFromHashtable(Hashtable<String, Object> hash, EngineId engId) { SystemNotification sn = new SystemNotification(); sn.mEngineId = engId; Enumeration<String> e = hash.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); Object value = hash.get(key); Tags tag = Tags.findTag(key); sn.setValue(tag, value); } sn.setEngine(); return sn; } /** * 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) return; switch (tag) { case CODE: code = (String)value; mSysCode = SysNotificationCode.findTag((String)value); break; case MESSAGE: message = (String)value; break; case TOS: info.put(Tags.TOS.toString(), ((Vector<String>)value).firstElement()); break; case CONVERSATION: info.put(Tags.CONVERSATION.toString(), (String)value); break; + case SERVICE: + info.put(Tags.SERVICE.toString(), (String)value); + break; default: // Do nothing. break; } } /** * Set EngineId of Engine that needs to handle the System Notification. */ private void setEngine() { if (mSysCode != null) { switch (mSysCode) { case SEND_MESSAGE_FAILED: case CONVERSATION_NULL: case SEND_MESSAGE_PARAMS_INVALID: case SET_AVAILABILITY_PARAMS_INVALID: case TOS_NULL: case CHAT_HISTORY_NULL: case CHAT_SUMMARY_NULL: case COMMUNITY_AUTH_VALID: + case COMMUNITY_LOGOUT_SUCCESSFUL: mEngineId = EngineId.PRESENCE_ENGINE; LogUtils.logE("SYSTEM_NOTIFICATION:" + mSysCode + ", message:" + message); break; case EXTERNAL_HTTP_ERROR: // This error can come for thumbnail download. As of now the // download is being done in ContactSyncEngine for MeProfile // and in the Content Engine for other normal contacts. // Hence as of here this engine ID would be undefined. But // in the run() of the decoder thread, we assign the engine // ID based on the request ID. // mEngineId = EngineId.CONTACT_SYNC_ENGINE; LogUtils.logE("SYSTEM_NOTIFICATION:" + mSysCode + ", message:" + message); break; case UNKNOWN_EVENT: case UNKNOWN_MESSAGE_TYPE: case GENERIC: case UNKNOWN: LogUtils.logE("SYSTEM_NOTIFICATION:" + mSysCode + ", message:" + message); break; default: LogUtils.logE("SYSTEM_NOTIFICATION UNHANDLED:" + code + ", message:" + message); } } else { LogUtils.logE("UNEXPECTED UNHANDLED SYSTEM_NOTIFICATION:" + code + ", message:" + message); } } /** * Get current System Notification code. * * @return current System Notification code. */ public SysNotificationCode getSysCode() { return mSysCode; } /** {@inheritDoc} */ @Override public String toString() { return "SystemNotification [code=" + code + ", mSysCode=" + mSysCode + ", message=" + message + "]"; } /** * This method returns hash of optional parameters coming with this message. * @return hash Hashtable<String, String> - hash of optional parameters. */ public Hashtable<String, String> getInfo() { return info; } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java index f360b2f..49cae52 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java +++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java @@ -1,269 +1,323 @@ /* * 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 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.ContactSummary.OnlineStatus; 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; } - + /** - * Parses user data before storing it to database - * - * @param user - * @param databaseHelper - * @return + * 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 convertUserIds(User user, DatabaseHelper databaseHelper) { - if (!user.getPayload().isEmpty()) { - long localContactId = -1; - ArrayList<NetworkPresence> payload = user.getPayload(); - boolean resetOverallPresenceStatus = false; - String userId = null; - for (NetworkPresence presence : payload) { - userId = presence.getUserId(); - if (notNullOrBlank(userId)) { - int networkId = presence.getNetworkId(); - if (userId.equals(String.valueOf(getMeProfileUserId(databaseHelper)))) { - localContactId = sMeProfileLocalContactId; - // remove the PC presence - if (networkId == SocialNetwork.PC.ordinal()) { - user.getPayload().remove(presence); - resetOverallPresenceStatus = true; - break; - } - } else { - if (networkId == SocialNetwork.MOBILE.ordinal() - || (networkId == SocialNetwork.PC.ordinal())) { - localContactId = ContactsTable.fetchLocalIdFromUserId(Long - .valueOf(userId), databaseHelper.getReadableDatabase()); - } else { - localContactId = ContactDetailsTable.findLocalContactIdByKey( - SocialNetwork.getPresenceValue(networkId).toString(), userId, - ContactDetail.DetailKeys.VCARD_IMADDRESS, databaseHelper - .getReadableDatabase()); - } - if (localContactId != UiAgent.ALL_USERS) { - break; - } - } - } - } - if (resetOverallPresenceStatus) { - int max = OnlineStatus.OFFLINE.ordinal(); - for (NetworkPresence presence : user.getPayload()) { - if (presence.getOnlineStatusId() > max) - max = presence.getOnlineStatusId(); - } - user.setOverallOnline(max); - } - user.setLocalContactId(localContactId); - return true; - } - LogUtils.logE("presence data can't be parsed!!"); - return false; + 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 // TODO: this hard code needs change, must filter the identities // info by VCARD.IMADRESS Hashtable<String, String> status = new Hashtable<String, String>(); status.put("google", "online"); status.put("microsoft", "online"); status.put("mobile", "online"); status.put("facebook.com", "online"); status.put("hyves.nl", "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 users 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 modifications. */ protected static boolean updateDatabase(List<User> users, long idListeningTo, DatabaseHelper dbHelper) { - boolean contactsChanged = false; - for (User user : users) { - if (convertUserIds(user, dbHelper)) { - SQLiteDatabase writableDb = dbHelper.getWritableDatabase(); + boolean presenceChanged = false; + boolean deleteNetworks = false; + + // the list of networks presence information for me we ignore - the networks where user is offline. + ArrayList<Integer> ignoredNetworks = new ArrayList<Integer>(); - int status = PresenceTable.updateUser(user, writableDb); - if (PresenceTable.USER_NOTADDED != status) { - user = PresenceTable.getUserPresenceByLocalContactId(user.getLocalContactId(), writableDb); - if (user != null) { - ContactSummaryTable.updateOnlineStatus(user); - if (user.getLocalContactId() == idListeningTo) { - contactsChanged = true; + 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; + for (NetworkPresence presence : payload) { + userId = presence.getUserId(); + if (notNullOrBlank(userId)) { + int 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), dbHelper.getReadableDatabase()); + if (localContactId != -1) { + break; + } + } else { // 3rd party accounts + localContactId = ContactDetailsTable.findLocalContactIdByKey( + SocialNetwork.getPresenceValue(networkId).toString(), userId, + ContactDetail.DetailKeys.VCARD_IMADDRESS, dbHelper + .getReadableDatabase()); + if (localContactId != -1) { + break; + } } - } else { - LogUtils.logE("PresenceDbUtils.updateDatabase(): USER WAS NOT FOUND"); } - } else { - LogUtils.logE("PresenceDbUtils.updateDatabase(): USER WAS NOT ADDED"); } - } + // 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, dbHelper.getWritableDatabase()); + } + } + if (user.getLocalContactId() > -1) { + SQLiteDatabase writableDb = dbHelper.getWritableDatabase(); + +// 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); + + 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) { - contactsChanged = true; + presenceChanged = true; } - return contactsChanged; + return presenceChanged; } + /** + * This method alter the User wrapper fro 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); + } + } + + if (!ignoredNetworks.isEmpty()) { + return true; + } + return false; + } + + protected static boolean updateMyPresence(User user, DatabaseHelper dbHelper) { boolean contactsChanged = false; SQLiteDatabase writableDb = dbHelper.getWritableDatabase(); - if (PresenceTable.updateUser(user, writableDb) != PresenceTable.USER_NOTADDED) { + if (PresenceTable.updateUser(user, null, writableDb) != 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); } } /** * @param input * @return */ public static boolean notNullOrBlank(String input) { return (input != null) && input.length() > 0; } } diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java index 6f0edcf..a0d7714 100644 --- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java +++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java @@ -1,819 +1,823 @@ /* * 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.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.contactsync.ContactSyncEngine.IContactSyncObserver; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode; import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State; 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.LogUtils; /** * Handles the Presence life cycle */ public class PresenceEngine extends BaseEngine implements ILoginEventsListener, IContactSyncObserver, ITcpConnectionListener { /** Check every 10 minutes. **/ private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000; /** Max attempts to try. **/ - private final static int MAX_RETRY_COUNT = 3; +// private final static int MAX_RETRY_COUNT = 3; /** Reconnecting before firing offline state to the handlers. **/ private boolean mLoggedIn = false; private long mNextRuntime = -1; // private AgentState mNetworkAgentState = AgentState.CONNECTED; private DatabaseHelper mDbHelper; private int mRetryNumber; private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message) private List<TimelineSummaryItem> mFailedMessagesList; // (to, network) private boolean mContObsAdded; /** 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; /** * * @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>(); addAsContactSyncObserver(); } @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 * * @return true if everything is ready */ private boolean canRun() { return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() && EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete(); } @Override public long getNextRunTime() { if (!mContObsAdded) { addAsContactSyncObserver(); } if (!canRun()) { mNextRuntime = -1; LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:" + mNextRuntime); return mNextRuntime; } if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) { 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 (mNextRuntime == -1) { LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!"); return 0; } else { return mNextRuntime; } } @Override public void run() { LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding[" + isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime[" + mNextRuntime + "]"); 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) { if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) { if (canRun()) { getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); // Request to update the UI setNextRuntime(); } else { // check after 30 seconds LogUtils.logE("Can't run PresenceEngine before the contact" + " list is downloaded:3 - set next runtime in 30 seconds"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20; } } } else { 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); } private void setNextRuntime() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again in [" + (CHECK_FREQUENCY / (1000 * 60)) + "] minutes"); mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY; } private void setRunNow() { LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW"); mNextRuntime = 0; } @Override public void onLoginStateChanged(boolean loggedIn) { LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]"); mLoggedIn = loggedIn; if (mLoggedIn) { initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); setNextRuntime(); } else { setPresenceOffline(); mContObsAdded = false; mRetryNumber = 0; mFailedMessagesList.clear(); mSendMessagesHash.clear(); } } /*** * 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); } @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: setRunNow(); } } @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); } - //mUsers.addAll(users); } } 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++; } } if (mUsers.size() > 0) { 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 + "]"); UiAgent uiAgent = mEventCallback.getUiAgent(); if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) { uiAgent.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 (!canRun()) { LogUtils.logE("PresenceEngine.handleServerResponce(): " + "Can't run PresenceEngine before the contact list is downloaded:2"); return; } if (dataTypes != null) { for (BaseDataType mBaseDataType : dataTypes) { String name = mBaseDataType.name(); if (name.equals(PresenceList.NAME)) { handlePresenceList((PresenceList)mBaseDataType); } else if (name.equals(PushEvent.NAME)) { handlePushEvent(((PushEvent)mBaseDataType)); } else if (name.equals(Conversation.NAME)) { // a new conversation has just started handleNewConversationId((Conversation)mBaseDataType); } else if (name.equals(SystemNotification.class.getSimpleName())) { handleSystemNotification((SystemNotification)mBaseDataType); } else if (name.equals(ServerError.NAME)) { handleServerError((ServerError)mBaseDataType); } else { LogUtils.logE("PresenceEngine.handleServerResponse()" + ": response datatype not recognized:" + name); } } } else { LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!"); } } private void handlePresenceList(PresenceList presenceList) { mRetryNumber = 0; // reset time out 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:" + mRetryNumber); - if (mRetryNumber < MAX_RETRY_COUNT) { - getPresenceList(); - mRetryNumber++; - } else { - mRetryNumber = 0; - setPresenceOffline(); - } +// I believe retrying getPresenceList makes no sense, as it may "confuse" the RPG +// if (mRetryNumber < MAX_RETRY_COUNT) { +// getPresenceList(); +// mRetryNumber++; +// } else { +// mRetryNumber = 0; +// setPresenceOffline(); +// } } } private void handleNewConversationId(Conversation conversation) { if (conversation.getTos() != null) { mRetryNumber = 0; // reset time out 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: mRetryNumber = 0; // reset time out 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; case IDENTITY_CHANGE: // identity has been added or removed, reset availability initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; default: LogUtils.logE("PresenceEngine.handleServerResponse():" + " push message type was not recognized:" + event.name()); } } 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()) { LogUtils.logE("PresenceEngine.processUIRequest():" + " Can't run PresenceEngine before the contact list is downloaded:1"); return; } LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]"); switch (requestId) { case SET_MY_AVAILABILITY: if (data != null) { Presence.setMyAvailability((Hashtable<String, String>)data); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); } break; case GET_PRESENCE_LIST: Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null); completeUiRequest(ServiceStatus.SUCCESS, null); setNextRuntime(); break; case CREATE_CONVERSATION: if (data != null) { List<String> tos = ((ChatMessage)data).getTos(); LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: " + tos); Chat.startChat(tos); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; case SEND_CHAT_MESSAGE: if (data != null) { 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); // Request to update the UI completeUiRequest(ServiceStatus.SUCCESS, null); // Request to update the UI setNextRuntime(); } break; default: LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request [" + requestId.name() + "]"); } } /** * Initiate the "get presence list" request sending to server. Makes the * engine run asap. * * @return */ public void getPresenceList() { addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null); } private void initSetMyAvailabilityRequest(User myself) { if (myself == null) { LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():" + " Can't send the setAvailability request due to DB reading errors"); return; } if ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() && ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) || !canRun()) { LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():" + " return NO NETWORK CONNECTION or not ready"); return; } Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } /** * Changes the state of the engine. Also displays the login notification if * necessary. * * @param accounts */ public void setMyAvailability(Hashtable<String, String> myselfPresence) { if (myselfPresence == null) { LogUtils.logE("PresenceEngine setMyAvailability:" + " Can't send the setAvailability request due to DB reading errors"); return; } LogUtils.logV("PresenceEngine setMyAvailability() called with:" + myselfPresence); if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) { LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION"); return; } User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)), myselfPresence); Hashtable<String, String> availability = new Hashtable<String, String>(); for (NetworkPresence presence : myself.getPayload()) { availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(), OnlineStatus.getValue(presence.getOnlineStatusId()).toString()); } // set the DB values for myself myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper)); updateMyPresenceInDatabase(myself); // set the engine to run now addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability); } 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); } } } /** * 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. */ private void addAsContactSyncObserver() { if (EngineManager.getInstance() != null && EngineManager.getInstance().getContactSyncEngine() != null) { EngineManager.getInstance().getContactSyncEngine().addEventCallback(this); mContObsAdded = true; LogUtils.logD("ActivityEngine contactSync observer added."); } else { LogUtils.logE("ActivityEngine can't add to contactSync observers."); } } @Override public void onContactSyncStateChange(Mode mode, State oldState, State newState) { LogUtils.logD("PresenceEngine onContactSyncStateChange called."); } @Override public void onProgressEvent(State currentState, int percent) { if (percent == 100) { switch (currentState) { case FETCHING_SERVER_CONTACTS: LogUtils .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_CONTACTS is done"); // mDownloadServerContactsComplete = true; // break; // case SYNCING_SERVER_ME_PROFILE: // LogUtils // .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_ME_PROFILE is done"); // mDownloadMeProfileComplete = true; // break; default: // nothing to do now break; } } } @Override public void onSyncComplete(ServiceStatus status) { LogUtils.logD("PresenceEngine onSyncComplete called."); } @Override public void onConnectionStateChanged(int state) { switch (state) { case STATE_CONNECTED: + getPresenceList(); initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase()); break; case STATE_CONNECTING: case STATE_DISCONNECTED: setPresenceOffline(); mRetryNumber = 0; mFailedMessagesList.clear(); mSendMessagesHash.clear(); break; } } } diff --git a/src/com/vodafone360/people/engine/presence/User.java b/src/com/vodafone360/people/engine/presence/User.java index fba7aad..a70c941 100644 --- a/src/com/vodafone360/people/engine/presence/User.java +++ b/src/com/vodafone360/people/engine/presence/User.java @@ -1,251 +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.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; /** * 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); } /** * 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) { - // need to return aggregated status for "pc" and "mobile" - // for Vodafone 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 static ArrayList<NetworkPresence> createPayload(String userId, + 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() { return "User [mLocalContactId=" + mLocalContactId + ", mOverallOnline=" + mOverallOnline + ", mPayload=" + mPayload + "]"; } + /** + * 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/agent/NetworkAgent.java b/src/com/vodafone360/people/service/agent/NetworkAgent.java index a871314..b10f73b 100644 --- a/src/com/vodafone360/people/service/agent/NetworkAgent.java +++ b/src/com/vodafone360/people/service/agent/NetworkAgent.java @@ -1,560 +1,558 @@ /* * 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 android.widget.Toast; import com.vodafone360.people.Intents; import com.vodafone360.people.MainApplication; -import com.vodafone360.people.R; 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 }; /** * 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); 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); } } 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); } 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) { 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 */) { 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) { diff --git a/src/com/vodafone360/people/utils/HardcodedUtils.java b/src/com/vodafone360/people/utils/HardcodedUtils.java index 8e4c75f..fc97e55 100644 --- a/src/com/vodafone360/people/utils/HardcodedUtils.java +++ b/src/com/vodafone360/people/utils/HardcodedUtils.java @@ -1,57 +1,71 @@ -/* - * 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.Hashtable; - -import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; -import com.vodafone360.people.engine.presence.NetworkPresence; - -/** - * @author timschwerdtner - * Collection of hardcoded and duplicated code as a first step for refactoring. - */ -public class HardcodedUtils { - - /** - * To be used with IPeopleService.setAvailability until identity handling - * has been refactored. - * @param Desired availability state - * @return A hashtable for the set availability call - */ - public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) { - Hashtable<String, String> availability = new Hashtable<String, String>(); - - LogUtils.logD("Setting Availability to: " + onlineStatus.toString()); - // TODO: REMOVE HARDCODE setting everything possible to currentStatus - availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString()); - availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString()); - availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString()); - availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString()); - availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString()); - - return availability; - } -} +/* + * 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.ArrayList; +import java.util.Hashtable; + +import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus; +import com.vodafone360.people.engine.presence.NetworkPresence; +import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork; + +/** + * @author timschwerdtner + * Collection of hardcoded and duplicated code as a first step for refactoring. + */ +public class HardcodedUtils { + + /** + * To be used with IPeopleService.setAvailability until identity handling + * has been refactored. + * @param Desired availability state + * @return A hashtable for the set availability call + */ + public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) { + Hashtable<String, String> availability = new Hashtable<String, String>(); + + LogUtils.logD("Setting Availability to: " + onlineStatus.toString()); + // TODO: REMOVE HARDCODE setting everything possible to currentStatus + availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString()); + availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString()); + + return availability; + } + + /** + * The static list of supported TPC accounts. + */ + public static final ArrayList<Integer> THIRD_PARTY_CHAT_ACCOUNTS = new ArrayList<Integer>(); + + static { + THIRD_PARTY_CHAT_ACCOUNTS.add(SocialNetwork.FACEBOOK_COM.ordinal()); + THIRD_PARTY_CHAT_ACCOUNTS.add(SocialNetwork.GOOGLE.ordinal()); + THIRD_PARTY_CHAT_ACCOUNTS.add(SocialNetwork.HYVES_NL.ordinal()); + THIRD_PARTY_CHAT_ACCOUNTS.add(SocialNetwork.MICROSOFT.ordinal()); + } +}
360/360-Engine-for-Android
fff0a1b0b4f0fbb5c0e4c97114bb40624d7ab525
added a dot into the comment
diff --git a/src/com/vodafone360/people/engine/EngineManager.java b/src/com/vodafone360/people/engine/EngineManager.java index 85f4713..4cb717c 100644 --- a/src/com/vodafone360/people/engine/EngineManager.java +++ b/src/com/vodafone360/people/engine/EngineManager.java @@ -1,592 +1,592 @@ /* * 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 + * {@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); 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(); }
360/360-Engine-for-Android
2a8b32ba1f9e5afce6f0de4d24b95d5942435fb5
PAND-1640: Crash: NullPointerException in com.vodafone360.people - Since there is no way to be sure where exactly the exception is I decided to fix the most likely issue that the query cursor was returned as null. In all cases we need to check for null.
diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java index 7707781..ee7b775 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi1.java @@ -1,1188 +1,1203 @@ /* * 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 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 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; /** * 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(String 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#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); } } return ContactChange.INVALID_ID; } /** * 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 * @return In the Organization insertion case this should contain the new ID and in the update case should contain the existing ID */ private long updateOrganization(ContactChange[] ccList, long nabContactId) { if(mMarkedOrganizationIndex < 0 && mMarkedTitleIndex < 0) { // no organization or title to update - do nothing return ContactChange.INVALID_ID; } long detailId = ContactChange.INVALID_ID; int flags = ContactChange.FLAG_NONE; String company = null; String title = null; final Uri organizationUri = Uri.withAppendedPath( ContentUris.withAppendedId(People.CONTENT_URI, nabContactId), Contacts.Organizations.CONTENT_DIRECTORY); final Cursor cursor = mCr.query(organizationUri, null, null, null, Organizations._ID); // First retrieve the values that are already present, // assuming that the lowest id is the one in CAB try { - if(cursor.moveToNext()) { + if(cursor != null && cursor.moveToNext()) { company = CursorUtils.getString(cursor, Organizations.COMPANY); title = CursorUtils.getString(cursor, Organizations.TITLE); detailId = CursorUtils.getLong(cursor, Organizations._ID); flags = mapFromNabOrganizationType(CursorUtils.getInt(cursor, Organizations.TYPE)); final boolean isPrimary = CursorUtils.getInt(cursor, Organizations.ISPRIMARY) > 0; if(isPrimary) { flags |= ContactChange.FLAG_PREFERRED; } } } finally { CursorUtils.closeCursor(cursor); } if(mMarkedOrganizationIndex >= 0) { final ContactChange cc = ccList[mMarkedOrganizationIndex]; if(cc.getType() != ContactChange.TYPE_DELETE_DETAIL) { final String value = cc.getValue(); if(value != null) { final VCardHelper.Organisation organization = VCardHelper.getOrg(value); if(!TextUtils.isEmpty(organization.name)) { company = organization.name; } } flags = cc.getFlags(); } else { // Delete case company = null; } } if(mMarkedTitleIndex >= 0) { final ContactChange cc = ccList[mMarkedTitleIndex]; title = cc.getValue(); if(cc.getType() != ContactChange.TYPE_DELETE_DETAIL) { flags = cc.getFlags(); } } if(company != null || title != null) { mValues.clear(); /* 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(Organizations.LABEL, (String)null); mValues.put(Organizations.COMPANY, company); mValues.put(Organizations.TITLE, title); mValues.put(Organizations.TYPE, mapToNabOrganizationType(flags)); mValues.put(Organizations.ISPRIMARY, flags & ContactChange.FLAG_PREFERRED); final Uri existingUri = ContentUris.withAppendedId(Contacts.Organizations.CONTENT_URI, detailId); if(detailId != ContactChange.INVALID_ID) { mCr.update(existingUri, mValues, null, null); } else { // insert final Uri idUri = mCr.insert(organizationUri, mValues); if(idUri != null) { return ContentUris.parseId(idUri); } } } else if (detailId != ContactChange.INVALID_ID) { final Uri existingUri = ContentUris.withAppendedId(Contacts.Organizations.CONTENT_URI, detailId); mCr.delete(existingUri, null, null); } else { mMarkedOrganizationIndex = mMarkedTitleIndex = -1; } // Updated detail id or ContactChange.INVALID_ID if deleted return detailId; } /** * 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 Phones.TYPE_HOME: return ContactChange.FLAG_HOME; case Phones.TYPE_MOBILE: return ContactChange.FLAG_CELL; case Phones.TYPE_WORK: return ContactChange.FLAG_WORK; case Phones.TYPE_FAX_HOME: return ContactChange.FLAGS_HOME_FAX; case Phones.TYPE_FAX_WORK: return ContactChange.FLAGS_WORK_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_HOME_FAX) == ContactChange.FLAGS_HOME_FAX) { return Phones.TYPE_FAX_HOME; } if((flags & ContactChange.FLAGS_WORK_FAX) == ContactChange.FLAGS_WORK_FAX) { return Phones.TYPE_FAX_WORK; } if((flags & ContactChange.FLAG_HOME) == ContactChange.FLAG_HOME) { return Phones.TYPE_HOME; } if((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return Phones.TYPE_WORK; } if((flags & ContactChange.FLAG_CELL) == ContactChange.FLAG_CELL) { return Phones.TYPE_MOBILE; } return Phones.TYPE_OTHER; } /** * Maps a method type from the native value into the {@link ContactChange} flags * @param nabType Native method type * @return {@link ContactChange} flags */ private static int mapFromNabContactMethodType(int nabType) { switch(nabType) { case ContactMethods.TYPE_HOME: return ContactChange.FLAG_HOME; case ContactMethods.TYPE_WORK: return ContactChange.FLAG_WORK; } return ContactChange.FLAG_NONE; } /** * Maps {@link ContactChange} flags into the native method type. * @param flags {@link ContactChange} flags * @return Native method type */ private static int mapToNabContactMethodType(int flags) { if((flags & ContactChange.FLAG_HOME) == ContactChange.FLAG_HOME) { return ContactMethods.TYPE_HOME; } if((flags & ContactChange.FLAG_WORK) == ContactChange.FLAG_WORK) { return ContactMethods.TYPE_WORK; } return ContactMethods.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 == Organizations.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 Organizations.TYPE_WORK; } return Organizations.TYPE_OTHER; } /** * Utility method used to parse a raw display Address * into a {@link VCardHelper.PostalAddress} object. * The purpose of this method is simply to remove '\n' separators. * It does not aim to correctly map * address components to the right place, e.g. it is not guaranteed * that 'PostalAddress.Country' will really be the Country. */ private static PostalAddress parseRawAddress(String rawAddress) { final PostalAddress address = new PostalAddress(); final String[] tokens = rawAddress.trim().split("\n"); final int numTokens = tokens.length; address.addressLine1 = tokens[0]; if(numTokens > 1) { address.addressLine2 = tokens[1]; } if(numTokens > 2) { address.city = tokens[2]; } if(numTokens > 3) { address.county = tokens[3]; } if(numTokens > 4) { address.postCode = tokens[4]; } if(numTokens > 5) { address.country = tokens[5]; } if(numTokens > 6) { final StringBuilder sb = new StringBuilder(); sb.append(tokens[6]); for(int i = 7; i < numTokens; i++) { sb.append(' '); sb.append(tokens[i]); } address.postOfficeBox = sb.toString(); } return address; } } diff --git a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java index 5e02026..088b78d 100644 --- a/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java +++ b/src/com/vodafone360/people/engine/contactsync/NativeContactsApi2.java @@ -1,2072 +1,2081 @@ /* * 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 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.LogUtils; import com.vodafone360.people.utils.CursorUtils; import com.vodafone360.people.utils.VersionUtils; import dalvik.system.PathClassLoader; 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.Event; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Website; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.text.TextUtils; import android.util.SparseArray; /** * 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 }; /** * 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() { fetchMyContactsGroupRowIds(); } /** * @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; } /** * @see NativeContactsApi2#getAccountsByType(String) */ @Override public Account[] getAccountsByType(String type) { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts2xApi = accountMan.getAccountsByType(type); 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; } 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); 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); } return isAdded; } /** * @see NativeContactsApi#isPeopleAccountCreated() */ @Override public boolean isPeopleAccountCreated() { AccountManager accountMan = AccountManager.get(mContext); android.accounts.Account[] accounts = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE); 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); 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.getCount() > 0) { + 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) || 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.getCount() > 0; + 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. * @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); 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.moveToNext()) { + 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); 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; } }
360/360-Engine-for-Android
1992271a694fe7eee55207fa62e55d864f699952
- suited tests/build.xml for blocking unit tests
diff --git a/tests/build.xml b/tests/build.xml index 87ceb78..f808c93 100644 --- a/tests/build.xml +++ b/tests/build.xml @@ -1,696 +1,697 @@ <?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <project name="tests"> <property environment="env"/> <!-- The build.properties file can be created by you and is never touched by the 'android' tool. This is the place to change some of the default property values used by the Ant rules. Here are some properties you may want to change/update: application.package the name of your application package as defined in the manifest. Used by the 'uninstall' rule. source.dir the name of the source directory. Default is 'src'. out.dir the name of the output directory. Default is 'bin'. Properties related to the SDK location or the project target should be updated using the 'android' tool with the 'update' action. This file is an integral part of the build system for your application and should be checked in in Version Control Systems. --> <property file="build.properties" /> <!-- The default.properties file is created and updated by the 'android' tool, as well as ADT. This file is an integral part of the build system for your application and should be checked in in Version Control Systems. --> <property file="default.properties" /> <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it already on your system, please do so. After setting it, create a new properties file in build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties to it. --> <property file="../build_property_files/${env.USERNAME_360}.properties" /> <echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the XMLTask is found in ${xml.task.dir}...</echo> <!-- Custom Android task to deal with the project target, and import the proper rules. This requires ant 1.6.0 or above. --> <path id="android.antlibs"> <pathelement path="${sdk.dir}/tools/lib/anttasks.jar" /> <pathelement path="${sdk.dir}/tools/lib/sdklib.jar" /> <pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" /> <pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" /> <pathelement path="${sdk.dir}/tools/lib/jarutils.jar" /> </path> <taskdef name="setup" classname="com.android.ant.SetupTask" classpathref="android.antlibs" /> <!-- Execute the Android Setup task that will setup some properties specific to the target, and import the build rules files. The rules file is imported from <SDK>/platforms/<target_platform>/templates/android_rules.xml To customize some build steps for your project: - copy the content of the main node <project> from android_rules.xml - paste it in this build.xml below the <setup /> task. - disable the import by changing the setup task below to <setup import="false" /> This will ensure that the properties are setup correctly but that your customized build steps are used. --> <setup import="false" /> <!-- EMMA Coverage interface for build script --> <target name="emma-coverage-interface"> <echo>EMMA Coverage interface for build script.</echo> <ant target="coverage" /> </target> <!-- JUunit interface for build script --> - <target name="run-tests-interface"> + <target name="run-tests-interface" depends="-dirs"> <echo>JUunit interface for build script.</echo> <ant target="run-tests" /> </target> <!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############ This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be run inside the build script without path issues. --> <!-- This rules file is meant to be imported by the custom Ant task: com.android.ant.AndroidInitTask The following properties are put in place by the importing task: android.jar, android.aidl, aapt, aidl, and dx Additionnaly, the task sets up the following classpath reference: android.target.classpath This is used by the compiler task as the boot classpath. --> <!-- Custom tasks --> <taskdef name="aaptexec" classname="com.android.ant.AaptExecLoopTask" classpathref="android.antlibs" /> <taskdef name="apkbuilder" classname="com.android.ant.ApkBuilderTask" classpathref="android.antlibs" /> <taskdef name="xpath" classname="com.android.ant.XPathTask" classpathref="android.antlibs" /> <!-- Properties --> <!-- Tells adb which device to target. You can change this from the command line by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for the emulator. --> <property name="adb.device.arg" value="" /> <property name="android.tools.dir" location="${sdk.dir}/tools" /> <!-- Name of the application package extracted from manifest file --> <xpath input="AndroidManifest.xml" expression="/manifest/@package" output="manifest.package" /> <!-- Input directories --> <property name="source.dir" value="src" /> <property name="source.absolute.dir" location="${source.dir}" /> <property name="gen.dir" value="gen" /> <property name="gen.absolute.dir" location="${gen.dir}" /> <property name="resource.dir" value="res" /> <property name="resource.absolute.dir" location="${resource.dir}" /> <property name="asset.dir" value="assets" /> <property name="asset.absolute.dir" location="${asset.dir}" /> <!-- Directory for the third party java libraries --> <property name="external.libs.dir" value="libs" /> <property name="external.libs.absolute.dir" location="${external.libs.dir}" /> <!-- Directory for the native libraries --> <property name="native.libs.dir" value="libs" /> <property name="native.libs.absolute.dir" location="${native.libs.dir}" /> <!-- Output directories --> <property name="out.dir" value="bin" /> <property name="out.absolute.dir" location="${out.dir}" /> <property name="out.classes.dir" value="${out.absolute.dir}/classes" /> <property name="out.classes.absolute.dir" location="${out.classes.dir}" /> <!-- Intermediate files --> <property name="dex.file.name" value="classes.dex" /> <property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" /> <!-- The final package file to generate --> <property name="out.debug.unaligned.package" location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" /> <property name="out.debug.package" location="${out.absolute.dir}/${ant.project.name}-debug.apk" /> <property name="out.unsigned.package" location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" /> <property name="out.unaligned.package" location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" /> <property name="out.release.package" location="${out.absolute.dir}/${ant.project.name}-release.apk" /> <!-- Verbosity --> <property name="verbose" value="false" /> <!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false' The property 'verbosity' is not user configurable and depends exclusively on 'verbose' value.--> <condition property="verbosity" value="verbose" else="quiet"> <istrue value="${verbose}" /> </condition> <!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose' --> <condition property="v.option" value="-v" else=""> <istrue value="${verbose}" /> </condition> <!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' --> <condition property="verbose.option" value="--verbose" else=""> <istrue value="${verbose}" /> </condition> <!-- Tools --> <condition property="exe" value=".exe" else=""><os family="windows" /></condition> <property name="adb" location="${android.tools.dir}/adb${exe}" /> <property name="zipalign" location="${android.tools.dir}/zipalign${exe}" /> <!-- Emma configuration --> <property name="emma.dir" value="${sdk.dir}/tools/lib" /> <path id="emma.lib"> <pathelement location="${emma.dir}/emma.jar" /> <pathelement location="${emma.dir}/emma_ant.jar" /> </path> <taskdef resource="emma_ant.properties" classpathref="emma.lib" /> <!-- End of emma configuration --> <!-- Macros --> <!-- Configurable macro, which allows to pass as parameters output directory, output dex filename and external libraries to dex (optional) --> <macrodef name="dex-helper"> <element name="external-libs" optional="yes" /> <element name="extra-parameters" optional="yes" /> <sequential> <echo>Converting compiled files and external libraries into ${intermediate.dex.file}... </echo> <apply executable="${dx}" failonerror="true" parallel="true"> <arg value="--dex" /> <arg value="--output=${intermediate.dex.file}" /> <extra-parameters /> <arg line="${verbose.option}" /> <arg path="${out.classes.absolute.dir}" /> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> <external-libs /> </apply> </sequential> </macrodef> <!-- This is macro that enable passing variable list of external jar files to ApkBuilder Example of use: <package-helper> <extra-jars> <jarfolder path="my_jars" /> <jarfile path="foo/bar.jar" /> <jarfolder path="your_jars" /> </extra-jars> </package-helper> --> <macrodef name="package-helper"> <attribute name="sign.package" /> <element name="extra-jars" optional="yes" /> <sequential> <apkbuilder outfolder="${out.absolute.dir}" basename="${ant.project.name}" signed="@{sign.package}" verbose="${verbose}"> <file path="${intermediate.dex.file}" /> <sourcefolder path="${source.absolute.dir}" /> <nativefolder path="${native.libs.absolute.dir}" /> <jarfolder path="${external.libs.absolute.dir}" /> <extra-jars/> </apkbuilder> </sequential> </macrodef> <!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets debug, -debug-with-emma and release.--> <macrodef name="zipalign-helper"> <attribute name="in.package" /> <attribute name="out.package" /> <sequential> <echo>Running zip align on final apk...</echo> <exec executable="${zipalign}" failonerror="true"> <arg line="${v.option}" /> <arg value="-f" /> <arg value="4" /> <arg path="@{in.package}" /> <arg path="@{out.package}" /> </exec> </sequential> </macrodef> <!-- This is macro used only for sharing code among two targets, -install and -install-with-emma which do exactly the same but differ in dependencies --> <macrodef name="install-helper"> <sequential> <echo>Installing ${out.debug.package} onto default emulator or device...</echo> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="install" /> <arg value="-r" /> <arg path="${out.debug.package}" /> </exec> </sequential> </macrodef> <!-- Rules --> <!-- Creates the output directories if they don't exist yet. --> <target name="-dirs"> <echo>Creating output directories if needed...</echo> <mkdir dir="${resource.absolute.dir}" /> <mkdir dir="${external.libs.absolute.dir}" /> <mkdir dir="${gen.absolute.dir}" /> <mkdir dir="${out.absolute.dir}" /> <mkdir dir="${out.classes.absolute.dir}" /> + <mkdir dir="${tested.project.absolute.dir}/output/" /> </target> <!-- Generates the R.java file for this project's resources. --> <target name="-resource-src" depends="-dirs"> <echo>Generating R.java / Manifest.java from the resources...</echo> <exec executable="${aapt}" failonerror="true"> <arg value="package" /> <arg line="${v.option}" /> <arg value="-m" /> <arg value="-J" /> <arg path="${gen.absolute.dir}" /> <arg value="-M" /> <arg path="AndroidManifest.xml" /> <arg value="-S" /> <arg path="${resource.absolute.dir}" /> <arg value="-I" /> <arg path="${android.jar}" /> </exec> </target> <!-- Generates java classes from .aidl files. --> <target name="-aidl" depends="-dirs"> <echo>Compiling aidl files into Java classes...</echo> <apply executable="${aidl}" failonerror="true"> <arg value="-p${android.aidl}" /> <arg value="-I${source.absolute.dir}" /> <arg value="-o${gen.absolute.dir}" /> <fileset dir="${source.absolute.dir}"> <include name="**/*.aidl" /> </fileset> </apply> </target> <!-- Compiles this project's .java files into .class files. --> <target name="compile" depends="-resource-src, -aidl" description="Compiles project's .java files into .class files"> <!-- If android rules are used for a test project, its classpath should include tested project's location --> <condition property="extensible.classpath" value="${tested.project.absolute.dir}/bin/classes" else="."> <isset property="tested.project.absolute.dir" /> </condition> <echo>extensible.classpath: ${extensible.classpath}</echo> <javac encoding="ascii" target="1.5" debug="true" extdirs="" destdir="${out.classes.absolute.dir}" bootclasspathref="android.target.classpath" verbose="${verbose}" classpath="${extensible.classpath}"> <src path="${source.absolute.dir}" /> - <src path="../../${ui.project.name}/${source.dir}" /> <src path="${gen.absolute.dir}" /> <classpath> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> </classpath> </javac> </target> <!-- Converts this project's .class files into .dex files --> <target name="-dex" depends="compile"> <dex-helper /> </target> <!-- Puts the project's resources into the output package file This actually can create multiple resource package in case Some custom apk with specific configuration have been declared in default.properties. --> <target name="-package-resources"> <echo>Packaging resources</echo> <aaptexec executable="${aapt}" command="package" manifest="AndroidManifest.xml" resources="${resource.absolute.dir}" assets="${asset.absolute.dir}" androidjar="${android.jar}" outfolder="${out.absolute.dir}" basename="${ant.project.name}" /> </target> <!-- Packages the application and sign it with a debug key. --> <target name="-package-debug-sign" depends="-dex, -package-resources"> <package-helper sign.package="true" /> </target> <!-- Packages the application without signing it. --> <target name="-package-no-sign" depends="-dex, -package-resources"> <package-helper sign.package="false" /> </target> <target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again"> <subant target="compile"> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <!-- Builds debug output package, provided all the necessary files are already dexed --> <target name="debug" depends="-compile-tested-if-test, -package-debug-sign" description="Builds the application and signs it with a debug key."> <zipalign-helper in.package="${out.debug.unaligned.package}" out.package="${out.debug.package}" /> <echo>Debug Package: ${out.debug.package}</echo> </target> <target name="-release-check"> <condition property="release.sign"> <and> <isset property="key.store" /> <isset property="key.alias" /> </and> </condition> </target> <target name="-release-nosign" depends="-release-check" unless="release.sign"> <echo>No key.store and key.alias properties found in build.properties.</echo> <echo>Please sign ${out.unsigned.package} manually</echo> <echo>and run zipalign from the Android SDK tools.</echo> </target> <target name="release" depends="-package-no-sign, -release-nosign" if="release.sign" description="Builds the application. The generated apk file must be signed before it is published."> <!-- Gets passwords --> <input message="Please enter keystore password (store:${key.store}):" addproperty="key.store.password" /> <input message="Please enter password for alias '${key.alias}':" addproperty="key.alias.password" /> <!-- Signs the APK --> <echo>Signing final apk...</echo> <signjar jar="${out.unsigned.package}" signedjar="${out.unaligned.package}" keystore="${key.store}" storepass="${key.store.password}" alias="${key.alias}" keypass="${key.alias.password}" verbose="${verbose}" /> <!-- Zip aligns the APK --> <zipalign-helper in.package="${out.unaligned.package}" out.package="${out.release.package}" /> <echo>Release Package: ${out.release.package}</echo> </target> <target name="install" depends="debug" description="Installs/reinstalls the debug package onto a running emulator or device. If the application was previously installed, the signatures must match." > <install-helper /> </target> <target name="-uninstall-check"> <condition property="uninstall.run"> <isset property="manifest.package" /> </condition> </target> <target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run"> <echo>Unable to run 'ant uninstall', manifest.package property is not defined. </echo> </target> <!-- Uninstalls the package from the default emulator/device --> <target name="uninstall" depends="-uninstall-error" if="uninstall.run" description="Uninstalls the application from a running emulator or device."> <echo>Uninstalling ${manifest.package} from the default emulator or device...</echo> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="uninstall" /> <arg value="${manifest.package}" /> </exec> </target> <target name="clean" description="Removes output files created by other targets."> <delete dir="${out.absolute.dir}" verbose="${verbose}" /> <delete dir="${gen.absolute.dir}" verbose="${verbose}" /> </target> <!-- Targets for code-coverage measurement purposes, invoked from external file --> <!-- Emma-instruments tested project classes (compiles the tested project if necessary) and writes instrumented classes to ${instrumentation.absolute.dir}/classes --> <target name="-emma-instrument" depends="compile"> <echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo> <!-- It only instruments class files, not any external libs --> <emma enabled="true"> <instr verbosity="${verbosity}" mode="overwrite" instrpath="${out.absolute.dir}/classes" outdir="${out.absolute.dir}/classes"> </instr> <!-- TODO: exclusion filters on R*.class and allowing custom exclusion from user defined file --> </emma> </target> <target name="-dex-instrumented" depends="-emma-instrument"> <dex-helper> <extra-parameters> <arg value="--no-locals" /> </extra-parameters> <external-libs> <fileset file="${emma.dir}/emma_device.jar" /> </external-libs> </dex-helper> </target> <!-- Invoked from external files for code coverage purposes --> <target name="-package-with-emma" depends="-dex-instrumented, -package-resources"> <package-helper sign.package="true"> <extra-jars> <!-- Injected from external file --> <jarfile path="${emma.dir}/emma_device.jar" /> </extra-jars> </package-helper> </target> <target name="-debug-with-emma" depends="-package-with-emma"> <zipalign-helper in.package="${out.debug.unaligned.package}" out.package="${out.debug.package}" /> </target> <target name="-install-with-emma" depends="-debug-with-emma"> <install-helper /> </target> <!-- End of targets for code-coverage measurement purposes --> <target name="help"> <!-- displays starts at col 13 |13 80| --> <echo>Android Ant Build. Available targets:</echo> <echo> help: Displays this help.</echo> <echo> clean: Removes output files created by other targets.</echo> <echo> compile: Compiles project's .java files into .class files.</echo> <echo> debug: Builds the application and signs it with a debug key.</echo> <echo> release: Builds the application. The generated apk file must be</echo> <echo> signed before it is published.</echo> <echo> install: Installs/reinstalls the debug package onto a running</echo> <echo> emulator or device.</echo> <echo> If the application was previously installed, the</echo> <echo> signatures must match.</echo> <echo> uninstall: Uninstalls the application from a running emulator or</echo> <echo> device.</echo> </target> <!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ --> <!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## --> <property name="tested.project.absolute.dir" location="${tested.project.dir}" /> - <property name="junit.out.file" value="${tested.project.absolute.dir}\output\junit-result.txt" /> + <property name="junit.out.file" value="${tested.project.absolute.dir}/output/junit-result.txt" /> <property name="instrumentation.dir" value="instrumented" /> <property name="instrumentation.absolute.dir" location="${instrumentation.dir}" /> <property name="test.runner" value="android.test.InstrumentationTestRunner" /> <!-- Application package of the tested project extracted from its manifest file --> <xpath input="${tested.project.absolute.dir}/AndroidManifest.xml" expression="/manifest/@package" output="tested.manifest.package" /> <!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated project --> <property name="emma.dump.file" value="/data/data/${tested.manifest.package}/files/coverage.ec" /> <macrodef name="run-tests-helper"> <attribute name="emma.enabled" default="false" /> <element name="extra-instrument-args" optional="yes" /> <sequential> <echo>Running tests with output sent to ${junit.out.file}...</echo> + <exec executable="${adb}" failonerror="true" output="${junit.out.file}"> <arg value="shell" /> <arg value="am" /> <arg value="instrument" /> <arg value="-w" /> <arg value="-r" /> <!-- XML output --> <arg value="-e" /> <arg value="coverage" /> <arg value="@{emma.enabled}" /> <extra-instrument-args /> <arg value="${manifest.package}/${test.runner}" /> </exec> <loadfile srcfile="${junit.out.file}" property="result"> <filterchain> <linecontains> <contains value="INSTRUMENTATION_CODE: -1"/> </linecontains> </filterchain> </loadfile> <loadfile srcfile="${junit.out.file}" property="result2"> <filterchain> <linecontains> <contains value="FAILURES"/> </linecontains> </filterchain> </loadfile> <echo>Result ${result} ${result2}</echo> <loadfile property="junit-out-file" srcFile="${junit.out.file}"/> <echo>Junit results...</echo> <echo>${junit-out-file}</echo> <fail unless="result">JUnit tests failed, please look at ${junit.out.file} for more information.</fail> <fail if="result2">JUnit tests failed, please look at ${junit.out.file} for more information.</fail> </sequential> </macrodef> <!-- Invoking this target sets the value of extensible.classpath, which is being added to javac classpath in target 'compile' (android_rules.xml) --> <target name="-set-coverage-classpath"> <property name="extensible.classpath" location="${instrumentation.absolute.dir}/classes" /> </target> <!-- Ensures that tested project is installed on the device before we run the tests. Used for ordinary tests, without coverage measurement --> <target name="-install-tested-project"> <property name="do.not.compile.again" value="true" /> <subant target="install"> <property name="sdk.dir" location="${sdk.dir}"/> <property name="sdk-location" location="${sdk-location}"/> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <target name="run-tests" depends="-install-tested-project, install" description="Runs tests from the package defined in test.package property"> <run-tests-helper /> </target> <target name="-install-instrumented"> <property name="do.not.compile.again" value="true" /> <subant target="-install-with-emma"> <property name="out.absolute.dir" value="${instrumentation.absolute.dir}" /> <property name="sdk.dir" location="${sdk.dir}"/> <property name="sdk-location" location="${sdk-location}"/> <fileset dir="${tested.project.absolute.dir}" includes="build.xml" /> </subant> </target> <target name="coverage" depends="-set-coverage-classpath, -install-instrumented, install" description="Runs the tests against the instrumented code and generates code coverage report"> <run-tests-helper emma.enabled="true"> <extra-instrument-args> <arg value="-e" /> <arg value="coverageFile" /> <arg value="${emma.dump.file}" /> </extra-instrument-args> </run-tests-helper> <echo>Downloading coverage file into project directory...</echo> <exec executable="${adb}" failonerror="true"> <arg value="pull" /> <arg value="${emma.dump.file}" /> <arg value="coverage.ec" /> </exec> <echo>#################### INSERTED CODE #####################</echo> <move file="${tested.project.absolute.dir}/coverage.em" tofile="${tested.project.absolute.dir}/tests/coverage.em"/> <echo>#################### INSERTED CODE #####################</echo> <echo>Extracting coverage report...</echo> <emma> <report sourcepath="${tested.project.absolute.dir}/${source.dir}" verbosity="${verbosity}"> <!-- TODO: report.dir or something like should be introduced if necessary --> <infileset dir="."> <include name="coverage.ec" /> <include name="coverage.em" /> </infileset> <!-- TODO: reports in other, indicated by user formats --> <html outfile="coverage.html" /> </report> </emma> <echo>Cleaning up temporary files...</echo> <delete dir="${instrumentation.absolute.dir}" /> <delete file="coverage.ec" /> <delete file="coverage.em" /> <echo>Saving the report file in ${basedir}/coverage/coverage.html</echo> </target> <!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## --> </project> \ No newline at end of file