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:org.mythtv.service.dvr.v25.RecordedHelperV25.java

private void processProgramGroups(final Context context, final LocationProfile locationProfile,
        Program[] programs) throws RemoteException, OperationApplicationException {
    Log.v(TAG, "processProgramGroups : enter");

    if (null == context)
        throw new RuntimeException("RecordedHelperV25 is not initialized");

    Map<String, ProgramGroup> programGroups = new TreeMap<String, ProgramGroup>();
    for (Program program : programs) {

        if (null != program.getRecording()) {

            if (null != program.getRecording().getRecGroup()
                    && !"livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                    && !"deleted".equalsIgnoreCase(program.getRecording().getRecGroup())) {
                String cleaned = ArticleCleaner.clean(program.getTitle());
                if (!programGroups.containsKey(cleaned)) {

                    ProgramGroup programGroup = new ProgramGroup();
                    programGroup.setTitle(program.getTitle());
                    programGroup.setCategory(program.getCategory());
                    programGroup.setInetref(program.getInetref());
                    programGroup.setSort(0);

                    programGroups.put(cleaned, programGroup);
                }//from   ww  w  . j  a  va  2  s  .co m

            }

        }

    }

    int processed = -1;
    int count = 0;

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

    Log.v(TAG, "processProgramGroups : adding 'All' program group in programGroups");
    ProgramGroup all = new ProgramGroup(null, "All", "All", "All", "", 1);
    programGroups.put(all.getProgramGroup(), all);

    String[] programGroupProjection = new String[] { ProgramGroupConstants._ID };
    String programGroupSelection = ProgramGroupConstants.FIELD_PROGRAM_GROUP + " = ?";

    programGroupSelection = appendLocationHostname(context, locationProfile, programGroupSelection, null);

    for (String key : programGroups.keySet()) {
        Log.v(TAG, "processProgramGroups : processing programGroup '" + key + "'");

        ProgramGroup programGroup = programGroups.get(key);

        ContentValues programValues = convertProgramGroupToContentValues(locationProfile, programGroup);
        Cursor programGroupCursor = context.getContentResolver().query(ProgramGroupConstants.CONTENT_URI,
                programGroupProjection, programGroupSelection, new String[] { key }, null);
        if (programGroupCursor.moveToFirst()) {

            Long id = programGroupCursor
                    .getLong(programGroupCursor.getColumnIndexOrThrow(ProgramGroupConstants._ID));
            ops.add(ContentProviderOperation
                    .newUpdate(ContentUris.withAppendedId(ProgramGroupConstants.CONTENT_URI, id))
                    .withValues(programValues).withYieldAllowed(true).build());

        } else {

            ops.add(ContentProviderOperation.newInsert(ProgramGroupConstants.CONTENT_URI)
                    .withValues(programValues).withYieldAllowed(true).build());
        }
        programGroupCursor.close();
        count++;

        if (count > 100) {
            Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

            processBatch(context, ops, processed, count);
        }

    }

    if (!ops.isEmpty()) {
        Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    Log.v(TAG, "processProgramGroups : remove deleted program groups");
    ops = new ArrayList<ContentProviderOperation>();

    DateTime lastModified = new DateTime();
    lastModified = lastModified.minusHours(1);

    String deleteProgramGroupSelection = ProgramGroupConstants.FIELD_LAST_MODIFIED_DATE + " < ?";
    String[] deleteProgramGroupArgs = new String[] { String.valueOf(lastModified.getMillis()) };

    deleteProgramGroupSelection = appendLocationHostname(context, locationProfile, deleteProgramGroupSelection,
            ProgramGroupConstants.TABLE_NAME);

    ops.add(ContentProviderOperation.newDelete(ProgramGroupConstants.CONTENT_URI)
            .withSelection(deleteProgramGroupSelection, deleteProgramGroupArgs).withYieldAllowed(true).build());

    if (!ops.isEmpty()) {
        Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

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

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

@Override
public Void call() throws Exception {
    if (mProvider == null) {
        return null;
    }//from  w  w w .ja v a  2 s .co  m

    if ((ContextCompat.checkSelfPermission(mContext,
            Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED)
            || (ContextCompat.checkSelfPermission(mContext,
                    Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED)) {
        return null;
    }

    if (!CalendarUtils.getSyncCalendar(mContext, this.mCalendarName)) {
        return null;
    }

    if (mShowProgress) {
        mUpdateNotification = new SyncNotification(mContext, R.string.notification_sync_calendar);
        mUpdateNotification.show(mContext.getString(R.string.notification_sync_calendar_loading,
                CalendarUtils.getCalendarName(mContext, this.mCalendarName)));
    }
    CalendarChangedNotification mNotification = new CalendarChangedNotification(mContext,
            CalendarUtils.getCalendarName(mContext, this.mCalendarName));

    try {
        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_calendar_loading,
                    CalendarUtils.getCalendarName(mContext, this.mCalendarName)));

            Log.d(TAG, "loading calendar");

            Calendar iCal;
            String kusssIdPrefix;
            // {{ Load calendar events from resource
            switch (this.mCalendarName) {
            case CalendarUtils.ARG_CALENDAR_EXAM:
                iCal = KusssHandler.getInstance().getExamIcal(mContext, mCalendarBuilder);
                kusssIdPrefix = "at-jku-kusss-exam-";
                break;
            case CalendarUtils.ARG_CALENDAR_COURSE:
                iCal = KusssHandler.getInstance().getLVAIcal(mContext, mCalendarBuilder);
                kusssIdPrefix = "at-jku-kusss-coursedate-";
                break;
            default: {
                Log.w(TAG, "calendar not found: " + this.mCalendarName);
                return null;
            }
            }
            if (iCal == null) {
                Log.w(TAG, "calendar not loaded: " + this.mCalendarName);
                mSyncResult.stats.numParseExceptions++;
                return null;
            }

            List<?> events = iCal.getComponents(Component.VEVENT);

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

            updateNotify(mContext.getString(R.string.notification_sync_calendar_updating,
                    CalendarUtils.getCalendarName(mContext, this.mCalendarName)));

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

            // modify events: move courseId/term and lecturer to description
            String lineSeparator = System.getProperty("line.separator");
            if (lineSeparator == null)
                lineSeparator = ", ";

            Map<String, VEvent> eventsMap = new HashMap<>();
            for (Object e : events) {
                if (VEvent.class.isInstance(e)) {
                    VEvent ev = ((VEvent) e);

                    String summary = ev.getSummary().getValue().trim();
                    String description = ev.getDescription().getValue().trim();

                    Matcher courseIdTermMatcher = courseIdTermPattern.matcher(summary); // (courseId/term)
                    if (courseIdTermMatcher.find()) {
                        if (!description.isEmpty()) {
                            description += lineSeparator;
                            description += lineSeparator;
                        }
                        description += summary.substring(courseIdTermMatcher.start());
                        summary = summary.substring(0, courseIdTermMatcher.start());
                    } else {
                        Matcher lecturerMatcher = lecturerPattern.matcher(summary);
                        if (lecturerMatcher.find()) {
                            if (!description.isEmpty()) {
                                description += lineSeparator;
                                description += lineSeparator;
                            }
                            description += summary.substring(lecturerMatcher.start());
                            summary = summary.substring(0, lecturerMatcher.start());
                        }
                    }

                    summary = summary.trim().replaceAll("([\\r\\n]|\\\\n)+", ", ").trim();
                    description = description.trim();

                    ev.getProperty(Property.SUMMARY).setValue(summary);
                    ev.getProperty(Property.DESCRIPTION).setValue(description);
                }
            }

            // Build hash table of incoming entries
            for (Object e : events) {
                if (VEvent.class.isInstance(e)) {
                    VEvent ev = ((VEvent) e);

                    String uid = ev.getUid().getValue();
                    // compense DST
                    eventsMap.put(uid, ev);
                }
            }

            String calendarId = CalendarUtils.getCalIDByName(mContext, mAccount, mCalendarName, true);

            if (calendarId == null) {
                Log.w(TAG, "calendarId not found");
                return null;
            }

            String mCalendarAccountName = mAccount.name;
            String mCalendarAccountType = mAccount.type;

            try {
                Cursor c = mProvider.query(CalendarContractWrapper.Calendars.CONTENT_URI(),
                        CalendarUtils.CALENDAR_PROJECTION, null, null, null);
                if (c != null) {
                    while (c.moveToNext()) {
                        if (calendarId.equals(c.getString(CalendarUtils.COLUMN_CAL_ID))) {
                            mCalendarAccountName = c.getString(CalendarUtils.COLUMN_CAL_ACCOUNT_NAME);
                            mCalendarAccountType = c.getString(CalendarUtils.COLUMN_CAL_ACCOUNT_TYPE);
                            break;
                        }
                    }
                    c.close();
                }
            } catch (Exception e) {
                return null;
            }

            Log.d(TAG, "Fetching local entries for merge with: " + calendarId);

            Uri calUri = CalendarContractWrapper.Events.CONTENT_URI();

            Cursor c = CalendarUtils.loadEvent(mProvider, calUri, calendarId);

            if (c == null) {
                Log.w(TAG, "selection failed");
            } else {
                Log.d(TAG, String.format("Found %d local entries. Computing merge solution...", c.getCount()));

                // find stale data
                String eventId;
                String eventKusssId;
                String eventLocation;
                String eventTitle;
                String eventDescription;
                long eventDTStart;
                long eventDTEnd;
                boolean eventDirty;
                boolean eventDeleted;

                // calc date for notifiying only future changes
                // max update interval is 1 week
                long notifyFrom = new Date().getTime() - (DateUtils.DAY_IN_MILLIS * 7);

                while (c.moveToNext()) {
                    mSyncResult.stats.numEntries++;
                    eventId = c.getString(CalendarUtils.COLUMN_EVENT_ID);

                    //                        Log.d(TAG, "---------");
                    eventKusssId = null;

                    // get kusssId from extended properties
                    Cursor c2 = mProvider.query(CalendarContract.ExtendedProperties.CONTENT_URI,
                            CalendarUtils.EXTENDED_PROPERTIES_PROJECTION,
                            CalendarContract.ExtendedProperties.EVENT_ID + " = ?", new String[] { eventId },
                            null);

                    if (c2 != null) {
                        while (c2.moveToNext()) {

                            //                                    String extra = "";
                            //                                    for (int i = 0; i < c2.getColumnCount(); i++) {
                            //                                        extra = extra + i + "=" + c2.getString(i) + ";";
                            //                                    }
                            //                                    Log.d(TAG, "Extended: " + extra);

                            if (c2.getString(1).contains(CalendarUtils.EXTENDED_PROPERTY_NAME_KUSSS_ID)) {
                                eventKusssId = c2.getString(2);
                            }
                        }
                        c2.close();
                    }

                    if (TextUtils.isEmpty(eventKusssId)) {
                        eventKusssId = c.getString(CalendarUtils.COLUMN_EVENT_KUSSS_ID_LEGACY);
                    }

                    eventTitle = c.getString(CalendarUtils.COLUMN_EVENT_TITLE);
                    Log.d(TAG, "Title: " + eventTitle);

                    eventLocation = c.getString(CalendarUtils.COLUMN_EVENT_LOCATION);
                    eventDescription = c.getString(CalendarUtils.COLUMN_EVENT_DESCRIPTION);
                    eventDTStart = c.getLong(CalendarUtils.COLUMN_EVENT_DTSTART);
                    eventDTEnd = c.getLong(CalendarUtils.COLUMN_EVENT_DTEND);
                    eventDirty = "1".equals(c.getString(CalendarUtils.COLUMN_EVENT_DIRTY));
                    eventDeleted = "1".equals(c.getString(CalendarUtils.COLUMN_EVENT_DELETED));

                    if (eventKusssId != null && kusssIdPrefix != null
                            && eventKusssId.startsWith(kusssIdPrefix)) {
                        VEvent match = eventsMap.get(eventKusssId);
                        if (match != null && !eventDeleted) {
                            // Entry exists. Remove from entry
                            // map to prevent insert later
                            eventsMap.remove(eventKusssId);

                            // update only changes after notifiyFrom
                            if ((match.getStartDate().getDate().getTime() > notifyFrom
                                    || eventDTStart > notifyFrom) &&
                            // check to see if the entry needs to be updated
                                    ((match.getStartDate().getDate().getTime() != eventDTStart)
                                            || (match.getEndDate().getDate().getTime() != eventDTEnd)
                                            || (!match.getSummary().getValue().trim().equals(eventTitle.trim()))
                                            || (!match.getSummary().getValue().trim().equals(eventTitle.trim()))
                                            || (!match.getLocation().getValue().trim()
                                                    .equals(eventLocation.trim()))
                                            || (!match.getDescription().getValue().trim()
                                                    .equals(eventDescription.trim())))) {
                                Uri existingUri = calUri.buildUpon().appendPath(eventId).build();

                                // Update existing record
                                Log.d(TAG, "Scheduling update: " + existingUri + " dirty=" + eventDirty);

                                batch.add(ContentProviderOperation.newUpdate(existingUri)
                                        .withValues(getContentValuesFromEvent(match)).build());
                                mSyncResult.stats.numUpdates++;

                                mNotification.addUpdate(getEventString(mContext, match));
                            } else {
                                mSyncResult.stats.numSkippedEntries++;
                            }
                        } else {
                            if (eventDTStart > (mSyncFromNow - DateUtils.DAY_IN_MILLIS)) {
                                // Entry doesn't exist. Remove only newer events from the database.
                                Uri deleteUri = calUri.buildUpon().appendPath(eventId).build();
                                Log.d(TAG, "Scheduling delete: " + deleteUri);
                                // notify only future changes
                                if (eventDTStart > notifyFrom && !eventDeleted) {
                                    mNotification.addDelete(AppUtils.getEventString(mContext, eventDTStart,
                                            eventDTEnd, eventTitle, false));
                                }

                                batch.add(ContentProviderOperation.newDelete(deleteUri).build());
                                mSyncResult.stats.numDeletes++;
                            } else {
                                mSyncResult.stats.numSkippedEntries++;
                            }
                        }
                    } else {
                        Log.i(TAG, "Event UID not set, ignore event: uid=" + eventKusssId + " dirty="
                                + eventDirty + " title=" + eventTitle);
                    }
                }
                c.close();

                Log.d(TAG, String.format("Cursor closed, %d events left", eventsMap.size()));

                updateNotify(mContext.getString(R.string.notification_sync_calendar_adding,
                        CalendarUtils.getCalendarName(mContext, this.mCalendarName)));

                // Add new items
                for (VEvent v : eventsMap.values()) {

                    if (v.getUid().getValue().startsWith(kusssIdPrefix)) {
                        // notify only future changes
                        if (v.getStartDate().getDate().getTime() > notifyFrom) {
                            mNotification.addInsert(getEventString(mContext, v));
                        }

                        Builder builder = ContentProviderOperation
                                .newInsert(CalendarContractWrapper.Events.CONTENT_URI());

                        builder.withValue(CalendarContractWrapper.Events.CALENDAR_ID(), calendarId)
                                .withValues(getContentValuesFromEvent(v))
                                .withValue(CalendarContractWrapper.Events.EVENT_TIMEZONE(),
                                        TimeZone.getDefault().getID());

                        if (mCalendarName.equals(CalendarUtils.ARG_CALENDAR_EXAM)) {
                            builder.withValue(CalendarContractWrapper.Events.AVAILABILITY(),
                                    CalendarContractWrapper.Events.AVAILABILITY_BUSY());
                        } else {
                            builder.withValue(CalendarContractWrapper.Events.AVAILABILITY(),
                                    CalendarContractWrapper.Events.AVAILABILITY_FREE());
                        }

                        builder.withValue(CalendarContract.Events.STATUS,
                                CalendarContract.Events.STATUS_TENTATIVE);
                        builder.withValue(CalendarContract.Events.HAS_ALARM, "0");
                        builder.withValue(CalendarContract.Events.HAS_ATTENDEE_DATA, "0");
                        builder.withValue(CalendarContract.Events.HAS_EXTENDED_PROPERTIES, "1");

                        ContentProviderOperation op = builder.build();
                        Log.d(TAG, "Scheduling insert: " + v.getUid().getValue());
                        batch.add(op);

                        int eventIndex = batch.size() - 1;

                        // add kusssid as extendet property
                        batch.add(ContentProviderOperation
                                .newInsert(KusssContentContract.asEventSyncAdapter(
                                        CalendarContract.ExtendedProperties.CONTENT_URI, mAccount.name,
                                        mAccount.type))
                                .withValueBackReference(CalendarContract.ExtendedProperties.EVENT_ID,
                                        eventIndex)
                                .withValue(CalendarContract.ExtendedProperties.NAME,
                                        CalendarUtils.EXTENDED_PROPERTY_NAME_KUSSS_ID)
                                .withValue(CalendarContract.ExtendedProperties.VALUE, v.getUid().getValue())
                                .build());
                        // add location extra for google maps
                        batch.add(ContentProviderOperation
                                .newInsert(KusssContentContract.asEventSyncAdapter(
                                        CalendarContract.ExtendedProperties.CONTENT_URI, mAccount.name,
                                        mAccount.type))
                                .withValueBackReference(CalendarContract.ExtendedProperties.EVENT_ID,
                                        eventIndex)
                                .withValue(CalendarContract.ExtendedProperties.NAME,
                                        CalendarUtils.EXTENDED_PROPERTY_LOCATION_EXTRA)
                                .withValue(CalendarContract.ExtendedProperties.VALUE, getLocationExtra(v))
                                .build());

                        mSyncResult.stats.numInserts++;
                    } else {
                        mSyncResult.stats.numSkippedEntries++;
                    }
                }

                if (batch.size() > 0) {
                    updateNotify(mContext.getString(R.string.notification_sync_calendar_saving,
                            CalendarUtils.getCalendarName(mContext, this.mCalendarName)));

                    Log.d(TAG, "Applying batch update");
                    mProvider.applyBatch(batch);
                    Log.d(TAG, "Notify resolver");
                    mResolver.notifyChange(calUri.buildUpon().appendPath(calendarId).build(), // URI
                            // where
                            // data
                            // was
                            // modified
                            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 calendar failed", e);
    }

    if (mUpdateNotification != null) {
        mUpdateNotification.cancel();
    }
    mNotification.show();

    if (mReleaseProvider) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mProvider.close();
        } else {
            mProvider.release();
        }
    }

    return null;
}

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;/*from  ww w . j  a va 2  s .  c  o m*/
    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.mythtv.service.dvr.v27.RecordedHelperV27.java

private void processProgramGroups(final Context context, final LocationProfile locationProfile,
        Program[] programs) throws RemoteException, OperationApplicationException {
    Log.v(TAG, "processProgramGroups : enter");

    if (null == context)
        throw new RuntimeException("RecordedHelperV27 is not initialized");

    Map<String, ProgramGroup> programGroups = new TreeMap<String, ProgramGroup>();
    for (Program program : programs) {

        if (null != program.getRecording()) {

            if (null != program.getRecording().getRecGroup()
                    && !"livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                    && !"deleted".equalsIgnoreCase(program.getRecording().getRecGroup())) {
                String cleaned = ArticleCleaner.clean(program.getTitle());
                if (!programGroups.containsKey(cleaned)) {

                    ProgramGroup programGroup = new ProgramGroup();
                    programGroup.setTitle(program.getTitle());
                    programGroup.setCategory(program.getCategory());
                    programGroup.setInetref(program.getInetref());
                    programGroup.setSort(0);

                    programGroups.put(cleaned, programGroup);
                }//from   w  w w. j  av a2  s  .  co  m

            }

        }

    }

    int processed = -1;
    int count = 0;

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

    Log.v(TAG, "processProgramGroups : adding 'All' program group in programGroups");
    ProgramGroup all = new ProgramGroup(null, "All", "All", "All", "", 1);
    programGroups.put(all.getProgramGroup(), all);

    String[] programGroupProjection = new String[] { ProgramGroupConstants._ID };
    String programGroupSelection = ProgramGroupConstants.FIELD_PROGRAM_GROUP + " = ?";

    programGroupSelection = appendLocationHostname(context, locationProfile, programGroupSelection, null);

    for (String key : programGroups.keySet()) {
        Log.v(TAG, "processProgramGroups : processing programGroup '" + key + "'");

        ProgramGroup programGroup = programGroups.get(key);

        ContentValues programValues = convertProgramGroupToContentValues(locationProfile, programGroup);
        Cursor programGroupCursor = context.getContentResolver().query(ProgramGroupConstants.CONTENT_URI,
                programGroupProjection, programGroupSelection, new String[] { key }, null);
        if (programGroupCursor.moveToFirst()) {

            Long id = programGroupCursor
                    .getLong(programGroupCursor.getColumnIndexOrThrow(ProgramGroupConstants._ID));
            ops.add(ContentProviderOperation
                    .newUpdate(ContentUris.withAppendedId(ProgramGroupConstants.CONTENT_URI, id))
                    .withValues(programValues).withYieldAllowed(true).build());

        } else {

            ops.add(ContentProviderOperation.newInsert(ProgramGroupConstants.CONTENT_URI)
                    .withValues(programValues).withYieldAllowed(true).build());
        }
        programGroupCursor.close();
        count++;

        if (count > 100) {
            Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

            processBatch(context, ops, processed, count);
        }

    }

    if (!ops.isEmpty()) {
        Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    Log.v(TAG, "processProgramGroups : remove deleted program groups");
    ops = new ArrayList<ContentProviderOperation>();

    DateTime lastModified = new DateTime();
    lastModified = lastModified.minusHours(1);

    String deleteProgramGroupSelection = ProgramGroupConstants.FIELD_LAST_MODIFIED_DATE + " < ?";
    String[] deleteProgramGroupArgs = new String[] { String.valueOf(lastModified.getMillis()) };

    deleteProgramGroupSelection = appendLocationHostname(context, locationProfile, deleteProgramGroupSelection,
            ProgramGroupConstants.TABLE_NAME);

    ops.add(ContentProviderOperation.newDelete(ProgramGroupConstants.CONTENT_URI)
            .withSelection(deleteProgramGroupSelection, deleteProgramGroupArgs).withYieldAllowed(true).build());

    if (!ops.isEmpty()) {
        Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

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

From source file:nl.privacybarometer.privacyvandaag.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<>();

    while (cursor != null && 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);
        }//  ww  w .j  a v  a  2 s  .  co m

        try {
            NetworkUtils.downloadImage(entryId, imgPath);

            // If we are here, everything is OK
            operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
        } 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());
            }
        }
    }

    if (cursor != null)
        cursor.close();

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

From source file:org.totschnig.myexpenses.sync.SyncAdapter.java

private void writeRemoteChangesToDbPart(ContentProviderClient provider, List<TransactionChange> remoteChanges,
        long accountId) throws RemoteException, OperationApplicationException {
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();
    ops.add(ContentProviderOperation//from   ww w . j a v  a2s.  c  om
            .newInsert(TransactionProvider.DUAL_URI.buildUpon()
                    .appendQueryParameter(TransactionProvider.QUERY_PARAMETER_SYNC_BEGIN, "1").build())
            .build());
    Stream.of(remoteChanges).filter(change -> !(change.isCreate() && uuidExists(change.uuid())))
            .forEach(change -> collectOperations(change, accountId, ops, -1));
    ops.add(ContentProviderOperation.newDelete(TransactionProvider.DUAL_URI.buildUpon()
            .appendQueryParameter(TransactionProvider.QUERY_PARAMETER_SYNC_END, "1").build()).build());
    ContentProviderResult[] contentProviderResults = provider.applyBatch(ops);
    int opsSize = ops.size();
    int resultsSize = contentProviderResults.length;
    if (opsSize != resultsSize) {
        AcraHelper.report(
                String.format(Locale.ROOT, "applied %d operations, received %d results", opsSize, resultsSize));
    }
}

From source file:fr.mixit.android.io.JsonHandlerApplyMembers.java

protected void deleteItemsDataNotFound(ContentResolver resolver) {
    // delete deleted members from N-N relation with interest
    for (final Map.Entry<String, HashSet<String>> entry : mItemInterestsIds.entrySet()) {
        final String itemId = entry.getKey();
        final HashSet<String> interestIds = entry.getValue();
        final Uri itemInterestIds = MixItContract.Members.buildInterestsDirUri(itemId);
        final HashSet<String> lostInterestIds = ProviderParsingUtils.getLostIds(interestIds, itemInterestIds,
                MixItContract.Interests.PROJ.PROJECTION, MixItContract.Interests.PROJ.INTEREST_ID, resolver);
        for (final String lostInterestId : lostInterestIds) {
            final Uri deleteUri = MixItContract.Members.buildMemberInterestUri(itemId, lostInterestId);
            final ContentProviderOperation ope = ContentProviderOperation.newDelete(deleteUri).build();
            ProviderParsingUtils.addOpeAndApplyBatch(mAuthority, resolver, mBatch, false, ope);
        }//from   w  w  w.  ja va2  s .c  om
    }

    // and delete deleted members from N-N relation with members (links)
    for (final Map.Entry<String, HashSet<String>> entry : mItemLinksIds.entrySet()) {
        final String itemId = entry.getKey();
        final HashSet<String> linkIds = entry.getValue();
        final Uri itemLinksUri = MixItContract.Members.buildLinksDirUri(itemId);
        final HashSet<String> lostLinkIds = ProviderParsingUtils.getLostIds(linkIds, itemLinksUri,
                MixItContract.Members.PROJ_LINKS.PROJECTION, MixItContract.Members.PROJ_LINKS.LINK_ID,
                resolver);
        for (final String lostLinkId : lostLinkIds) {
            final Uri deleteUri = MixItContract.Members.buildMemberLinkUri(itemId, lostLinkId);
            final ContentProviderOperation ope = ContentProviderOperation.newDelete(deleteUri).build();
            ProviderParsingUtils.addOpeAndApplyBatch(mAuthority, resolver, mBatch, false, ope);
        }
    }

    // and delete deleted members from N-N relation with members (linkers)
    for (final Map.Entry<String, HashSet<String>> entry : mItemLinkersIds.entrySet()) {
        final String itemId = entry.getKey();
        final HashSet<String> linkerIds = entry.getValue();
        final Uri itemLinkersUri = MixItContract.Members.buildLinkersDirUri(itemId);
        final HashSet<String> lostLinkerIds = ProviderParsingUtils.getLostIds(linkerIds, itemLinkersUri,
                MixItContract.Members.PROJ_LINKS.PROJECTION, MixItContract.Members.PROJ_LINKS.LINKER_ID,
                resolver);
        for (final String lostLinkerId : lostLinkerIds) {
            final Uri deleteUri = MixItContract.Members.buildMemberLinkerUri(itemId, lostLinkerId);
            final ContentProviderOperation ope = ContentProviderOperation.newDelete(deleteUri).build();
            ProviderParsingUtils.addOpeAndApplyBatch(mAuthority, resolver, mBatch, false, ope);
        }
    }

    // and delete deleted sharedLinks from 1-N relation with members
    for (final Map.Entry<String, HashSet<String>> entry : mItemSharedLinksIds.entrySet()) {
        final String itemId = entry.getKey();
        final HashSet<String> sharedLinkIds = entry.getValue();
        final Uri itemSharedLinksUri = MixItContract.Members.buildSharedLinksDirUri(itemId);
        final HashSet<String> lostSharedLinkIds = ProviderParsingUtils.getLostIds(sharedLinkIds,
                itemSharedLinksUri, MixItContract.SharedLinks.PROJ.PROJECTION,
                MixItContract.SharedLinks.PROJ.SHARED_LINK_ID, resolver);
        for (final String lostSharedLinkId : lostSharedLinkIds) {
            final Uri deleteUri = MixItContract.Members.buildMemberSharedLinkUri(itemId, lostSharedLinkId);
            final ContentProviderOperation ope = ContentProviderOperation.newDelete(deleteUri).build();
            ProviderParsingUtils.addOpeAndApplyBatch(mAuthority, resolver, mBatch, false, ope);
        }
    }
}

From source file:org.totschnig.myexpenses.sync.SyncAdapter.java

@VisibleForTesting
public void collectOperations(@NonNull TransactionChange change, long accountId,
        ArrayList<ContentProviderOperation> ops, int parentOffset) {
    Uri uri = Transaction.CALLER_IS_SYNC_ADAPTER_URI;
    switch (change.type()) {
    case created:
        ops.addAll(getContentProviderOperationsForCreate(change, ops.size(), parentOffset));
        break;/*from  w  ww.j  a  v a 2s . co  m*/
    case updated:
        ContentValues values = toContentValues(change);
        if (values.size() > 0) {
            ops.add(ContentProviderOperation.newUpdate(uri)
                    .withSelection(KEY_UUID + " = ? AND " + KEY_ACCOUNTID + " = ?",
                            new String[] { change.uuid(), String.valueOf(accountId) })
                    .withValues(values).build());
        }
        break;
    case deleted:
        ops.add(ContentProviderOperation.newDelete(uri)
                .withSelection(KEY_UUID + " = ?", new String[] { change.uuid() }).build());
        break;
    }
    if (change.splitParts() != null) {
        final int newParentOffset = ops.size() - 1;
        List<TransactionChange> splitPartsFiltered = filterDeleted(change.splitParts(),
                findDeletedUuids(Stream.of(change.splitParts())));
        Stream.of(splitPartsFiltered).forEach(splitChange -> collectOperations(splitChange, accountId, ops,
                change.isCreate() ? newParentOffset : -1)); //back reference is only used when we insert a new split, for updating an existing split we search for its _id via its uuid
    }
}

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

@Override
protected void removeDataRows(Resource resource) {
    Event event = (Event) resource;
    pendingOperations.add(ContentProviderOperation.newDelete(syncAdapterURI(Attendees.CONTENT_URI))
            .withSelection(Attendees.EVENT_ID + "=?", new String[] { String.valueOf(event.getLocalID()) })
            .build());/*from  w w w.  j  a  v a  2 s.c om*/
    pendingOperations.add(ContentProviderOperation.newDelete(syncAdapterURI(Reminders.CONTENT_URI))
            .withSelection(Reminders.EVENT_ID + "=?", new String[] { String.valueOf(event.getLocalID()) })
            .build());
}

From source file:fr.mixit.android.io.JsonHandlerApplyMembers.java

protected void deleteItemsNotFound(ContentResolver resolver) {
    final String[] args = { String.valueOf(mMemberType) };
    for (final String lostId : ProviderParsingUtils.getLostIds(mItemIds, MixItContract.Members.CONTENT_URI,
            MixItContract.Members.PROJ_DETAIL.PROJECTION, MixItContract.Members.PROJ_DETAIL.MEMBER_ID, resolver,
            MixItContract.Members.TYPE + " = ?", args)) {
        // delete members not found from N-N relation with interest
        Uri deleteUri = MixItContract.Members.buildInterestsDirUri(lostId);
        ContentProviderOperation ope = ContentProviderOperation.newDelete(deleteUri).build();
        ProviderParsingUtils.addOpeAndApplyBatch(mAuthority, resolver, mBatch, false, ope);

        // and delete members not found from 1-N relation with sharedLinks
        deleteUri = MixItContract.Members.buildSharedLinksDirUri(lostId);
        ope = ContentProviderOperation.newDelete(deleteUri).build();
        ProviderParsingUtils.addOpeAndApplyBatch(mAuthority, resolver, mBatch, false, ope);

        // and delete members not found from N-N relation with members (links and linkers)
        deleteUri = MixItContract.Members.buildMemberUri(lostId);
        ope = ContentProviderOperation.newDelete(deleteUri).build();
        ProviderParsingUtils.addOpeAndApplyBatch(mAuthority, resolver, mBatch, false, ope);
    }//  w  w  w. j  av  a 2 s  .  c  om
}