List of usage examples for android.content ContentProviderClient applyBatch
public @NonNull ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations) throws RemoteException, OperationApplicationException
From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java
/** * We know that the group exists locally, so we can use the data in the JSON group as gold * @param group// w ww . j a v a2s.c o m * @param provider * @param authToken * @param account * @param syncResult * @throws JSONException * @throws RemoteException * @throws OperationApplicationException */ private void optimisticallyAddContactsToExistingGroup(JSONObject group, ContentProviderClient provider, String authToken, Account account, SyncResult syncResult) throws JSONException, RemoteException { if (!group.has(JSONKeys.KEY_MEMBERS)) { return; } String groupCloudId = group.getString(JSONKeys.KEY_ID); Cursor groupCursor = provider.query(GMSGroups.CONTENT_URI, new String[] { GMSGroup._ID, GMSGroup.CLOUD_ID }, GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }, null); try { if (groupCursor == null || 1 != groupCursor.getCount() || !groupCursor.moveToFirst()) { syncResult.databaseError = true; return; } long groupId = groupCursor.getLong(0); if (groupId < 0L) { syncResult.databaseError = true; return; } // Optimistically add the contacts JSONArray membersArray = group.getJSONArray(JSONKeys.KEY_MEMBERS); for (int j = 0; j < membersArray.length(); ++j) { JSONObject member = membersArray.getJSONObject(j); ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); // If the first operation asserts it means the contact exists already // Operation 0 ContentProviderOperation op = ContentProviderOperation.newAssertQuery(GMSContacts.CONTENT_URI) .withSelection(GMSContact.CLOUD_ID + "=? AND " + GMSContact.GROUP_ID + "=?", new String[] { member.getString(JSONKeys.KEY_ID), String.valueOf(groupId) }) .withExpectedCount(0).build(); ops.add(op); op = ContentProviderOperation.newInsert(GMSContacts.CONTENT_URI) .withValues(GMSApplication.getMemberValues(member)).withValue(GMSContact.GROUP_ID, groupId) .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).build(); ops.add(op); try { @SuppressWarnings("unused") ContentProviderResult[] results = provider.applyBatch(ops); } catch (OperationApplicationException e) { // The contact already exists, so we'll optionally update it, based on its version Cursor contactCursor = null; try { contactCursor = provider.query(GMSContacts.CONTENT_URI, new String[] { GMSContact._ID, GMSContact.CLOUD_ID, GMSContact.GROUP_ID }, GMSContact.CLOUD_ID + "=? AND " + GMSContact.GROUP_ID + "=?", new String[] { member.getString(JSONKeys.KEY_ID), String.valueOf(groupId) }, null); if (contactCursor == null || !contactCursor.moveToFirst()) { syncResult.databaseError = true; return; } // The member already exists, so optinally update it ops = new ArrayList<ContentProviderOperation>(); // Operation 0 - we know it exists. If its the right version, we don't need to do the update // So we assert that we'll find zero records with the current version and if that's right, we'll update our // record, including the version with the new record data op = ContentProviderOperation .newAssertQuery(ContentUris.withAppendedId(GMSContacts.CONTENT_URI, contactCursor.getLong(0))) .withSelection(GMSContact.VERSION + "=?", new String[] { member.getString(JSONKeys.KEY_VERSION) }) .withExpectedCount(0).build(); ops.add(op); op = ContentProviderOperation .newUpdate(ContentUris.withAppendedId(GMSContacts.CONTENT_URI, contactCursor.getLong(0))) .withValues(GMSApplication.getMemberValues(member)) .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).withExpectedCount(1) .build(); ops.add(op); provider.applyBatch(ops); } catch (OperationApplicationException l) { ops = new ArrayList<ContentProviderOperation>(); // Operation 0 - we know it exists and is of the current version, so no update of attributes is needed // We still have to update the status to SYNCED so we don't blow it away later. op = ContentProviderOperation .newUpdate(ContentUris.withAppendedId(GMSContacts.CONTENT_URI, contactCursor.getLong(0))) .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).withExpectedCount(1) .build(); ops.add(op); try { provider.applyBatch(ops); } catch (OperationApplicationException e1) { syncResult.stats.numSkippedEntries++; e1.printStackTrace(); } } finally { if (contactCursor != null) { contactCursor.close(); } } } } } finally { if (groupCursor != null) { groupCursor.close(); } } }
From source file:com.taxicop.sync.SyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {/*w w w . j a v a 2 s. com*/ USER = queryUser(provider); Log.i(TAG, "onPerformSync: Start"); NetworkUtilities.reset(); FROM = queryLastId(provider); Log.d(TAG, "data from= " + FROM); ArrayList<Complaint> queries = query(provider, FROM); NetworkUtilities.add(USER); for (Complaint c : queries) { NetworkUtilities.add(c.RANKING, c.CAR_PLATE, c.DESCRIPTION, c.USER, c.DATE); } Log.d(TAG, "from= " + FROM + " size del query= " + queries.size()); String response = null; if (NetworkUtilities.adapter.size() > 0) { response = ":" + NetworkUtilities.process_upload(); Log.i(TAG, "response: " + response); } else Log.i(TAG, "no data"); if (USER != null) { NetworkUtilities.reset(); NetworkUtilities.add(USER); NetworkUtilities.add(FROM); response = null; if (NetworkUtilities.adapter.size() > 0) { response = NetworkUtilities.process_download(); Log.d(TAG, "" + response); } else Log.e(TAG, "no data"); try { if (response != null) { final JSONArray cars = new JSONArray(response); provider.delete(PlateContentProvider.URI_REPORT, null, null); Log.i(TAG, "" + response); for (int i = 0; i < cars.length(); i++) { JSONObject COMPLETE = cars.getJSONObject(i); JSONObject e1 = COMPLETE.getJSONObject("fields"); float rank = (float) e1.getDouble(Fields.RANKING); String car = e1.getString(Fields.CAR_PLATE); String desc = e1.getString(Fields.DESCRIPTION); String date = e1.getString(Fields.DATE_REPORT); ContentValues in = new ContentValues(); in.put(Fields.ID_KEY, i); in.put(Fields.CAR_PLATE, car); in.put(Fields.RANKING, rank); in.put(Fields.DATE_REPORT, date); in.put(Fields.DESCRIPTION, desc); insert.add(in); } Log.d(TAG, "current ammount to insert= " + insert.size() + ", FROM=" + FROM); ContentValues upd = new ContentValues(); upd.put(Fields.ITH, insert.size()); upd.put(Fields.ID_USR, USER); provider.update(PlateContentProvider.URI_USERS, upd, "" + Fields.ID_USR + " = '" + USER + "'", null); //if(insert.size()>FROM) provider.applyBatch(insertData()); insert.clear(); } else { Log.e(TAG, "null response"); } } catch (Exception e) { Log.e(TAG, "inserting .... fucked => message: " + e.getMessage()); } } }
From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java
private void deleteUnsyncedItems(ContentProviderClient provider, Account account, SyncResult syncResult) throws RemoteException, JSONException { Log.d(TAG, "Delete unsynced items before count: " + syncResult.stats.numDeletes); ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ContentProviderOperation op;/*w ww . j av a2 s. c om*/ ContentProviderResult[] results; // This is the good part Cursor unsyncedGroupsCursor = null; try { final String SELECT = GMSGroup.STATUS + " ISNULL OR " + GMSGroup.STATUS + " != " + GMSGroup.STATUS_SYNCED; unsyncedGroupsCursor = provider.query(GMSGroups.CONTENT_URI, new String[] { GMSGroup._ID, GMSGroup.CLOUD_ID, GMSGroup.STATUS, GMSGroup.NAME, GMSGroup.RAW_CONTACT_ID }, SELECT, null, null); ContentProviderClient contactsProvider; if (unsyncedGroupsCursor.moveToFirst()) { contactsProvider = getContext().getContentResolver() .acquireContentProviderClient(ContactsContract.AUTHORITY); do { long groupId = unsyncedGroupsCursor.getLong(0); long groupRawContactId = unsyncedGroupsCursor.getLong(4); Cursor memberCursor = null; try { memberCursor = provider.query(GMSContacts.CONTENT_URI, new String[] { GMSContact._ID, GMSContact.GROUP_ID }, GMSContact.GROUP_ID + "=?", new String[] { String.valueOf(groupId) }, null); while (memberCursor.moveToNext()) { op = ContentProviderOperation.newDelete( ContentUris.withAppendedId(GMSContacts.CONTENT_URI, memberCursor.getLong(0))) .build(); ops.add(op); } } finally { if (memberCursor != null) { memberCursor.close(); } } op = ContentProviderOperation .newDelete(ContentUris.withAppendedId(GMSGroups.CONTENT_URI, groupId)).build(); ops.add(op); if (groupRawContactId <= 0) { Cursor accountContactsCursor = null; try { String sourceId = unsyncedGroupsCursor.getString(1); Log.d(TAG, String.format("Unsynced Group Id: %1$d, SourceId: %2$s", groupId, sourceId)); accountContactsCursor = GMSContactOperations.findGroupInContacts(contactsProvider, account, sourceId); if (accountContactsCursor != null && accountContactsCursor.moveToFirst()) { groupRawContactId = accountContactsCursor.getLong(0); } } finally { if (accountContactsCursor != null) { accountContactsCursor.close(); } } GMSContactOperations.removeGroupFromContacts(contactsProvider, account, groupRawContactId, syncResult); } } while (unsyncedGroupsCursor.moveToNext()); } } finally { if (unsyncedGroupsCursor != null) { unsyncedGroupsCursor.close(); } } // Now delete any unsynced contacts from the local provider op = ContentProviderOperation.newDelete(GMSContacts.CONTENT_URI) .withSelection( GMSContact.STATUS + " ISNULL OR " + GMSContact.STATUS + " != " + GMSContact.STATUS_SYNCED, null) .build(); ops.add(op); op = ContentProviderOperation.newUpdate(GMSGroups.CONTENT_URI).withValue(GMSGroup.STATUS, null).build(); ops.add(op); op = ContentProviderOperation.newUpdate(GMSContacts.CONTENT_URI).withValue(GMSContact.STATUS, null).build(); ops.add(op); try { results = provider.applyBatch(ops); int numResults = results.length; for (int i = 0; i < numResults; ++i) { // The first first N-2 results were deletes if (i < numResults - 2) { syncResult.stats.numDeletes += results[i].count; } else { // The last two results were updates syncResult.stats.numEntries += results[i].count; } } Log.d(TAG, String.format("Delete unsynced items after count: %1$d, entries: %2$d", syncResult.stats.numDeletes, syncResult.stats.numEntries)); } catch (OperationApplicationException e) { syncResult.stats.numSkippedEntries++; e.printStackTrace(); } }
From source file:org.pixmob.droidlink.sync.SyncAdapter.java
private void doPerformSync(NetworkClient client, SharedPreferences prefs, ContentProviderClient provider, SyncResult syncResult, boolean fullSync) { // Prepare the query. final String selection = DEVICE_ID + "=? AND " + STATE + "=? OR " + STATE + "=?"; final String[] selectionArgs = { client.getDeviceId(), String.valueOf(EventsContract.PENDING_UPLOAD_STATE), String.valueOf(EventsContract.PENDING_DELETE_STATE) }; // Get local data to sync. final Map<String, JSONObject> eventsToUpload = new HashMap<String, JSONObject>(8); final Set<String> eventsToDelete = new HashSet<String>(4); Cursor c = null;/*from ww w .j a v a 2s. com*/ try { c = provider.query(EventsContract.CONTENT_URI, PROJECTION, selection, selectionArgs, null); final int idIdx = c.getColumnIndexOrThrow(_ID); final int typeIdx = c.getColumnIndexOrThrow(TYPE); final int createdIdx = c.getColumnIndexOrThrow(CREATED); final int numberIdx = c.getColumnIndexOrThrow(NUMBER); final int nameIdx = c.getColumnIndexOrThrow(NAME); final int messageIdx = c.getColumnIndexOrThrow(MESSAGE); final int stateIdx = c.getColumnIndexOrThrow(STATE); while (c.moveToNext()) { final String eventId = c.getString(idIdx); final int eventState = c.getInt(stateIdx); if (EventsContract.PENDING_UPLOAD_STATE == eventState) { // This is a newly created event. final JSONObject event = new JSONObject(); try { event.put("deviceId", client.getDeviceId()); event.put("created", c.getLong(createdIdx)); event.put("type", c.getInt(typeIdx)); event.put("number", c.getString(numberIdx)); event.put("name", c.getString(nameIdx)); event.put("message", c.getString(messageIdx)); } catch (JSONException e) { Log.w(TAG, "Invalid event " + eventId + ": cannot sync", e); syncResult.stats.numSkippedEntries++; continue; } eventsToUpload.put(eventId, event); } else if (EventsContract.PENDING_DELETE_STATE == eventState) { // The user wants this event to be deleted. eventsToDelete.add(eventId); } } } catch (RemoteException e) { Log.e(TAG, "Failed to get events: cannot sync", e); syncResult.stats.numIoExceptions++; } finally { if (c != null) { c.close(); c = null; } } final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(32); final ContentValues values = new ContentValues(8); if (eventsToDelete.isEmpty()) { Log.i(TAG, "No events to delete"); } else { Log.i(TAG, "Found " + eventsToDelete.size() + " event(s) to delete"); } // Delete events on the remote server. for (final String eventId : eventsToDelete) { if (DEVELOPER_MODE) { Log.d(TAG, "Deleting event: " + eventId); } try { client.delete("/events/" + eventId); if (DEVELOPER_MODE) { Log.d(TAG, "Deleting event in local database: " + eventId); } batch.add(ContentProviderOperation .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build()); syncResult.stats.numDeletes++; } catch (IOException e) { Log.e(TAG, "Event deletion error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } catch (AppEngineAuthenticationException e) { Log.e(TAG, "Authentication error: cannot sync", e); syncResult.stats.numAuthExceptions++; return; } } try { provider.applyBatch(batch); } catch (Exception e) { Log.w(TAG, "Database error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } batch.clear(); if (fullSync) { // Get all events from the remote server. final JSONArray events; if (DEVELOPER_MODE) { Log.d(TAG, "Fetching events from the remote server"); } try { events = client.getAsArray("/events"); } catch (IOException e) { Log.e(TAG, "Event listing error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } catch (AppEngineAuthenticationException e) { Log.e(TAG, "Authentication error: cannot sync", e); syncResult.stats.numAuthExceptions++; return; } final int eventsLen = events != null ? events.length() : 0; if (eventsLen == 0) { Log.i(TAG, "No events from the remote server"); } else { Log.i(TAG, "Found " + eventsLen + " event(s) from the remote server"); } // Build a collection with local event identifiers. // This collection will be used to identify which events have // been deleted on the remote server. final Set<String> localEventIds; try { c = provider.query(EventsContract.CONTENT_URI, PROJECTION_ID, STATE + "=?", new String[] { String.valueOf(EventsContract.UPLOADED_STATE) }, null); localEventIds = new HashSet<String>(c.getCount()); final int idIdx = c.getColumnIndexOrThrow(_ID); while (c.moveToNext()) { final String eventId = c.getString(idIdx); localEventIds.add(eventId); } } catch (RemoteException e) { Log.e(TAG, "Failed to get events from local database", e); syncResult.stats.numIoExceptions++; return; } finally { if (c != null) { c.close(); c = null; } } String newEventId = null; int newEventCount = 0; // Reconcile remote events with local events. for (int i = 0; i < eventsLen; ++i) { String eventId = null; try { final JSONObject event = events.getJSONObject(i); eventId = event.getString("id"); // Check if this event exists in the local database. if (localEventIds.contains(eventId)) { // Found the event: update it. values.clear(); values.put(NUMBER, trimToNull(event.getString("number"))); values.put(NAME, trimToNull(event.getString("name"))); values.put(MESSAGE, trimToNull(event.getString("message"))); if (DEVELOPER_MODE) { Log.d(TAG, "Updating event in local database: " + eventId); } batch.add(ContentProviderOperation .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)) .withExpectedCount(1).withValues(values).build()); syncResult.stats.numUpdates++; } else { // The event was not found: insert it. values.clear(); values.put(_ID, eventId); values.put(DEVICE_ID, event.getString("deviceId")); values.put(CREATED, event.getLong("created")); values.put(TYPE, event.getInt("type")); values.put(NUMBER, trimToNull(event.getString("number"))); values.put(NAME, trimToNull(event.getString("name"))); values.put(MESSAGE, trimToNull(event.getString("message"))); values.put(STATE, EventsContract.UPLOADED_STATE); if (DEVELOPER_MODE) { Log.d(TAG, "Adding event to local database: " + eventId); } batch.add(ContentProviderOperation .newInsert(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)) .withValues(values).build()); syncResult.stats.numInserts++; ++newEventCount; if (newEventId == null) { newEventId = eventId; } } // This event now exists in the local database: // remove its identifier from this collection as we // don't want to delete it. localEventIds.remove(eventId); } catch (JSONException e) { Log.w(TAG, "Invalid event at index " + i + ": cannot sync", e); syncResult.stats.numSkippedEntries++; continue; } } // The remaining event identifiers was removed on the remote // server: there are still present in the local database. These // events are now being deleted. for (final String eventId : localEventIds) { if (DEVELOPER_MODE) { Log.d(TAG, "Deleting event in local database: " + eventId); } batch.add(ContentProviderOperation .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build()); syncResult.stats.numDeletes++; } try { provider.applyBatch(batch); } catch (Exception e) { Log.e(TAG, "Database error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } batch.clear(); if (newEventCount > 1) { newEventId = null; } if (newEventCount != 0) { startSyncNotificationService(newEventCount, newEventId); } } final int numEventsToUpload = eventsToUpload.size(); if (numEventsToUpload == 0) { Log.i(TAG, "No events to upload"); } else { Log.i(TAG, "Found " + numEventsToUpload + " event(s) to upload"); } // Send local events to the remote server. for (final Map.Entry<String, JSONObject> entry : eventsToUpload.entrySet()) { final String eventId = entry.getKey(); if (DEVELOPER_MODE) { Log.d(TAG, "Uploading event: " + eventId); } final JSONObject event = entry.getValue(); try { client.put("/events/" + eventId, event); if (DEVELOPER_MODE) { Log.d(TAG, "Updating event state to UPLOADED: " + eventId); } values.clear(); values.put(STATE, EventsContract.UPLOADED_STATE); batch.add(ContentProviderOperation .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).withValues(values) .withExpectedCount(1).build()); syncResult.stats.numUpdates++; Log.i(TAG, "Event upload successful: " + eventId); } catch (NetworkClientException e) { if (e.getStatusCode() == 404) { Log.e(TAG, "Device not found: cannot sync", e); registerDevice(); } else { Log.e(TAG, "Network error: cannot sync", e); } syncResult.stats.numIoExceptions++; return; } catch (IOException e) { Log.e(TAG, "Event upload error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } catch (AppEngineAuthenticationException e) { Log.e(TAG, "Authentication error: cannot sync", e); syncResult.stats.numAuthExceptions++; return; } } try { provider.applyBatch(batch); } catch (Exception e) { Log.w(TAG, "Database error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } batch.clear(); final SharedPreferences.Editor prefsEditor = prefs.edit(); final boolean syncRequired = !eventsToDelete.isEmpty() || !eventsToUpload.isEmpty(); if (syncRequired) { // Generate an unique sync token: the server will send this token to // every devices. If this token is received on this device, the sync // will not start. final String syncToken = UUID.randomUUID().toString(); prefsEditor.putString(SP_KEY_SYNC_TOKEN, syncToken); Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // Sync user devices. try { final JSONObject data = new JSONObject(); data.put("token", syncToken); client.post("/devices/" + client.getDeviceId() + "/sync", data); } catch (NetworkClientException e) { if (e.getStatusCode() == 404) { registerDevice(); } } catch (IOException e) { Log.e(TAG, "Device sync error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } catch (AppEngineAuthenticationException e) { Log.e(TAG, "Authentication error: cannot sync", e); syncResult.stats.numAuthExceptions++; return; } catch (JSONException e) { Log.w(TAG, "Invalid sync token " + syncToken + ": cannot sync", e); syncResult.stats.numIoExceptions++; return; } } // Store sync time. prefsEditor.putLong(SP_KEY_LAST_SYNC, System.currentTimeMillis()); Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); }
From source file:org.kontalk.sync.Syncer.java
/** * The actual sync procedure.//from w ww. j a v a2 s .c om * This one uses the slowest method ever: it first checks for every phone * number in all contacts and it sends them to the server. Once a response * is received, it deletes all the raw contacts created by us and then * recreates only the ones the server has found a match for. */ public void performSync(Context context, Account account, String authority, ContentProviderClient provider, ContentProviderClient usersProvider, SyncResult syncResult) throws OperationCanceledException { final Map<String, RawPhoneNumberEntry> lookupNumbers = new HashMap<>(); final List<String> jidList = new ArrayList<>(); // resync users database Log.v(TAG, "resyncing users database"); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // update users database Uri uri = Users.CONTENT_URI.buildUpon().appendQueryParameter(Users.RESYNC, "true").build(); try { int count = usersProvider.update(uri, new ContentValues(), null, null); Log.d(TAG, "users database resynced (" + count + ")"); } catch (Exception e) { Log.e(TAG, "error resyncing users database - aborting sync", e); syncResult.databaseError = true; return; } // query all contacts Cursor cursor; try { cursor = usersProvider.query(Users.CONTENT_URI_OFFLINE, new String[] { Users.JID, Users.NUMBER, Users.LOOKUP_KEY }, null, null, null); } catch (Exception e) { Log.e(TAG, "error querying users database - aborting sync", e); syncResult.databaseError = true; return; } while (cursor.moveToNext()) { if (mCanceled) { cursor.close(); throw new OperationCanceledException(); } String jid = cursor.getString(0); String number = cursor.getString(1); String lookupKey = cursor.getString(2); // avoid to send duplicates to the server if (lookupNumbers.put(XmppStringUtils.parseLocalpart(jid), new RawPhoneNumberEntry(lookupKey, number, jid)) == null) jidList.add(jid); } cursor.close(); if (mCanceled) throw new OperationCanceledException(); // empty contacts :-| if (jidList.size() == 0) { // delete all Kontalk raw contacts try { syncResult.stats.numDeletes += deleteAll(account, provider); } catch (Exception e) { Log.e(TAG, "contact delete error", e); syncResult.databaseError = true; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { try { syncResult.stats.numDeletes += deleteProfile(account, provider); } catch (Exception e) { Log.e(TAG, "profile delete error", e); syncResult.databaseError = true; } } commit(usersProvider, syncResult); } else { final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(mContext); // register presence broadcast receiver PresenceBroadcastReceiver receiver = new PresenceBroadcastReceiver(jidList, this); IntentFilter f = new IntentFilter(); f.addAction(MessageCenterService.ACTION_PRESENCE); f.addAction(MessageCenterService.ACTION_ROSTER_MATCH); f.addAction(MessageCenterService.ACTION_PUBLICKEY); f.addAction(MessageCenterService.ACTION_BLOCKLIST); f.addAction(MessageCenterService.ACTION_LAST_ACTIVITY); f.addAction(MessageCenterService.ACTION_CONNECTED); lbm.registerReceiver(receiver, f); // request current connection status MessageCenterService.requestConnectionStatus(mContext); // wait for the service to complete its job synchronized (this) { // wait for connection try { wait(MAX_WAIT_TIME); } catch (InterruptedException e) { // simulate canceled operation mCanceled = true; } } lbm.unregisterReceiver(receiver); // last chance to quit if (mCanceled) throw new OperationCanceledException(); List<PresenceItem> res = receiver.getResponse(); if (res != null) { ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(); // TODO operations.size() could be used instead (?) int op = 0; // this is the time - delete all Kontalk raw contacts try { syncResult.stats.numDeletes += deleteAll(account, provider); } catch (Exception e) { Log.e(TAG, "contact delete error", e); syncResult.databaseError = true; return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { try { syncResult.stats.numDeletes += deleteProfile(account, provider); } catch (Exception e) { Log.e(TAG, "profile delete error", e); syncResult.databaseError = true; } } ContentValues registeredValues = new ContentValues(); registeredValues.put(Users.REGISTERED, 1); for (int i = 0; i < res.size(); i++) { PresenceItem entry = res.get(i); if (entry.discarded) continue; final RawPhoneNumberEntry data = lookupNumbers.get(XmppStringUtils.parseLocalpart(entry.from)); if (data != null && data.lookupKey != null) { // add contact addContact(account, getDisplayName(provider, data.lookupKey, data.number), data.number, data.jid, operations, op++); } else { syncResult.stats.numSkippedEntries++; } // update fields try { String status = entry.status; if (!TextUtils.isEmpty(status)) registeredValues.put(Users.STATUS, status); else registeredValues.putNull(Users.STATUS); if (entry.timestamp >= 0) registeredValues.put(Users.LAST_SEEN, entry.timestamp); else registeredValues.putNull(Users.LAST_SEEN); if (entry.publicKey != null) { try { PGPPublicKey pubKey = PGP.getMasterKey(entry.publicKey); // trust our own key blindly int trustLevel = Authenticator.isSelfJID(mContext, entry.from) ? MyUsers.Keys.TRUST_VERIFIED : -1; // update keys table immediately Keyring.setKey(mContext, entry.from, entry.publicKey, trustLevel); // no data from system contacts, use name from public key if (data == null) { PGPUserID uid = PGP.parseUserId(pubKey, XmppStringUtils.parseDomain(entry.from)); if (uid != null) { registeredValues.put(Users.DISPLAY_NAME, uid.getName()); } } } catch (Exception e) { Log.w(TAG, "unable to parse public key", e); } } else { // use roster name if no contact data available if (data == null && entry.rosterName != null) { registeredValues.put(Users.DISPLAY_NAME, entry.rosterName); } } // blocked status registeredValues.put(Users.BLOCKED, entry.blocked); // user JID as reported by the server registeredValues.put(Users.JID, entry.from); /* * Since UsersProvider.resync inserted the user row * using our server name, it might have changed because * of what the server reported. We already put into the * values the new JID, but we need to use the old one * in the where condition so we will have a match. */ String origJid; if (data != null) origJid = XMPPUtils.createLocalJID(mContext, XmppStringUtils.parseLocalpart(entry.from)); else origJid = entry.from; usersProvider.update(Users.CONTENT_URI_OFFLINE, registeredValues, Users.JID + " = ?", new String[] { origJid }); // clear data registeredValues.remove(Users.DISPLAY_NAME); // if this is our own contact, trust our own key later if (Authenticator.isSelfJID(mContext, entry.from)) { // register our profile while we're at it if (data != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // add contact addProfile(account, Authenticator.getDefaultDisplayName(mContext), data.number, data.jid, operations, op++); } } } catch (Exception e) { Log.e(TAG, "error updating users database", e); // we shall continue here... } } try { if (operations.size() > 0) provider.applyBatch(operations); syncResult.stats.numInserts += op; syncResult.stats.numEntries += op; } catch (Exception e) { Log.w(TAG, "contact write error", e); syncResult.stats.numSkippedEntries += op; /* * We do not consider system contacts failure a fatal error. * This is actually a workaround for systems with disabled permissions or * exotic firmwares. It can also protect against security 3rd party apps or * non-Android platforms, such as Jolla/Alien Dalvik. */ } commit(usersProvider, syncResult); } // timeout or error else { Log.w(TAG, "connection timeout - aborting sync"); syncResult.stats.numIoExceptions++; } } }
From source file:edu.mit.mobile.android.locast.sync.SyncEngine.java
/** * @param toSync//from ww w. j a v a2 s. c o m * @param account * @param extras * @param provider * @param syncResult * @return true if the item was sync'd successfully. Soft errors will cause this to return * false. * @throws RemoteException * @throws SyncException * @throws JSONException * @throws IOException * @throws NetworkProtocolException * @throws NoPublicPath * @throws OperationApplicationException * @throws InterruptedException */ public boolean sync(Uri toSync, Account account, Bundle extras, ContentProviderClient provider, SyncResult syncResult) throws RemoteException, SyncException, JSONException, IOException, NetworkProtocolException, NoPublicPath, OperationApplicationException, InterruptedException { String pubPath = null; // // Handle http or https uris separately. These require the // destination uri. // if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) { pubPath = toSync.toString(); if (!extras.containsKey(EXTRA_DESTINATION_URI)) { throw new IllegalArgumentException("missing EXTRA_DESTINATION_URI when syncing HTTP URIs"); } toSync = Uri.parse(extras.getString(EXTRA_DESTINATION_URI)); } final String type = provider.getType(toSync); final boolean isDir = type.startsWith(CONTENT_TYPE_PREFIX_DIR); final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); // skip any items already sync'd if (!manualSync && mLastUpdated.isUpdatedRecently(toSync)) { if (DEBUG) { Log.d(TAG, "not syncing " + toSync + " as it's been updated recently"); } syncResult.stats.numSkippedEntries++; return false; } // the sync map will convert the json data to ContentValues final SyncMap syncMap = MediaProvider.getSyncMap(provider, toSync); final Uri toSyncWithoutQuerystring = toSync.buildUpon().query(null).build(); final HashMap<String, SyncStatus> syncStatuses = new HashMap<String, SyncEngine.SyncStatus>(); final ArrayList<ContentProviderOperation> cpo = new ArrayList<ContentProviderOperation>(); final LinkedList<String> cpoPubUris = new LinkedList<String>(); // // first things first, upload any content that needs to be // uploaded. // try { uploadUnpublished(toSync, account, provider, syncMap, syncStatuses, syncResult); if (Thread.interrupted()) { throw new InterruptedException(); } // this should ensure that all items have a pubPath when we // query it below. if (pubPath == null) { // we should avoid calling this too much as it // can be expensive pubPath = MediaProvider.getPublicPath(mContext, toSync); } } catch (final NoPublicPath e) { // TODO this is a special case and this is probably not the best place to handle this. // Ideally, this should be done in such a way as to reduce any extra DB queries - // perhaps by doing a join with the parent. if (syncMap.isFlagSet(SyncMap.FLAG_PARENT_MUST_SYNC_FIRST)) { if (DEBUG) { Log.d(TAG, "skipping " + toSync + " whose parent hasn't been sync'd first"); } syncResult.stats.numSkippedEntries++; return false; } // if it's an item, we can handle it. if (isDir) { throw e; } } if (pubPath == null) { // this should have been updated already by the initial // upload, so something must be wrong throw new SyncException("never got a public path for " + toSync); } if (DEBUG) { Log.d(TAG, "sync(toSync=" + toSync + ", account=" + account + ", extras=" + extras + ", manualSync=" + manualSync + ",...)"); Log.d(TAG, "pubPath: " + pubPath); } final long request_time = System.currentTimeMillis(); HttpResponse hr = mNetworkClient.get(pubPath); final long response_time = System.currentTimeMillis(); // the time compensation below allows a time-based synchronization to function even if the // local clock is entirely wrong. The server's time is extracted using the Date header and // all are compared relative to the respective clock reference. Any data that's stored on // the mobile should be stored relative to the local clock and the server will respect the // same. long serverTime; try { serverTime = getServerTime(hr); } catch (final DateParseException e) { Log.w(TAG, "could not retrieve date from server. Using local time, which may be incorrect.", e); serverTime = System.currentTimeMillis(); } // TODO check out // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html final long response_delay = response_time - request_time; if (DEBUG) { Log.d(TAG, "request took " + response_delay + "ms"); } final long localTime = request_time; // add this to the server time to get the local time final long localOffset = (localTime - serverTime); if (Math.abs(localOffset) > 30 * 60 * 1000) { Log.w(TAG, "local clock is off by " + localOffset + "ms"); } if (Thread.interrupted()) { throw new InterruptedException(); } final HttpEntity ent = hr.getEntity(); String selection; String selectionInverse; String[] selectionArgs; if (isDir) { final JSONArray ja = new JSONArray(StreamUtils.inputStreamToString(ent.getContent())); ent.consumeContent(); final int len = ja.length(); selectionArgs = new String[len]; // build the query to see which items are already in the // database final StringBuilder sb = new StringBuilder(); sb.append("("); for (int i = 0; i < len; i++) { if (Thread.interrupted()) { throw new InterruptedException(); } final SyncStatus syncStatus = loadItemFromJsonObject(ja.getJSONObject(i), syncMap, serverTime); syncStatuses.put(syncStatus.remote, syncStatus); selectionArgs[i] = syncStatus.remote; // add in a placeholder for the query sb.append('?'); if (i != (len - 1)) { sb.append(','); } } sb.append(")"); final String placeholders = sb.toString(); selection = JsonSyncableItem._PUBLIC_URI + " IN " + placeholders; selectionInverse = JsonSyncableItem._PUBLIC_URI + " NOT IN " + placeholders; } else { final JSONObject jo = new JSONObject(StreamUtils.inputStreamToString(ent.getContent())); ent.consumeContent(); final SyncStatus syncStatus = loadItemFromJsonObject(jo, syncMap, serverTime); syncStatuses.put(syncStatus.remote, syncStatus); selection = JsonSyncableItem._PUBLIC_URI + "=?"; selectionInverse = JsonSyncableItem._PUBLIC_URI + "!=?"; selectionArgs = new String[] { syncStatus.remote }; } // first check without the querystring. This will ensure that we // properly mark things that we already have in the database. final Cursor check = provider.query(toSyncWithoutQuerystring, SYNC_PROJECTION, selection, selectionArgs, null); // these items are on both sides try { final int pubUriCol = check.getColumnIndex(JsonSyncableItem._PUBLIC_URI); final int idCol = check.getColumnIndex(JsonSyncableItem._ID); // All the items in this cursor should be found on both // the client and the server. for (check.moveToFirst(); !check.isAfterLast(); check.moveToNext()) { if (Thread.interrupted()) { throw new InterruptedException(); } final long id = check.getLong(idCol); final Uri localUri = ContentUris.withAppendedId(toSync, id); final String pubUri = check.getString(pubUriCol); final SyncStatus itemStatus = syncStatuses.get(pubUri); itemStatus.state = SyncState.BOTH_UNKNOWN; itemStatus.local = localUri; // make the status searchable by both remote and // local uri syncStatuses.put(localUri.toString(), itemStatus); } } finally { check.close(); } Cursor c = provider.query(toSync, SYNC_PROJECTION, selection, selectionArgs, null); // these items are on both sides try { final int pubUriCol = c.getColumnIndex(JsonSyncableItem._PUBLIC_URI); final int localModifiedCol = c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE); final int serverModifiedCol = c.getColumnIndex(JsonSyncableItem._SERVER_MODIFIED_DATE); final int idCol = c.getColumnIndex(JsonSyncableItem._ID); // All the items in this cursor should be found on both // the client and the server. for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { if (Thread.interrupted()) { throw new InterruptedException(); } final long id = c.getLong(idCol); final Uri localUri = ContentUris.withAppendedId(toSync, id); final String pubUri = c.getString(pubUriCol); final SyncStatus itemStatus = syncStatuses.get(pubUri); if (itemStatus.state == SyncState.ALREADY_UP_TO_DATE || itemStatus.state == SyncState.NOW_UP_TO_DATE) { if (DEBUG) { Log.d(TAG, localUri + "(" + pubUri + ")" + " is already up to date."); } continue; } itemStatus.local = localUri; // make the status searchable by both remote and local uri syncStatuses.put(localUri.toString(), itemStatus); // last modified as stored in the DB, in phone time final long itemLocalModified = c.getLong(localModifiedCol); // last modified as stored in the DB, in server time final long itemServerModified = c.getLong(serverModifiedCol); final long localAge = localTime - itemLocalModified; final long remoteAge = serverTime - itemStatus.remoteModifiedTime; final long ageDifference = Math.abs(localAge - remoteAge); // up to date, as far remote -> local goes if (itemServerModified == itemStatus.remoteModifiedTime) { itemStatus.state = SyncState.ALREADY_UP_TO_DATE; if (DEBUG) { Log.d(TAG, pubUri + " is up to date."); } // need to download } else if (localAge > remoteAge) { if (DEBUG) { final long serverModified = itemStatus.remoteModifiedTime; Log.d(TAG, pubUri + " : local is " + ageDifference + "ms older (" + android.text.format.DateUtils.formatDateTime(mContext, itemLocalModified, FORMAT_ARGS_DEBUG) + ") than remote (" + android.text.format.DateUtils.formatDateTime(mContext, serverModified, FORMAT_ARGS_DEBUG) + "); updating local copy..."); } itemStatus.state = SyncState.REMOTE_DIRTY; final ContentProviderOperation.Builder b = ContentProviderOperation.newUpdate(localUri); // update this so it's in the local timescale correctServerOffset(itemStatus.remoteCVs, JsonSyncableItem._CREATED_DATE, JsonSyncableItem._CREATED_DATE, localOffset); correctServerOffset(itemStatus.remoteCVs, JsonSyncableItem._SERVER_MODIFIED_DATE, JsonSyncableItem._MODIFIED_DATE, localOffset); b.withValues(itemStatus.remoteCVs); b.withExpectedCount(1); cpo.add(b.build()); cpoPubUris.add(pubUri); syncResult.stats.numUpdates++; // need to upload } else if (localAge < remoteAge) { if (DEBUG) { final long serverModified = itemStatus.remoteModifiedTime; Log.d(TAG, pubUri + " : local is " + ageDifference + "ms newer (" + android.text.format.DateUtils.formatDateTime(mContext, itemLocalModified, FORMAT_ARGS_DEBUG) + ") than remote (" + android.text.format.DateUtils.formatDateTime(mContext, serverModified, FORMAT_ARGS_DEBUG) + "); publishing to server..."); } itemStatus.state = SyncState.LOCAL_DIRTY; mNetworkClient.putJson(pubPath, JsonSyncableItem.toJSON(mContext, localUri, c, syncMap)); } mLastUpdated.markUpdated(localUri); syncResult.stats.numEntries++; } // end for } finally { c.close(); } /* * Apply updates in bulk */ if (cpo.size() > 0) { if (DEBUG) { Log.d(TAG, "applying " + cpo.size() + " bulk updates..."); } final ContentProviderResult[] r = provider.applyBatch(cpo); if (DEBUG) { Log.d(TAG, "Done applying updates. Running postSync handler..."); } for (int i = 0; i < r.length; i++) { final ContentProviderResult res = r[i]; final SyncStatus ss = syncStatuses.get(cpoPubUris.get(i)); if (ss == null) { Log.e(TAG, "can't get sync status for " + res.uri); continue; } syncMap.onPostSyncItem(mContext, account, ss.local, ss.remoteJson, res.count != null ? res.count == 1 : true); ss.state = SyncState.NOW_UP_TO_DATE; } if (DEBUG) { Log.d(TAG, "done running postSync handler."); } cpo.clear(); cpoPubUris.clear(); } if (Thread.interrupted()) { throw new InterruptedException(); } /* * Look through the SyncState.state values and find ones that need to be stored. */ for (final Map.Entry<String, SyncStatus> entry : syncStatuses.entrySet()) { if (Thread.interrupted()) { throw new InterruptedException(); } final String pubUri = entry.getKey(); final SyncStatus status = entry.getValue(); if (status.state == SyncState.REMOTE_ONLY) { if (DEBUG) { Log.d(TAG, pubUri + " is not yet stored locally, adding..."); } // update this so it's in the local timescale correctServerOffset(status.remoteCVs, JsonSyncableItem._CREATED_DATE, JsonSyncableItem._CREATED_DATE, localOffset); correctServerOffset(status.remoteCVs, JsonSyncableItem._SERVER_MODIFIED_DATE, JsonSyncableItem._MODIFIED_DATE, localOffset); final ContentProviderOperation.Builder b = ContentProviderOperation.newInsert(toSync); b.withValues(status.remoteCVs); cpo.add(b.build()); cpoPubUris.add(pubUri); syncResult.stats.numInserts++; } } /* * Execute the content provider operations in bulk. */ if (cpo.size() > 0) { if (DEBUG) { Log.d(TAG, "bulk inserting " + cpo.size() + " items..."); } final ContentProviderResult[] r = provider.applyBatch(cpo); if (DEBUG) { Log.d(TAG, "applyBatch completed. Processing results..."); } int successful = 0; for (int i = 0; i < r.length; i++) { final ContentProviderResult res = r[i]; if (res.uri == null) { syncResult.stats.numSkippedEntries++; Log.e(TAG, "result from content provider bulk operation returned null"); continue; } final String pubUri = cpoPubUris.get(i); final SyncStatus ss = syncStatuses.get(pubUri); if (ss == null) { syncResult.stats.numSkippedEntries++; Log.e(TAG, "could not find sync status for " + cpoPubUris.get(i)); continue; } ss.local = res.uri; if (DEBUG) { Log.d(TAG, "onPostSyncItem(" + res.uri + ", ...); pubUri: " + pubUri); } syncMap.onPostSyncItem(mContext, account, res.uri, ss.remoteJson, res.count != null ? res.count == 1 : true); ss.state = SyncState.NOW_UP_TO_DATE; successful++; } if (DEBUG) { Log.d(TAG, successful + " batch inserts successfully applied."); } } else { if (DEBUG) { Log.d(TAG, "no updates to perform."); } } /** * Look through all the items that we didn't already find on the server side, but which * still have a public uri. They should be checked to make sure they're not deleted. */ c = provider.query(toSync, SYNC_PROJECTION, ProviderUtils.addExtraWhere(selectionInverse, JsonSyncableItem._PUBLIC_URI + " NOT NULL"), selectionArgs, null); try { final int idCol = c.getColumnIndex(JsonSyncableItem._ID); final int pubUriCol = c.getColumnIndex(JsonSyncableItem._PUBLIC_URI); cpo.clear(); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { final String pubUri = c.getString(pubUriCol); SyncStatus ss = syncStatuses.get(pubUri); final Uri item = isDir ? ContentUris.withAppendedId(toSyncWithoutQuerystring, c.getLong(idCol)) : toSync; if (ss == null) { ss = syncStatuses.get(item.toString()); } if (DEBUG) { Log.d(TAG, item + " was not found in the main list of items on the server (" + pubPath + "), but appears to be a child of " + toSync); if (ss != null) { Log.d(TAG, "found sync status for " + item + ": " + ss); } } if (ss != null) { switch (ss.state) { case ALREADY_UP_TO_DATE: case NOW_UP_TO_DATE: if (DEBUG) { Log.d(TAG, item + " is already up to date. No need to see if it was deleted."); } continue; case BOTH_UNKNOWN: if (DEBUG) { Log.d(TAG, item + " was found on both sides, but has an unknown sync status. Skipping..."); } continue; default: Log.w(TAG, "got an unexpected state for " + item + ": " + ss); } } else { ss = new SyncStatus(pubUri, SyncState.LOCAL_ONLY); ss.local = item; hr = mNetworkClient.head(pubUri); switch (hr.getStatusLine().getStatusCode()) { case 200: if (DEBUG) { Log.d(TAG, "HEAD " + pubUri + " returned 200"); } ss.state = SyncState.BOTH_UNKNOWN; break; case 404: if (DEBUG) { Log.d(TAG, "HEAD " + pubUri + " returned 404. Deleting locally..."); } ss.state = SyncState.DELETED_REMOTELY; final ContentProviderOperation deleteOp = ContentProviderOperation .newDelete(ContentUris.withAppendedId(toSyncWithoutQuerystring, c.getLong(idCol))) .build(); cpo.add(deleteOp); break; default: syncResult.stats.numIoExceptions++; Log.w(TAG, "HEAD " + pubUri + " got unhandled result: " + hr.getStatusLine()); } } syncStatuses.put(pubUri, ss); } // for cursor if (cpo.size() > 0) { final ContentProviderResult[] results = provider.applyBatch(cpo); for (final ContentProviderResult result : results) { if (result.count != 1) { throw new SyncException("Error deleting item"); } } } } finally { c.close(); } syncStatuses.clear(); mLastUpdated.markUpdated(toSync); return true; }