Example usage for android.content ContentProviderOperation newDelete

List of usage examples for android.content ContentProviderOperation newDelete

Introduction

In this page you can find the example usage for android.content ContentProviderOperation newDelete.

Prototype

public static Builder newDelete(Uri uri) 

Source Link

Document

Create a Builder suitable for building a delete ContentProviderOperation .

Usage

From source file:com.granita.icloudcalsync.resource.LocalCalendar.java

public void deleteAllExceptRemoteNames(Resource[] remoteResources) {
    List<String> sqlFileNames = new LinkedList<>();
    for (Resource res : remoteResources)
        sqlFileNames.add(DatabaseUtils.sqlEscapeString(res.getName()));

    // delete master events
    String where = entryColumnParentID() + "=?";
    where += sqlFileNames.isEmpty() ? " AND " + entryColumnRemoteName() + " IS NOT NULL" : // don't retain anything (delete all)
            " AND " + entryColumnRemoteName() + " NOT IN (" + StringUtils.join(sqlFileNames, ",") + ")"; // retain by remote file name
    if (sqlFilter != null)
        where += " AND (" + sqlFilter + ")";
    pendingOperations.add(ContentProviderOperation.newDelete(entriesURI())
            .withSelection(where, new String[] { String.valueOf(id) }).build());

    // delete exceptions, too
    where = entryColumnParentID() + "=?";
    where += sqlFileNames.isEmpty() ? " AND " + Events.ORIGINAL_SYNC_ID + " IS NOT NULL" : // don't retain anything (delete all)
            " AND " + Events.ORIGINAL_SYNC_ID + " NOT IN (" + StringUtils.join(sqlFileNames, ",") + ")"; // retain by remote file name
    pendingOperations.add(ContentProviderOperation.newDelete(entriesURI())
            .withSelection(where, new String[] { String.valueOf(id) }).withYieldAllowed(true).build());
}

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 w w  w.  ja v  a  2s.c o m*/
    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:com.barak.pix.FeedsActivity.java

/**
 * This method remove IM entry at default Contact application.
 *
 * @param contentResolver/*from ww w .ja  v  a 2  s  .  c  o  m*/
 *            content resolver
 * @param uid
 *            User id from android
 * @param account
 *            account name
 */
public static void removeIMContactField(ContentResolver contentResolver, String uid, String account) {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
            .withSelection(
                    ContactsContract.Data.RAW_CONTACT_ID + "=? and " + ContactsContract.Data.MIMETYPE
                            + "=? and " + ContactsContract.CommonDataKinds.Im.DATA + " = ?",
                    new String[] { String.valueOf(uid), ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE,
                            account })
            .build());

    try {
        contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
        Log.d(LOG_TAG, "Can't delete Contact's IM field.");
    }
}

From source file:org.m2x.rssreader.service.FetcherService.java

private void downloadAllImages() {
    ContentResolver cr = MainApplication.getContext().getContentResolver();
    Cursor cursor = cr.query(TaskColumns.CONTENT_URI,
            new String[] { TaskColumns._ID, TaskColumns.ENTRY_ID, TaskColumns.IMG_URL_TO_DL,
                    TaskColumns.NUMBER_ATTEMPT },
            TaskColumns.IMG_URL_TO_DL + Constants.DB_IS_NOT_NULL, null, null);

    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    while (cursor.moveToNext()) {
        long taskId = cursor.getLong(0);
        long entryId = cursor.getLong(1);
        String imgPath = cursor.getString(2);
        int nbAttempt = 0;
        if (!cursor.isNull(3)) {
            nbAttempt = cursor.getInt(3);
        }/* w w  w .  j  a v a 2s.  c  o m*/

        try {
            NetworkUtils.downloadImage(entryId, imgPath);

            // If we are here, everything is OK
            operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            cr.notifyChange(EntryColumns.CONTENT_URI(entryId), null); // To refresh the view
        } catch (Exception e) {
            if (nbAttempt + 1 > MAX_TASK_ATTEMPT) {
                operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            } else {
                ContentValues values = new ContentValues();
                values.put(TaskColumns.NUMBER_ATTEMPT, nbAttempt + 1);
                operations.add(ContentProviderOperation.newUpdate(TaskColumns.CONTENT_URI(taskId))
                        .withValues(values).build());
            }
        }
    }

    cursor.close();

    if (!operations.isEmpty()) {
        try {
            cr.applyBatch(FeedData.AUTHORITY, operations);
        } catch (Throwable ignored) {
        }
    }
}

