Exemplo n.º 1
0
  @Override
  public ArrayList<ContentProviderOperation> parse(String parser, ContentResolver resolver)
      throws IOException, JSONException {
    // TODO Auto-generated method stub

    Log.v("TAG", "ENTER INTO DASHBORED");

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

    ContentProviderOperation.Builder builder_delete =
        ContentProviderOperation.newDelete(Dashboards.CONTENT_URI);
    batch.add(builder_delete.build());

    if (parser != null) {
      Gson gson = new Gson();
      dashBoard = gson.fromJson(parser, Dashboard.class);
      final ContentProviderOperation.Builder builder =
          ContentProviderOperation.newInsert(Dashboards.CONTENT_URI);
      builder.withValue(Dashboards.PATIENT_ID, dashBoard.getPatientId());
      builder.withValue(Dashboards.JSON, parser);
      batch.add(builder.build());

      Log.v("dashboard", dashBoard.getPatientId());
      Log.v("TAG", "LOADED INTO DATABASE");
    }
    return batch;
  }
  private void addContact(String participant) {
    String DisplayName = participant;

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

    ops.add(
        ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
            .build());

    if (DisplayName != null) {
      ops.add(
          ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
              .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
              .withValue(
                  ContactsContract.Data.MIMETYPE,
                  ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
              .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, DisplayName)
              .build());
    }

    try {
      getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void testTrimInsertEmpty() {
    final ContactsSource source = getSource();
    final Sources sources = getSources(source);
    final DataKind kindPhone = source.getKindForMimetype(Phone.CONTENT_ITEM_TYPE);
    final EditType typeHome = EntityModifier.getType(kindPhone, Phone.TYPE_HOME);

    // Try creating a contact without any child entries
    final EntityDelta state = getEntity(null);
    final EntitySet set = EntitySet.fromSingle(state);

    // Build diff, expecting single insert
    final ArrayList<ContentProviderOperation> diff = Lists.newArrayList();
    state.buildDiff(diff);
    assertEquals("Unexpected operations", 2, diff.size());
    {
      final ContentProviderOperation oper = diff.get(0);
      assertEquals("Incorrect type", TYPE_INSERT, oper.getType());
      assertEquals("Incorrect target", RawContacts.CONTENT_URI, oper.getUri());
    }

    // Trim empty rows and try again, expecting no insert
    EntityModifier.trimEmpty(set, sources);
    diff.clear();
    state.buildDiff(diff);
    assertEquals("Unexpected operations", 0, diff.size());
  }
Exemplo n.º 4
0
 private static void a(Account paramAccount, String paramString1, String paramString2)
 {
   g5.b(z[3] + paramString1 + z[9] + paramString2);
   ArrayList localArrayList = new ArrayList();
   ContentProviderOperation.Builder localBuilder1 = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI);
   localBuilder1.withValue(z[4], paramAccount.name);
   localBuilder1.withValue(z[10], paramAccount.type);
   localBuilder1.withValue(z[13], paramString2);
   localArrayList.add(localBuilder1.build());
   ContentProviderOperation.Builder localBuilder2 = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
   localBuilder2.withValueBackReference(z[6], 0);
   localBuilder2.withValue(z[11], z[8]);
   localBuilder2.withValue(z[0], paramString1);
   localArrayList.add(localBuilder2.build());
   ContentProviderOperation.Builder localBuilder3 = ContentProviderOperation.newInsert(a(ContactsContract.Data.CONTENT_URI));
   localBuilder3.withValueBackReference(z[6], 0);
   localBuilder3.withValue(z[11], z[2]);
   localBuilder3.withValue(z[0], paramString2);
   localBuilder3.withValue(z[12], App.Mb.getString(2131296836));
   localBuilder3.withValue(z[1], "+" + paramString2.substring(0, paramString2.indexOf("@")));
   localArrayList.add(localBuilder3.build());
   try
   {
     App.ib.applyBatch(z[5], localArrayList);
     return;
   }
   catch (Exception localException)
   {
     while (true)
       g5.d(z[7] + paramString1 + z[9] + paramString2 + localException.toString());
   }
 }
Exemplo n.º 5
0
 @Override
 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
     throws OperationApplicationException {
   HashSet<Uri> urisToNotify = new HashSet<Uri>(operations.size());
   for (ContentProviderOperation operation : operations) {
     urisToNotify.add(operation.getUri());
   }
   SQLiteDatabase db = mSqLiteOpenHelper.getWritableDatabase();
   db.beginTransaction();
   try {
     int numOperations = operations.size();
     ContentProviderResult[] results = new ContentProviderResult[numOperations];
     int i = 0;
     for (ContentProviderOperation operation : operations) {
       results[i] = operation.apply(this, results, i);
       if (operation.isYieldAllowed()) {
         db.yieldIfContendedSafely();
       }
       i++;
     }
     db.setTransactionSuccessful();
     for (Uri uri : urisToNotify) {
       getContext().getContentResolver().notifyChange(uri, null);
     }
     return results;
   } finally {
     db.endTransaction();
   }
 }
 public void buildCapsuleCleanup(long keepId, List<Long> duplicateIds) {
   // Convert the extra IDs into selection arguments
   String[] selectionArgs = CapsuleOperations.convertIdsToArguments(duplicateIds);
   String preparedStatementParams =
       CapsuleOperations.buildPreparedStatementParameters(duplicateIds.size());
   // UPDATE operation to change all Discoveries referencing the extra IDs to instead reference the
   // keep ID
   String discoverySelection =
       CapsuleContract.Discoveries.CAPSULE_ID + " IN (" + preparedStatementParams + ")";
   this.mOperations.add(
       ContentProviderOperation.newUpdate(CapsuleContract.Discoveries.CONTENT_URI)
           .withSelection(discoverySelection, selectionArgs)
           .withValue(CapsuleContract.Discoveries.CAPSULE_ID, keepId)
           .withYieldAllowed(true)
           .build());
   // UPDATE operation to change all Ownerships referencing the extra IDs to instead reference the
   // keep ID
   String ownershipSelection =
       CapsuleContract.Ownerships.CAPSULE_ID + " IN (" + preparedStatementParams + ")";
   this.mOperations.add(
       ContentProviderOperation.newUpdate(CapsuleContract.Ownerships.CONTENT_URI)
           .withSelection(ownershipSelection, selectionArgs)
           .withValue(CapsuleContract.Ownerships.CAPSULE_ID, keepId)
           .withYieldAllowed(false)
           .build());
   // DELETE the duplicate Capsules
   String capsuleSelection =
       CapsuleContract.Capsules._ID + " IN (" + preparedStatementParams + ")";
   this.mOperations.add(
       ContentProviderOperation.newDelete(CapsuleContract.Capsules.CONTENT_URI)
           .withSelection(capsuleSelection, selectionArgs)
           .withYieldAllowed(false)
           .build());
 }
Exemplo n.º 7
0
  @Override
  public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
      throws OperationApplicationException {
    Log.d(TAG, "applyBatch()");
    ContentProviderResult[] result = new ContentProviderResult[operations.size()];
    int i = 0;
    // Opens the database object in "write" mode.
    SQLiteDatabase db = database.getWritableDatabase();
    // Begin a transaction
    db.beginTransaction();
    try {
      for (ContentProviderOperation operation : operations) {
        // Chain the result for back references
        result[i++] = operation.apply(this, result, i);
      }

      db.setTransactionSuccessful();
    } catch (OperationApplicationException e) {
      Log.d(TAG, "batch failed: " + e.getLocalizedMessage());
    } finally {
      db.endTransaction();
    }
    Log.d(TAG, "applyBatch() result[0] " + result[0]);
    return result;
  }
Exemplo n.º 8
0
  private void buildSpeaker(
      boolean isInsert, Speaker speaker, ArrayList<ContentProviderOperation> list) {
    Uri allSpeakersUri =
        ScheduleContractHelper.setUriAsCalledFromSyncAdapter(ScheduleContract.Speakers.CONTENT_URI);
    Uri thisSpeakerUri =
        ScheduleContractHelper.setUriAsCalledFromSyncAdapter(
            ScheduleContract.Speakers.buildSpeakerUri(speaker.id));

    ContentProviderOperation.Builder builder;
    if (isInsert) {
      builder = ContentProviderOperation.newInsert(allSpeakersUri);
    } else {
      builder = ContentProviderOperation.newUpdate(thisSpeakerUri);
    }

    list.add(
        builder
            .withValue(ScheduleContract.SyncColumns.UPDATED, System.currentTimeMillis())
            .withValue(ScheduleContract.Speakers.SPEAKER_ID, speaker.id)
            .withValue(ScheduleContract.Speakers.SPEAKER_NAME, speaker.name)
            .withValue(ScheduleContract.Speakers.SPEAKER_ABSTRACT, speaker.bio)
            .withValue(ScheduleContract.Speakers.SPEAKER_COMPANY, speaker.company)
            .withValue(ScheduleContract.Speakers.SPEAKER_IMAGE_URL, speaker.thumbnailUrl)
            .withValue(ScheduleContract.Speakers.SPEAKER_PLUSONE_URL, speaker.plusoneUrl)
            .withValue(ScheduleContract.Speakers.SPEAKER_TWITTER_URL, speaker.twitterUrl)
            .withValue(
                ScheduleContract.Speakers.SPEAKER_IMPORT_HASHCODE, speaker.getImportHashcode())
            .build());
  }
Exemplo n.º 9
0
 private static ContentProviderOperation.Builder insertOrUpdateForRawContact(
     Uri uri, long rawContactId, String itemType) {
   if (rawContactId == -1) {
     return referenceRawContact(ContentProviderOperation.newInsert(uri), rawContactId)
         .withValue(ContactsContract.Data.MIMETYPE, itemType);
   } else {
     return selectByRawContactAndItemType(
         ContentProviderOperation.newUpdate(uri), rawContactId, itemType);
   }
 }
  private ArrayList<ContentProviderOperation> prepareBatch(
      Cursor cursor, Collection<CategoryItem> serverCategories) {
    ArrayList<ContentProviderOperation> batch = new ArrayList<>();
    Map<Double, CategoryItem> map = new HashMap<Double, CategoryItem>();
    for (CategoryItem item : serverCategories) {
      map.put(item.getId(), item);
    }

    Uri itemUri;
    Uri tableUri = CategoryColumns.CONTENT_URI;
    double canonicalId;
    CategoryItem dbItem;
    CategoryCursor itemCursor;
    try {
      while (cursor.moveToNext()) {
        itemCursor = new CategoryCursor(cursor);
        dbItem = transformer.transform(itemCursor);

        itemUri = Uri.withAppendedPath(tableUri, String.valueOf(itemCursor.getId()));
        canonicalId = itemCursor.getCategoryId();

        CategoryItem webItem = map.get(canonicalId);
        if (webItem == null) {
          syncResult.stats.numDeletes++;
          batch.add(ContentProviderOperation.newDelete(itemUri).build());
        } else {
          map.remove(canonicalId);

          if (!dbItem.equals(webItem)) {
            syncResult.stats.numUpdates++;
            batch.add(
                ContentProviderOperation.newUpdate(itemUri)
                    .withValue(CategoryColumns.DESCRIPTION, webItem.getDescription())
                    .withValue(CategoryColumns.NAME, webItem.getName())
                    .build());
          }
        }
      }
    } finally {
      cursor.close();
    }

    for (CategoryItem webItem : map.values()) {
      syncResult.stats.numInserts++;
      batch.add(
          ContentProviderOperation.newInsert(tableUri)
              .withValue(CategoryColumns.DESCRIPTION, webItem.getDescription())
              .withValue(CategoryColumns.NAME, webItem.getName())
              .withValue(CategoryColumns.CATEGORY_ID, webItem.getId())
              .build());
    }

    return batch;
  }
Exemplo n.º 11
0
  // ------------------------------------------------------ Create Google
  // Contact ()
  public void createGoogleContact(String name, String email, String phone, String group) {
    ops = new ArrayList<ContentProviderOperation>();
    ops.add(
        ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.google")
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, googleAccountName)
            // .withValue(RawContacts.AGGREGATION_MODE,
            // RawContacts.AGGREGATION_MODE_DEFAULT)
            .build());

    // ---------- Add Contacts First and Last names
    ops.add(
        ContentProviderOperation.newInsert(Data.CONTENT_URI)
            .withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
            .withValue(StructuredName.GIVEN_NAME, name)
            .build());

    // ---------- Add Contacts Mobile Phone Number
    ops.add(
        ContentProviderOperation.newInsert(Data.CONTENT_URI)
            .withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(
                ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_MOBILE)
            .build());

    // ---------- Add Contacts Email
    ops.add(
        ContentProviderOperation.newInsert(Data.CONTENT_URI)
            .withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(
                ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
            .withValue(
                ContactsContract.CommonDataKinds.Email.TYPE,
                ContactsContract.CommonDataKinds.Email.TYPE_WORK)
            .build());

    // ---------- Add Contact To Group
    addContactToGroup(ops, group);

    try {
      ContentProviderResult[] results =
          context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 12
0
 @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());
   pendingOperations.add(
       ContentProviderOperation.newDelete(syncAdapterURI(Reminders.CONTENT_URI))
           .withSelection(
               Reminders.EVENT_ID + "=?", new String[] {String.valueOf(event.getLocalID())})
           .build());
 }
    @Override
    protected Integer doInBackground(List<Contact>... arg0) {
      contacts = arg0[0];

      for (int i = 0; i < contacts.size(); i += BATCH_SIZE) {
        StringBuffer inVals = new StringBuffer();
        int maxIndex = Math.min(BATCH_SIZE + i, contacts.size()) - i;
        for (int j = 0; j < maxIndex; j++) inVals.append(contacts.get(i + j).rawContactId + ",");
        inVals.deleteCharAt(inVals.length() - 1);
        String selectionClause = GroupMembership.RAW_CONTACT_ID + " IN (" + inVals + ")";

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

        ops.add(
            ContentProviderOperation.newUpdate(
                    Data.CONTENT_URI
                        .buildUpon()
                        .appendQueryParameter(RawContacts.ACCOUNT_NAME, account)
                        .appendQueryParameter(RawContacts.ACCOUNT_TYPE, ACCOUNT_TYPE)
                        .build())
                .withSelection(selectionClause, null)
                .withValue(Photo.PHOTO, null)
                .build());

        try {
          getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (RemoteException e) {
        } catch (OperationApplicationException e) {
        }

        if (isCancelled()) return 0;
      }

      return contacts.size();
    }
Exemplo n.º 14
0
  @Override
  public void onReceive(Context context, Intent intent) {
    if (!SettingsStorage.getInstance().isEnableLogProfileSwitches()) {
      return;
    }
    if (intent == null) {
      return;
    }
    if (ACTION_FLUSH_LOG.equals(intent.getAction())
        || intent.getBooleanExtra(ACTION_FLUSH_LOG, false)) {
      flushLogToDB(context);
      return;
    }
    ContentValues values = new ContentValues();
    values.put(DB.SwitchLogDB.NAME_TIME, System.currentTimeMillis());
    values.put(DB.SwitchLogDB.NAME_MESSAGE, intent.getStringExtra(EXTRA_LOG_ENTRY));
    values.put(DB.SwitchLogDB.NAME_TRIGGER, intent.getStringExtra(DB.SwitchLogDB.NAME_TRIGGER));
    values.put(DB.SwitchLogDB.NAME_PROFILE, intent.getStringExtra(DB.SwitchLogDB.NAME_PROFILE));
    values.put(DB.SwitchLogDB.NAME_VIRTGOV, intent.getStringExtra(DB.SwitchLogDB.NAME_VIRTGOV));
    values.put(DB.SwitchLogDB.NAME_AC, intent.getIntExtra(DB.SwitchLogDB.NAME_AC, -1));
    values.put(DB.SwitchLogDB.NAME_BATTERY, intent.getIntExtra(DB.SwitchLogDB.NAME_BATTERY, -1));
    values.put(DB.SwitchLogDB.NAME_CALL, intent.getIntExtra(DB.SwitchLogDB.NAME_CALL, -1));
    values.put(DB.SwitchLogDB.NAME_HOT, intent.getIntExtra(DB.SwitchLogDB.NAME_HOT, -1));
    values.put(DB.SwitchLogDB.NAME_LOCKED, intent.getIntExtra(DB.SwitchLogDB.NAME_LOCKED, -1));

    Builder opp = ContentProviderOperation.newInsert(DB.SwitchLogDB.CONTENT_URI);
    opp.withValues(values);
    operations.add(opp.build());
    if (operations.size() > 10 || intent.getBooleanExtra(EXTRA_FLUSH_LOG, false)) {
      flushLogToDB(context);
    }
  }
  public static void addPhone(
      final Context context, final long rawContactId, @NonNull String number) {
    number = ContactUtils.modifyPhoneNumber(number);
    if (isNumberExists(context, number)) {
      return;
    }

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

    ops.add(
        ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            .withValue(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)
            .withValue(
                ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number)
            .withValue(
                ContactsContract.CommonDataKinds.Phone.TYPE,
                ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM)
            .withValue(ContactsContract.CommonDataKinds.Phone.LABEL, Config.SNYPIR_TAG)
            .build());
    try {
      context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException | OperationApplicationException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 16
0
  public static ContentProviderOperation buildBatchOperation(JSONObject jsonObject)
      throws JSONException {
    ContentProviderOperation.Builder builder =
        ContentProviderOperation.newInsert(QuoteProvider.Quotes.CONTENT_URI);

    if (!jsonObject.getString(CHANGE).equals(NULL) && !jsonObject.getString(BID).equals(NULL)) {
      String change = jsonObject.getString(CHANGE);
      builder.withValue(QuoteColumns.SYMBOL, jsonObject.getString(SYMBOL));
      builder.withValue(QuoteColumns.BIDPRICE, truncateBidPrice(jsonObject.getString(BID)));
      builder.withValue(
          QuoteColumns.PERCENT_CHANGE,
          truncateChange(jsonObject.getString(CHANGE_IN_PERCENT), true));
      builder.withValue(QuoteColumns.CHANGE, truncateChange(change, false));
      builder.withValue(QuoteColumns.ISCURRENT, 1);
      if (change.charAt(0) == '-') {
        builder.withValue(QuoteColumns.ISUP, 0);
      } else {
        builder.withValue(QuoteColumns.ISUP, 1);
      }

    } else {
      return null;
    }
    return builder.build();
  }
Exemplo n.º 17
0
  /**
   * Finds all apks from the repo we are currently updating, that belong to the specified app, and
   * delete them as they are no longer provided by that repo.
   */
  @Nullable
  private ContentProviderOperation deleteOrphanedApks(
      List<App> apps, Map<String, List<Apk>> packages) {
    String[] projection =
        new String[] {ApkProvider.DataColumns.PACKAGE_NAME, ApkProvider.DataColumns.VERSION_CODE};
    List<Apk> existing = ApkProvider.Helper.find(context, repo, apps, projection);
    List<Apk> toDelete = new ArrayList<>();

    for (Apk existingApk : existing) {
      boolean shouldStay = false;

      if (packages.containsKey(existingApk.packageName)) {
        for (Apk newApk : packages.get(existingApk.packageName)) {
          if (newApk.vercode == existingApk.vercode) {
            shouldStay = true;
            break;
          }
        }
      }

      if (!shouldStay) {
        toDelete.add(existingApk);
      }
    }

    if (toDelete.size() == 0) {
      return null;
    }
    Uri uri = TempApkProvider.getApksUri(repo, toDelete);
    return ContentProviderOperation.newDelete(uri).build();
  }
 /** M: Wipe the records from MessageStateChange table which belong to mMailbox */
 private void wipeMessageStateChanges() {
   Cursor c =
       mContentResolver.query(
           Message.CONTENT_URI,
           new String[] {MessageColumns.MESSAGE_ID},
           MessageColumns.MAILBOX_KEY + "=?",
           new String[] {String.valueOf(mMailbox.mId)},
           null);
   if (c == null) {
     LogUtils.i(Eas.BSK_TAG, "Get message cursor failed");
     return;
   }
   try {
     ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
     while (c.moveToNext()) {
       ops.add(
           ContentProviderOperation.newDelete(MessageStateChange.CONTENT_URI)
               .withSelection(
                   MessageChangeLogTable.MESSAGE_KEY + "=?", new String[] {c.getString(0)})
               .build());
       applyBatchIfNeeded(ops, MAX_OPS_PER_BATCH, false);
     }
     applyBatchIfNeeded(ops, MAX_OPS_PER_BATCH, true);
   } catch (RemoteException e) {
     LogUtils.i(Eas.BSK_TAG, "RemoteException when wipeMessageStateChanges");
   } catch (OperationApplicationException e) {
     LogUtils.i(Eas.BSK_TAG, "OperationApplicationException when wipeMessageStateChanges");
   } finally {
     c.close();
   }
 }
  /**
   * Delete the users that are present in the local content providers, but are not returned anymore
   * by Dailymotion. It means that these users are outdated and should not be proposed to the user.
   *
   * @return A boolean indicating if the deletion successfully occured.
   */
  private boolean deleteOutdatedUsers() {
    if (mLocalUsers.size() > 0) {
      int count = mLocalUsers.size();
      KidsLogger.i(LOG_TAG, String.format("Removing %d users from db", count));
      ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(count);
      for (String key : mLocalUsers.keySet()) {
        ContentProviderOperation operation =
            ContentProviderOperation.newDelete(UsersProvider.CONTENT_URI)
                .withSelection(UserContract.DAILYMOTION_ID + "=?", new String[] {key})
                .build();
        ops.add(operation);
      }
      try {
        return mContentResolver.applyBatch(UsersProvider.AUTHORITY, ops).length == count;
      } catch (RemoteException e) {
        // Should not happen, the Content Provider is local.
        KidsLogger.w(LOG_TAG, "An exception occured while communicating with provider.");
        return false;
      } catch (OperationApplicationException e) {
        KidsLogger.w(LOG_TAG, "An operation has failed when deleting local users.");
        return false;
      }
    }

    return true;
  }
Exemplo n.º 20
0
  @Override
  protected void notifyUpdate(Iterable<PicItem> entities) {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    for (PicItem entity : entities) {
      Long key = getKey(entity);
      if (key != null) {
        notifyExtraOb(key);

        ops.add(
            ContentProviderOperation.newUpdate(ContentUris.withAppendedId(CONTENT_URI, key))
                .withValue(null, null)
                .build());
      }
    }

    try {
      if (contextWeakReference.get() != null)
        contextWeakReference.get().getContentResolver().applyBatch(AUTHORITY, ops);
    } catch (RemoteException e) {
      e.printStackTrace();
    } catch (OperationApplicationException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 21
0
 @Override
 public void setCTag(String cTag) {
   pendingOperations.add(
       ContentProviderOperation.newUpdate(ContentUris.withAppendedId(calendarsURI(), id))
           .withValue(COLLECTION_COLUMN_CTAG, cTag)
           .build());
 }
Exemplo n.º 22
0
  public static void insert(Context context, UserData userData) {
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    ContentValues cv = new ContentValues();
    cv.put(DatabaseContract.MemberInfoTable.KEY_MEM_ID, userData.id);
    cv.put(DatabaseContract.MemberInfoTable.KEY_MEM_PWD, userData.pwd);
    cv.put(DatabaseContract.MemberInfoTable.KEY_MEM_NAME, userData.name);
    cv.put(DatabaseContract.MemberInfoTable.KEY_MEM_EMAIL, userData.email);
    cv.put(DatabaseContract.MemberInfoTable.KEY_MEM_HOMEPAGE, userData.homepage);
    cv.put(DatabaseContract.MemberInfoTable.KEY_MEM_LEVEL, userData.level);
    cv.put(DatabaseContract.MemberInfoTable.KEY_MEM_POINT, userData.point);
    cv.put(DatabaseContract.MemberInfoTable.KEY_MEM_COMMENT, userData.comment);
    cv.put(
        DatabaseContract.MemberInfoTable.KEY_MEM_DISCLOSE_INFO,
        userData.discloseInfo == true ? 1 : 0);
    cv.put(
        DatabaseContract.MemberInfoTable.KEY_MEM_IS_SHOW_COMMENT,
        userData.isShowComment == true ? 1 : 0);
    cv.put(DatabaseContract.MemberInfoTable.KEY_MEM_SERVER, userData.server);

    operations.add(
        ContentProviderOperation.newInsert(DatabaseContract.MemberInfoTable.CONTENT_URI)
            .withValues(cv)
            .build());

    try {
      context.getContentResolver().applyBatch(DatabaseContract.CONTENT_AUTHORITY, operations);
    } catch (RemoteException e) {
      e.printStackTrace();
    } catch (OperationApplicationException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 23
0
  public static void seperate(Context c, long rawContactID) {
    ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
    Cursor cursor =
        c.getContentResolver()
            .query(
                RawContacts.CONTENT_URI,
                new String[] {RawContacts.CONTACT_ID},
                RawContacts._ID + " = '" + rawContactID + "'",
                null,
                null);
    if (cursor.moveToFirst()) {
      long contactID = cursor.getLong(cursor.getColumnIndex(RawContacts.CONTACT_ID));
      Set<Long> ids = getRawContacts(c, contactID, rawContactID);
      for (long id : ids) {
        ContentProviderOperation.Builder builder =
            ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI);
        builder.withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, rawContactID);
        builder.withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, id);
        builder.withValue(
            ContactsContract.AggregationExceptions.TYPE,
            ContactsContract.AggregationExceptions.TYPE_KEEP_SEPARATE);
        operationList.add(builder.build());
      }

      if (operationList.size() > 0)
        try {
          c.getContentResolver().applyBatch(ContactsContract.AUTHORITY, operationList);
        } catch (RemoteException e) {
          Log.e("Error", e.getLocalizedMessage());
        } catch (OperationApplicationException e) {
          Log.e("Error", e.getLocalizedMessage());
        }
    }
    cursor.close();
  }
Exemplo n.º 24
0
  /** Removes all calendar entries associated with Google I/O 2013. */
  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;
  }
  /**
   * Set the policy for an account atomically; this also removes any other policy associated with
   * the account and sets the policy key for the account. If policy is null, the policyKey is set to
   * 0 and the securitySyncKey to null. Also, update the account object to reflect the current
   * policyKey and securitySyncKey
   *
   * @param context the caller's context
   * @param account the account whose policy is to be set
   * @param policy the policy to set, or null if we're clearing the policy
   * @param securitySyncKey the security sync key for this account (ignored if policy is null)
   */
  public static void setAccountPolicy(
      Context context, Account account, Policy policy, String securitySyncKey) {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    // Make sure this is a valid policy set
    if (policy != null) {
      policy.normalize();
      // Add the new policy (no account will yet reference this)
      ops.add(
          ContentProviderOperation.newInsert(Policy.CONTENT_URI)
              .withValues(policy.toContentValues())
              .build());
      // Make the policyKey of the account our newly created policy, and set the sync key
      ops.add(
          ContentProviderOperation.newUpdate(
                  ContentUris.withAppendedId(Account.CONTENT_URI, account.mId))
              .withValueBackReference(AccountColumns.POLICY_KEY, 0)
              .withValue(AccountColumns.SECURITY_SYNC_KEY, securitySyncKey)
              .build());
    } else {
      ops.add(
          ContentProviderOperation.newUpdate(
                  ContentUris.withAppendedId(Account.CONTENT_URI, account.mId))
              .withValue(AccountColumns.SECURITY_SYNC_KEY, null)
              .withValue(AccountColumns.POLICY_KEY, 0)
              .build());
    }

    // Delete the previous policy associated with this account, if any
    if (account.mPolicyKey > 0) {
      ops.add(
          ContentProviderOperation.newDelete(
                  ContentUris.withAppendedId(Policy.CONTENT_URI, account.mPolicyKey))
              .build());
    }

    try {
      context.getContentResolver().applyBatch(EmailContent.AUTHORITY, ops);
      account.refresh(context);
      syncAccount(context, account);
    } catch (RemoteException e) {
      // This is fatal to a remote process
      throw new IllegalStateException("Exception setting account policy.");
    } catch (OperationApplicationException e) {
      // Can't happen; our provider doesn't throw this exception
    }
  }
 // Check if there at least MAX_OPS_PER_BATCH ops in queue and flush if there are.
 // If force is true, flush regardless of size.
 private void applyBatchIfNeeded(
     ArrayList<ContentProviderOperation> ops, int maxOpsPerBatch, boolean force)
     throws RemoteException, OperationApplicationException {
   if (force || ops.size() >= maxOpsPerBatch) {
     // STOPSHIP Remove calculating size of data before ship
     if (LogUtils.isLoggable(TAG, Log.DEBUG)) {
       final Parcel parcel = Parcel.obtain();
       for (ContentProviderOperation op : ops) {
         op.writeToParcel(parcel, 0);
       }
       Log.d(TAG, String.format("Committing %d ops total size=%d", ops.size(), parcel.dataSize()));
       parcel.recycle();
     }
     mContentResolver.applyBatch(EmailContent.AUTHORITY, ops);
     ops.clear();
   }
 }
  /** {@inheritDoc} */
  @Override
  public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver)
      throws XmlPullParserException, IOException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    // Walk document, parsing any incoming entries
    int type;
    while ((type = parser.next()) != END_DOCUMENT) {
      if (type == START_TAG && ENTRY.equals(parser.getName())) {
        // Process single spreadsheet row at a time
        final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser);

        final String speakerId = sanitizeId(entry.get(Columns.SPEAKER_TITLE), true);
        final Uri speakerUri = Speakers.buildSpeakerUri(speakerId);

        // Check for existing details, only update when changed
        final long localUpdated = queryItemUpdated(speakerUri, resolver);
        final long serverUpdated = entry.getUpdated();
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
          Log.v(TAG, "found speaker " + entry.toString());
          Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
        }
        if (localUpdated >= serverUpdated) continue;

        // Clear any existing values for this speaker, treating the
        // incoming details as authoritative.
        batch.add(ContentProviderOperation.newDelete(speakerUri).build());

        final ContentProviderOperation.Builder builder =
            ContentProviderOperation.newInsert(Speakers.CONTENT_URI);

        builder.withValue(SyncColumns.UPDATED, serverUpdated);
        builder.withValue(Speakers.SPEAKER_ID, speakerId);
        builder.withValue(Speakers.SPEAKER_NAME, entry.get(Columns.SPEAKER_TITLE));
        builder.withValue(Speakers.SPEAKER_IMAGE_URL, entry.get(Columns.SPEAKER_IMAGE_URL));
        builder.withValue(Speakers.SPEAKER_COMPANY, entry.get(Columns.SPEAKER_COMPANY));
        builder.withValue(Speakers.SPEAKER_ABSTRACT, entry.get(Columns.SPEAKER_ABSTRACT));
        builder.withValue(Speakers.SPEAKER_URL, entry.get(Columns.SPEAKER_URL));

        // Normal speaker details ready, write to provider
        batch.add(builder.build());
      }
    }

    return batch;
  }