From source file:org.mythtv.service.channel.v25.ChannelHelperV25.java

private void deleteChannels(final Context context, final LocationProfile locationProfile,
        ArrayList<ContentProviderOperation> ops, DateTime today) {
    Log.v(TAG, "deleteChannels : enter");

    String channelDeleteSelection = ChannelConstants.FIELD_LAST_MODIFIED_DATE + " < ?";
    String[] channelDeleteSelectionArgs = new String[] { String.valueOf(today.getMillis()) };

    channelDeleteSelection = appendLocationHostname(context, locationProfile, channelDeleteSelection,
            ChannelConstants.TABLE_NAME);

    ops.add(ContentProviderOperation.newDelete(ChannelConstants.CONTENT_URI)
            .withSelection(channelDeleteSelection, channelDeleteSelectionArgs).withYieldAllowed(true).build());

    Log.v(TAG, "deleteChannels : exit");
}

From source file:com.google.samples.apps.iosched.service.SessionCalendarService.java

/**
 * Removes all calendar entries associated with Google I/O.
 *//*from   w  w  w.  j  a v a2 s. c o  m*/
private ArrayList<ContentProviderOperation> processClearAllSessions(ContentResolver resolver, long calendarId) {

    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();

    // Unable to find the Calendar associated with the user. Stop here.
    if (calendarId == INVALID_CALENDAR_ID) {
        Log.e(TAG, "Unable to find Calendar for user");
        return batch;
    }

    // Delete all calendar entries matching the given title within the given time period
    batch.add(ContentProviderOperation.newDelete(CalendarContract.Events.CONTENT_URI).withSelection(
            CalendarContract.Events.CALENDAR_ID + " = ? and " + CalendarContract.Events.TITLE + " LIKE ? and "
                    + CalendarContract.Events.DTSTART + ">= ? and " + CalendarContract.Events.DTEND + "<= ?",
            new String[] { Long.toString(calendarId), CALENDAR_CLEAR_SEARCH_LIKE_EXPRESSION,
                    Long.toString(Config.CONFERENCE_START_MILLIS),
                    Long.toString(Config.CONFERENCE_END_MILLIS) })
            .build());

    return batch;
}

From source file:org.voidsink.anewjkuapp.update.ImportExamTask.java