Exemplo n.º 28
0
 /** Creates a empty raw contact with a given masterKeyId */
 private static void insertContact(
     ArrayList<ContentProviderOperation> ops, Context context, long masterKeyId) {
   ops.add(
       ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
           .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, Constants.ACCOUNT_NAME)
           .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, Constants.ACCOUNT_TYPE)
           .withValue(ContactsContract.RawContacts.SOURCE_ID, Long.toString(masterKeyId))
           .build());
 }
Exemplo n.º 29
0
 public void buildCapsuleInsert(Capsule capsule, boolean withYield) {
   // Build the INSERT operation
   ContentProviderOperation.Builder builder =
       ContentProviderOperation.newInsert(CapsuleContract.Capsules.CONTENT_URI);
   builder.withValues(Capsules.buildContentValues(capsule));
   builder.withYieldAllowed(withYield);
   // Add it to the collection
   this.mOperations.add(builder.build());
 }
  @Override
  protected void onHandleIntent(Intent intent) {
    Map<String, String> eventBody = new HashMap<>();
    try {
      // get caller data
      Bundle iArgs = intent.getExtras();
      // src
      String src = iArgs.getString(AppConstants.K.SRC.name());
      eventBody.put(AppConstants.K.SRC.name(), src);

      // srcID
      String srcID = iArgs.getString(AppConstants.K.SRC_ID.name());
      eventBody.put(AppConstants.K.SRC_ID.name(), srcID);

      String notifUID = iArgs.getString(AppConstants.K.NOTIF.name());
      eventBody.put(AppConstants.K.NOTIF.name(), notifUID);

      if (StringUtils.isNotBlank(notifUID)) {
        // LOCAL UPDATE
        ArrayList<ContentProviderOperation> delOps = new ArrayList<>();
        delOps.add(
            ContentProviderOperation.newDelete(SchemaNotifications.CONTENT_URI)
                .withSelection(SchemaNotifications.COLUMN_UID + "=?", new String[] {notifUID})
                .build());
        getContentResolver().applyBatch(AppConstants.API.CONTENT_AUTHORITY.getValue(), delOps);
      } else {
        return;
      }

      // REMOTE UPDATE
      String notifURI = StringUtils.join(new String[] {NOTIFICATIONS.getValue(), notifUID}, "/");

      // body part of request
      Map<String, String> reqBody = new HashMap<>();
      if (!Utils.isLoggedIn()) {
        // UNIQUE ID FOR THIS INSTALL
        reqBody.put(PARAMS.REF.getValue(), Utils.uniqueID());
      }

      ReqSetBody req = new ReqSetBody();
      req.setToken(Utils.getAppToken(false));
      req.setCmd(PARAMS.COMMAND.getValue());
      req.setBody(reqBody);

      // headers
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.APPLICATION_JSON);
      headers.setAccept(RestClient.INSTANCE.jsonMediaType());

      HttpEntity<ReqSetBody> payloadEntity = new HttpEntity<>(req, headers);
      RestClient.INSTANCE.handle().exchange(notifURI, HttpMethod.POST, payloadEntity, Resp.class);
    } catch (Exception e) {
      // muted
    } finally {
      BusProvider.INSTANCE.getBus().post(new Events.SingleNotifsUPDATEEvent(eventBody));
    }
  }