@Override
protected Void doInBackground(Void... params) {
    Log.d(TAG, "Start importing exams");

    synchronized (sync_lock) {
        final DateFormat df = DateFormat.getDateInstance();

        try {/* w w  w.j  av a 2 s . c o m*/
            Log.d(TAG, "setup connection");

            updateNotify(mContext.getString(R.string.notification_sync_connect));

            if (KusssHandler.getInstance().isAvailable(mContext,
                    AppUtils.getAccountAuthToken(mContext, mAccount),
                    AppUtils.getAccountName(mContext, mAccount),
                    AppUtils.getAccountPassword(mContext, mAccount))) {

                updateNotify(mContext.getString(R.string.notification_sync_exam_loading));

                List<Exam> exams;
                if (PreferenceWrapper.getNewExamsByCourseId(mContext)) {
                    CourseMap courseMap = new CourseMap(mContext);
                    List<Term> terms = KusssContentProvider.getTerms(mContext);

                    Log.d(TAG, "load exams by courseId");
                    exams = KusssHandler.getInstance().getNewExamsByCourseId(mContext, courseMap.getCourses(),
                            terms);
                } else {
                    Log.d(TAG, "load exams");
                    exams = KusssHandler.getInstance().getNewExams(mContext);
                }
                if (exams == null) {
                    mSyncResult.stats.numParseExceptions++;
                } else {
                    Map<String, Exam> examMap = new HashMap<>();
                    for (Exam exam : exams) {
                        Exam old = examMap.put(
                                KusssHelper.getExamKey(exam.getCourseId(),
                                        AppUtils.termToString(exam.getTerm()), exam.getDtStart().getTime()),
                                exam);
                        if (old != null) {
                            Log.w(TAG, "exam alread loaded: " + KusssHelper.getExamKey(old.getCourseId(),
                                    AppUtils.termToString(old.getTerm()), old.getDtStart().getTime()));
                        }
                    }

                    Log.d(TAG, String.format("got %s exams", exams.size()));

                    updateNotify(mContext.getString(R.string.notification_sync_exam_updating));

                    ArrayList<ContentProviderOperation> batch = new ArrayList<>();

                    Uri examUri = KusssContentContract.Exam.CONTENT_URI;
                    Cursor c = mProvider.query(examUri, EXAM_PROJECTION, null, null, null);

                    if (c == null) {
                        Log.w(TAG, "selection failed");
                    } else {
                        Log.d(TAG, "Found " + c.getCount() + " local entries. Computing merge solution...");
                        int examId;
                        String examTerm;
                        String examCourseId;
                        long examDtStart;
                        long examDtEnd;
                        String examLocation;

                        while (c.moveToNext()) {
                            examId = c.getInt(COLUMN_EXAM_ID);
                            examTerm = c.getString(COLUMN_EXAM_TERM);
                            examCourseId = c.getString(COLUMN_EXAM_COURSEID);
                            examDtStart = c.getLong(COLUMN_EXAM_DTSTART);
                            examDtEnd = c.getLong(COLUMN_EXAM_DTEND);
                            examLocation = c.getString(COLUMN_EXAM_LOCATION);

                            Exam exam = examMap
                                    .remove(KusssHelper.getExamKey(examCourseId, examTerm, examDtStart));
                            if (exam != null) {
                                // Check to see if the entry needs to be
                                // updated
                                Uri existingUri = examUri.buildUpon().appendPath(Integer.toString(examId))
                                        .build();
                                Log.d(TAG, "Scheduling update: " + existingUri);

                                if (!DateUtils.isSameDay(new Date(examDtStart), exam.getDtStart())
                                        || !new Date(examDtEnd).equals(exam.getDtEnd())
                                        || !examLocation.equals(exam.getLocation())) {
                                    mNewExamNotification.addUpdate(getEventString(exam));
                                }

                                batch.add(ContentProviderOperation
                                        .newUpdate(KusssContentContract.asEventSyncAdapter(existingUri,
                                                mAccount.name, mAccount.type))
                                        .withValue(KusssContentContract.Exam.COL_ID, Integer.toString(examId))
                                        .withValues(KusssHelper.getExamContentValues(exam)).build());
                                mSyncResult.stats.numUpdates++;
                            } else if (examDtStart > mSyncFromNow - DateUtils.MILLIS_PER_DAY) {
                                // Entry doesn't exist. Remove only newer
                                // events from the database.
                                Uri deleteUri = examUri.buildUpon().appendPath(Integer.toString(examId))
                                        .build();
                                Log.d(TAG, "Scheduling delete: " + deleteUri);

                                batch.add(ContentProviderOperation.newDelete(KusssContentContract
                                        .asEventSyncAdapter(deleteUri, mAccount.name, mAccount.type)).build());
                                mSyncResult.stats.numDeletes++;
                            }
                        }
                        c.close();

                        for (Exam exam : examMap.values()) {
                            batch.add(ContentProviderOperation
                                    .newInsert(KusssContentContract.asEventSyncAdapter(examUri, mAccount.name,
                                            mAccount.type))
                                    .withValues(KusssHelper.getExamContentValues(exam)).build());
                            Log.d(TAG, "Scheduling insert: " + exam.getTerm() + " " + exam.getCourseId());

                            mNewExamNotification.addInsert(getEventString(exam));

                            mSyncResult.stats.numInserts++;
                        }

                        if (batch.size() > 0) {
                            updateNotify(mContext.getString(R.string.notification_sync_exam_saving));

                            Log.d(TAG, "Applying batch update");
                            mProvider.applyBatch(batch);
                            Log.d(TAG, "Notify resolver");
                            mResolver.notifyChange(KusssContentContract.Exam.CONTENT_CHANGED_URI, null, // No
                                    // local
                                    // observer
                                    false); // IMPORTANT: Do not
                            // sync to
                            // network
                        } else {
                            Log.w(TAG, "No batch operations found! Do nothing");
                        }
                    }
                }
                KusssHandler.getInstance().logout(mContext);
            } else {
                mSyncResult.stats.numAuthExceptions++;
            }
        } catch (Exception e) {
            Analytics.sendException(mContext, e, true);
            Log.e(TAG, "import failed", e);
        }
    }

    setImportDone();

    return null;
}

From source file:org.totschnig.myexpenses.model.Account.java

public static void delete(long id) throws RemoteException, OperationApplicationException {
    Account account = getInstanceFromDb(id);
    if (account == null) {
        return;// w  w w  . j a v  a2 s.  com
    }
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();
    ops.add(account.updateTransferPeersForTransactionDelete(buildTransactionRowSelect(null),
            new String[] { String.valueOf(account.getId()) }));
    ops.add(ContentProviderOperation.newDelete(CONTENT_URI.buildUpon().appendPath(String.valueOf(id)).build())
            .build());
    cr().applyBatch(TransactionProvider.AUTHORITY, ops);
    accounts.remove(id);
}

From source file:net.peterkuterna.android.apps.devoxxsched.io.RemoteSessionsHandler.java

@Override
public ArrayList<ContentProviderOperation> parse(ArrayList<JSONArray> entries, ContentResolver resolver)
        throws JSONException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    final HashSet<String> sessionIds = Sets.newHashSet();
    final HashSet<String> trackIds = Sets.newHashSet();
    final HashMap<String, HashSet<String>> sessionSpeakerIds = Maps.newHashMap();
    final HashMap<String, HashSet<String>> sessionTagIds = Maps.newHashMap();

    int nrEntries = 0;
    for (JSONArray sessions : entries) {
        Log.d(TAG, "Retrieved " + sessions.length() + " presentation entries.");
        nrEntries += sessions.length();//from ww w. j  a  v  a  2 s .  c  om

        for (int i = 0; i < sessions.length(); i++) {
            JSONObject session = sessions.getJSONObject(i);
            String id = session.getString("id");

            final String sessionId = sanitizeId(id);
            final Uri sessionUri = Sessions.buildSessionUri(sessionId);
            sessionIds.add(sessionId);
            int isStarred = isStarred(sessionUri, resolver);

            boolean sessionUpdated = false;
            boolean newSession = false;
            ContentProviderOperation.Builder builder;
            if (isRowExisting(sessionUri, SessionsQuery.PROJECTION, resolver)) {
                builder = ContentProviderOperation.newUpdate(sessionUri);
                builder.withValue(Sessions.NEW, false);
                sessionUpdated = isSessionUpdated(sessionUri, session, resolver);
                if (isRemoteSync()) {
                    builder.withValue(Sessions.UPDATED, sessionUpdated);
                }
            } else {
                newSession = true;
                builder = ContentProviderOperation.newInsert(Sessions.CONTENT_URI);
                builder.withValue(Sessions.SESSION_ID, sessionId);
                if (!isLocalSync()) {
                    builder.withValue(Sessions.NEW, true);
                }
            }

            final String type = session.getString("type");
            if (newSession || sessionUpdated) {
                builder.withValue(Sessions.TITLE, session.getString("title"));
                builder.withValue(Sessions.EXPERIENCE, session.getString("experience"));
                builder.withValue(Sessions.TYPE, type);
                builder.withValue(Sessions.SUMMARY, session.getString("summary"));
                builder.withValue(Sessions.STARRED, isStarred);
            }
            builder.withValue(Sessions.TYPE_ID, getTypeId(type));

            batch.add(builder.build());

            if (session.has("track")) {
                final String trackName = session.getString("track");
                final String trackId = Tracks.generateTrackId(trackName);
                final Uri trackUri = Tracks.buildTrackUri(trackId);

                if (!trackIds.contains(trackId)) {
                    trackIds.add(trackId);

                    ContentProviderOperation.Builder trackBuilder;
                    if (isRowExisting(Tracks.buildTrackUri(trackId), TracksQuery.PROJECTION, resolver)) {
                        trackBuilder = ContentProviderOperation.newUpdate(trackUri);
                    } else {
                        trackBuilder = ContentProviderOperation.newInsert(Tracks.CONTENT_URI);
                        trackBuilder.withValue(Tracks.TRACK_ID, trackId);
                    }

                    trackBuilder.withValue(Tracks.TRACK_NAME, trackName);
                    final int color = Color.parseColor(getTrackColor(trackId));
                    trackBuilder.withValue(Tracks.TRACK_COLOR, color);
                    batch.add(trackBuilder.build());
                }

                if (newSession || sessionUpdated) {
                    builder.withValue(Sessions.TRACK_ID, trackId);
                }
            }

            if (session.has("speakers")) {
                final Uri speakerSessionsUri = Sessions.buildSpeakersDirUri(sessionId);
                final JSONArray speakers = session.getJSONArray("speakers");
                final HashSet<String> speakerIds = Sets.newHashSet();

                if (!isLocalSync()) {
                    final boolean sessionSpeakersUpdated = isSessionSpeakersUpdated(speakerSessionsUri,
                            speakers, resolver);
                    if (sessionSpeakersUpdated) {
                        Log.d(TAG, "Speakers of session with id " + sessionId + " was udpated.");
                        batch.add(ContentProviderOperation.newUpdate(sessionUri)
                                .withValue(Sessions.UPDATED, true).build());
                    }
                }

                for (int j = 0; j < speakers.length(); j++) {
                    JSONObject speaker = speakers.getJSONObject(j);

                    final Uri speakerUri = Uri.parse(speaker.getString("speakerUri"));
                    final String speakerId = speakerUri.getLastPathSegment();
                    speakerIds.add(speakerId);

                    batch.add(ContentProviderOperation.newInsert(speakerSessionsUri)
                            .withValue(SessionsSpeakers.SPEAKER_ID, speakerId)
                            .withValue(SessionsSpeakers.SESSION_ID, sessionId).build());
                }

                sessionSpeakerIds.put(sessionId, speakerIds);
            }

            if (session.has("tags")) {
                final Uri tagSessionsUri = Sessions.buildTagsDirUri(sessionId);
                final JSONArray tags = session.getJSONArray("tags");
                final HashSet<String> tagIds = Sets.newHashSet();

                for (int j = 0; j < tags.length(); j++) {
                    JSONObject tag = tags.getJSONObject(j);
                    final String tagName = tag.getString("name").toLowerCase();
                    final String tagId = Tags.generateTagId(tagName);
                    tagIds.add(tagId);

                    batch.add(ContentProviderOperation.newInsert(Tags.CONTENT_URI).withValue(Tags.TAG_ID, tagId)
                            .withValue(Tags.TAG_NAME, tagName).build());

                    batch.add(ContentProviderOperation.newInsert(SearchSuggest.CONTENT_URI)
                            .withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, tagName).build());

                    batch.add(ContentProviderOperation.newInsert(tagSessionsUri)
                            .withValue(SessionsTags.TAG_ID, tagId).withValue(SessionsTags.SESSION_ID, sessionId)
                            .build());
                }

                sessionTagIds.put(sessionId, tagIds);
            }
        }
    }

    if (isRemoteSync() && nrEntries > 0) {
        for (Entry<String, HashSet<String>> entry : sessionSpeakerIds.entrySet()) {
            String sessionId = entry.getKey();
            HashSet<String> speakerIds = entry.getValue();
            final Uri speakerSessionsUri = Sessions.buildSpeakersDirUri(sessionId);
            HashSet<String> lostSpeakerIds = getLostIds(speakerIds, speakerSessionsUri,
                    SpeakersQuery.PROJECTION, SpeakersQuery.SPEAKER_ID, resolver);
            for (String lostSpeakerId : lostSpeakerIds) {
                final Uri deleteUri = Sessions.buildSessionSpeakerUri(sessionId, lostSpeakerId);
                batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            }
        }

        for (Entry<String, HashSet<String>> entry : sessionTagIds.entrySet()) {
            String sessionId = entry.getKey();
            HashSet<String> tagIds = entry.getValue();
            final Uri tagSessionsUri = Sessions.buildTagsDirUri(sessionId);
            HashSet<String> lostTagIds = getLostIds(tagIds, tagSessionsUri, TagsQuery.PROJECTION,
                    TagsQuery.TAG_ID, resolver);
            for (String lostTagId : lostTagIds) {
                final Uri deleteUri = Sessions.buildSessionTagUri(sessionId, lostTagId);
                batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            }
        }

        HashSet<String> lostTrackIds = getLostIds(trackIds, Tracks.CONTENT_URI, TracksQuery.PROJECTION,
                TracksQuery.TRACK_ID, resolver);
        for (String lostTrackId : lostTrackIds) {
            Uri deleteUri = Tracks.buildSessionsUri(lostTrackId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Tracks.buildTrackUri(lostTrackId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        }
        HashSet<String> lostSessionIds = getLostIds(sessionIds, Sessions.CONTENT_URI, SessionsQuery.PROJECTION,
                SessionsQuery.SESSION_ID, resolver);
        for (String lostSessionId : lostSessionIds) {
            Uri deleteUri = Sessions.buildSpeakersDirUri(lostSessionId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Sessions.buildTagsDirUri(lostSessionId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Sessions.buildSessionUri(lostSessionId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        }
    }

    return batch;
}

From source file:at.bitfire.davdroid.resource.LocalCalendar.java

public int deleteAllExceptRemoteNames(Resource[] remoteResources) throws LocalStorageException {
    List<String> sqlFileNames = new LinkedList<>();
    for (Resource res : remoteResources)
        sqlFileNames.add(DatabaseUtils.sqlEscapeString(res.getName()));

    // delete master events
    String where = entryColumnParentID() + "=?";
    where += sqlFileNames.isEmpty() ? " AND " + entryColumnRemoteName() + " IS NOT NULL" : // don't retain anything (delete all)
            " AND " + entryColumnRemoteName() + " NOT IN (" + StringUtils.join(sqlFileNames, ",") + ")"; // retain by remote file name
    if (sqlFilter != null)
        where += " AND (" + sqlFilter + ")";
    pendingOperations.add(ContentProviderOperation.newDelete(entriesURI())
            .withSelection(where, new String[] { String.valueOf(id) }).build());

    // delete exceptions, too
    where = entryColumnParentID() + "=?";
    where += sqlFileNames.isEmpty() ? " AND " + Events.ORIGINAL_SYNC_ID + " IS NOT NULL" : // don't retain anything (delete all)
            " AND " + Events.ORIGINAL_SYNC_ID + " NOT IN (" + StringUtils.join(sqlFileNames, ",") + ")"; // retain by remote file name
    pendingOperations.add(ContentProviderOperation.newDelete(entriesURI())
            .withSelection(where, new String[] { String.valueOf(id) }).withYieldAllowed(true).build());
    return commit();
}