Example usage for android.content ContentValues putNull

List of usage examples for android.content ContentValues putNull

Introduction

In this page you can find the example usage for android.content ContentValues putNull.

Prototype

public void putNull(String key) 

Source Link

Document

Adds a null value to the set.

Usage

From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java

@Test
public void testWriteDataAndMetadataIntoExistingTableWhenIDIsNull_ExpectFail()
        throws ActionNotAuthorizedException {
    String tableId = testTable;//  w  w  w .  java 2s  . c o m
    boolean thrown = false;
    String testColType = ElementDataType.string.name();
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column("col1", "col1", testColType, "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());

    ContentValues cvValues = new ContentValues();
    cvValues.putNull(DataTableColumns.ID);
    cvValues.putNull(DataTableColumns.ROW_ETAG);
    cvValues.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
    cvValues.putNull(DataTableColumns.CONFLICT_TYPE);
    cvValues.putNull(DataTableColumns.DEFAULT_ACCESS);
    cvValues.putNull(DataTableColumns.ROW_OWNER);
    cvValues.putNull(DataTableColumns.GROUP_MODIFY);
    cvValues.putNull(DataTableColumns.GROUP_PRIVILEGED);
    cvValues.putNull(DataTableColumns.GROUP_READ_ONLY);
    cvValues.putNull(DataTableColumns.FORM_ID);
    cvValues.putNull(DataTableColumns.LOCALE);
    cvValues.putNull(DataTableColumns.SAVEPOINT_TYPE);
    cvValues.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
    cvValues.putNull(DataTableColumns.SAVEPOINT_CREATOR);

    try {
        ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, null, activeUser,
                RoleConsts.ADMIN_ROLES_LIST, currentLocale);
    } catch (ActionNotAuthorizedException ex) {
        throw ex;
    } catch (Exception e) {
        thrown = true;
        e.printStackTrace();
    }

    assertTrue(thrown);

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}

From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java

@Test
public void testInsertCheckpointRowIntoExistingTableWithIdWithRowConflictType_ExpectFail()
        throws ActionNotAuthorizedException {
    String tableId = testTable;/*from  www .j a v a 2  s .c om*/
    String testCol = "testColumn";
    String testColType = ElementDataType.string.name();
    String testVal = "test";
    String rowId = LocalizationUtils.genUUID();
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column(testCol, testCol, testColType, "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    ContentValues cvValues = new ContentValues();
    cvValues.put(testCol, testVal);
    cvValues.putNull(DataTableColumns.CONFLICT_TYPE);

    boolean thrown = true;
    try {
        ODKDatabaseImplUtils.get().insertCheckpointRowWithId(db, tableId, orderedColumns, cvValues, rowId,
                activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale);
    } catch (ActionNotAuthorizedException ex) {
        throw ex;
    } catch (Exception e) {
        thrown = true;
        e.printStackTrace();
    }

    assertTrue(thrown);

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}

From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java

@Test
public void testInsertCheckpointRowIntoExistingTableWithIdWithRowSavepointType_ExpectFail()
        throws ActionNotAuthorizedException {
    String tableId = testTable;//from   w ww  .ja v a 2s  .c o  m
    String testCol = "testColumn";
    String testColType = ElementDataType.string.name();
    String testVal = "test";
    String rowId = LocalizationUtils.genUUID();
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column(testCol, testCol, testColType, "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    ContentValues cvValues = new ContentValues();
    cvValues.put(testCol, testVal);
    cvValues.putNull(DataTableColumns.SAVEPOINT_TYPE);

    boolean thrown = true;
    try {
        ODKDatabaseImplUtils.get().insertCheckpointRowWithId(db, tableId, orderedColumns, cvValues, rowId,
                activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale);
    } catch (ActionNotAuthorizedException ex) {
        throw ex;
    } catch (Exception e) {
        thrown = true;
        e.printStackTrace();
    }

    assertTrue(thrown);

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}

From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java

@Test
public void testInsertCheckpointRowIntoExistingTableWithIdWithRowSavepointTimestamp_ExpectFail()
        throws ActionNotAuthorizedException {
    String tableId = testTable;//from   w ww  .j a v  a 2 s . c  o  m
    String testCol = "testColumn";
    String testColType = ElementDataType.string.name();
    String testVal = "test";
    String rowId = LocalizationUtils.genUUID();
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column(testCol, testCol, testColType, "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    ContentValues cvValues = new ContentValues();
    cvValues.put(testCol, testVal);
    cvValues.putNull(DataTableColumns.SAVEPOINT_TIMESTAMP);

    boolean thrown = true;
    try {
        ODKDatabaseImplUtils.get().insertCheckpointRowWithId(db, tableId, orderedColumns, cvValues, rowId,
                activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale);
    } catch (ActionNotAuthorizedException ex) {
        throw ex;
    } catch (Exception e) {
        thrown = true;
        e.printStackTrace();
    }

    assertTrue(thrown);

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}

From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java

@Test
public void testWriteDataAndMetadataIntoExistingTableWhenSyncStateIsNull_ExpectSuccess()
        throws ActionNotAuthorizedException {
    String tableId = testTable;/*ww w  .j a  va  2  s .co  m*/
    boolean thrown = false;
    String testColType = ElementDataType.string.name();
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column("col1", "col1", testColType, "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    String uuid = UUID.randomUUID().toString();
    String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());

    ContentValues cvValues = new ContentValues();
    cvValues.put(DataTableColumns.ID, uuid);
    cvValues.putNull(DataTableColumns.ROW_ETAG);
    cvValues.putNull(DataTableColumns.SYNC_STATE);
    cvValues.putNull(DataTableColumns.CONFLICT_TYPE);
    cvValues.putNull(DataTableColumns.DEFAULT_ACCESS);
    cvValues.putNull(DataTableColumns.ROW_OWNER);
    cvValues.putNull(DataTableColumns.GROUP_MODIFY);
    cvValues.putNull(DataTableColumns.GROUP_PRIVILEGED);
    cvValues.putNull(DataTableColumns.GROUP_READ_ONLY);
    cvValues.putNull(DataTableColumns.FORM_ID);
    cvValues.putNull(DataTableColumns.LOCALE);
    cvValues.putNull(DataTableColumns.SAVEPOINT_TYPE);
    cvValues.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
    cvValues.putNull(DataTableColumns.SAVEPOINT_CREATOR);

    try {
        ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, uuid, activeUser,
                RoleConsts.ADMIN_ROLES_LIST, currentLocale);
    } catch (ActionNotAuthorizedException ex) {
        throw ex;
    } catch (Exception e) {
        thrown = true;
        e.printStackTrace();
    }

    assertFalse(thrown);

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}

From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java

@Test
public void testWriteDataAndMetadataIntoExistingTableWhenTimeStampIsNull_ExpectFail()
        throws ActionNotAuthorizedException {
    // TODO: should this fail or succeed?
    String tableId = testTable;// ww  w  .j  a  v a2  s  .  c  o m
    boolean thrown = false;

    String testColType = ElementDataType.string.name();
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column("col1", "col1", testColType, "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    String uuid = UUID.randomUUID().toString();

    ContentValues cvValues = new ContentValues();
    cvValues.put(DataTableColumns.ID, uuid);
    cvValues.putNull(DataTableColumns.ROW_ETAG);
    cvValues.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
    cvValues.putNull(DataTableColumns.CONFLICT_TYPE);
    cvValues.putNull(DataTableColumns.DEFAULT_ACCESS);
    cvValues.putNull(DataTableColumns.ROW_OWNER);
    cvValues.putNull(DataTableColumns.GROUP_MODIFY);
    cvValues.putNull(DataTableColumns.GROUP_PRIVILEGED);
    cvValues.putNull(DataTableColumns.GROUP_READ_ONLY);
    cvValues.putNull(DataTableColumns.FORM_ID);
    cvValues.putNull(DataTableColumns.LOCALE);
    cvValues.putNull(DataTableColumns.SAVEPOINT_TYPE);
    cvValues.putNull(DataTableColumns.SAVEPOINT_TIMESTAMP);
    cvValues.putNull(DataTableColumns.SAVEPOINT_CREATOR);

    try {
        ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, uuid, activeUser,
                RoleConsts.ADMIN_ROLES_LIST, currentLocale);
    } catch (ActionNotAuthorizedException ex) {
        throw ex;
    } catch (Exception e) {
        thrown = true;
        e.printStackTrace();
    }

    // TODO: should this fail or succeed?
    // assertTrue(thrown);
    assertFalse(thrown);

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}

From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java

@Test
public void testWriteDataAndMetadataIntoExistingTableWithValidValue_ExpectPass()
        throws ActionNotAuthorizedException {
    String tableId = testTable;/* w w w  .java 2  s. c om*/
    String testColType = ElementDataType.string.name();
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column("col1", "col1", testColType, "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get().getAccessContext(db, tableId,
            activeUser, RoleConsts.ADMIN_ROLES_LIST);

    String uuid = UUID.randomUUID().toString();
    String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());

    ContentValues cvValues = new ContentValues();
    cvValues.put(DataTableColumns.ID, uuid);
    cvValues.putNull(DataTableColumns.ROW_ETAG);
    cvValues.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
    cvValues.putNull(DataTableColumns.CONFLICT_TYPE);
    cvValues.putNull(DataTableColumns.DEFAULT_ACCESS);
    cvValues.putNull(DataTableColumns.ROW_OWNER);
    cvValues.putNull(DataTableColumns.GROUP_MODIFY);
    cvValues.putNull(DataTableColumns.GROUP_PRIVILEGED);
    cvValues.putNull(DataTableColumns.GROUP_READ_ONLY);
    cvValues.putNull(DataTableColumns.FORM_ID);
    cvValues.putNull(DataTableColumns.LOCALE);
    cvValues.putNull(DataTableColumns.SAVEPOINT_TYPE);
    cvValues.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
    cvValues.putNull(DataTableColumns.SAVEPOINT_CREATOR);

    ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, uuid, activeUser,
            RoleConsts.ADMIN_ROLES_LIST, currentLocale);

    // Select everything out of the table
    String sel = "SELECT * FROM " + tableId + " WHERE " + DataTableColumns.ID + " = ?";
    String[] selArgs = { uuid };
    Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

    while (cursor.moveToNext()) {
        int ind = cursor.getColumnIndex(DataTableColumns.SAVEPOINT_TIMESTAMP);
        String ts = cursor.getString(ind);
        assertEquals(ts, timeStamp);

        ind = cursor.getColumnIndex(DataTableColumns.SYNC_STATE);
        String ss = cursor.getString(ind);
        assertEquals(ss, SyncState.new_row.name());
    }

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}

From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java

@Test
public void testDeleteServerConflictRowWithIdAndLocDelOldVals_ExpectPass() throws ActionNotAuthorizedException {
    String tableId = testTable;/*from  w w w .  j a v a  2  s  .c  o  m*/
    String testCol = "testColumn";
    String testColType = ElementDataType.integer.name();
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column(testCol, testCol, testColType, "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get().getAccessContext(db, tableId,
            activeUser, RoleConsts.ADMIN_ROLES_LIST);

    int testVal = 5;

    // local record that is synced and pending deletion...

    ContentValues cvValues = new ContentValues();
    String rowId = LocalizationUtils.genUUID();
    cvValues.put(testCol, testVal);
    cvValues.put(DataTableColumns.ROW_ETAG, LocalizationUtils.genUUID());
    cvValues.put(DataTableColumns.SYNC_STATE, SyncState.deleted.name());
    ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, rowId, activeUser,
            RoleConsts.ADMIN_ROLES_LIST, currentLocale);

    // Select everything out of the table
    String sel = "SELECT * FROM " + tableId + " WHERE " + DataTableColumns.ID + " = ? ORDER BY "
            + DataTableColumns.CONFLICT_TYPE + " ASC";
    String[] selArgs = { rowId };
    Cursor cursor = null;

    int val = 0;
    try {
        cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);
        assertEquals(cursor.getCount(), 1);

        while (cursor.moveToNext()) {
            int ind = cursor.getColumnIndex(testCol);
            int type = cursor.getType(ind);
            assertEquals(type, Cursor.FIELD_TYPE_INTEGER);
            val = cursor.getInt(ind);
        }
    } finally {
        cursor.close();
    }

    assertEquals(val, testVal);

    // NOTE: all metadata fields need to be specified
    // server has a change...
    ContentValues updates = new ContentValues();
    // data value
    updates.put(testCol, testVal + 6);
    // metadata fields
    updates.put(DataTableColumns.CONFLICT_TYPE, ConflictType.SERVER_UPDATED_UPDATED_VALUES);
    updates.put(DataTableColumns.SYNC_STATE, SyncState.in_conflict.name());
    updates.put(DataTableColumns.ROW_ETAG, LocalizationUtils.genUUID());
    // insert in_conflict server row
    updates.put(DataTableColumns.FORM_ID, "serverForm");
    updates.put(DataTableColumns.LOCALE, currentLocale);
    updates.put(DataTableColumns.SAVEPOINT_TIMESTAMP,
            TableConstants.nanoSecondsFromMillis(System.currentTimeMillis()));
    updates.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
    updates.put(DataTableColumns.SAVEPOINT_CREATOR, "mailto:server@gmail.com");
    updates.put(DataTableColumns.DEFAULT_ACCESS, RowFilterScope.Access.FULL.name());
    updates.put(DataTableColumns.ROW_OWNER, "mailto:server@gmail.com");
    updates.putNull(DataTableColumns.GROUP_READ_ONLY);
    updates.putNull(DataTableColumns.GROUP_MODIFY);
    updates.putNull(DataTableColumns.GROUP_PRIVILEGED);

    // Place row in conflict
    int conflictType = ConflictType.LOCAL_DELETED_OLD_VALUES;
    ODKDatabaseImplUtils.get().privilegedPlaceRowIntoConflictWithId(db, tableId, orderedColumns, updates, rowId,
            conflictType, activeUser, currentLocale);

    // Run the query again and make sure that the place row in conflict worked as expected
    String whereClause = DataTableColumns.ID + "=?";
    String[] selectionArgs = new String[] { rowId };
    String[] orderByKeys = new String[] { DataTableColumns.CONFLICT_TYPE };
    String[] orderByDirs = new String[] { "ASC" };
    List<String> adminColumns = ODKDatabaseImplUtils.get().getAdminColumns();
    String[] adminColArr = adminColumns.toArray(new String[adminColumns.size()]);

    BaseTable baseTable = ODKDatabaseImplUtils.get().query(db, tableId,
            QueryUtil.buildSqlStatement(tableId, whereClause, null, null, orderByKeys, orderByDirs),
            selectionArgs, null, accessContext);
    UserTable table = new UserTable(baseTable, orderedColumns, adminColArr);

    assertEquals(table.getNumberOfRows(), 2);

    Row first = table.getRowAtIndex(0);
    Row second = table.getRowAtIndex(1);

    String v;
    int conflictTypeVal;

    v = first.getDataByKey(DataTableColumns.CONFLICT_TYPE);
    assertNotNull(v);
    conflictTypeVal = Integer.valueOf(v);
    assertEquals(conflictType, conflictTypeVal);

    v = second.getDataByKey(DataTableColumns.CONFLICT_TYPE);
    assertNotNull(v);
    conflictTypeVal = Integer.valueOf(v);
    assertEquals(ConflictType.SERVER_UPDATED_UPDATED_VALUES, conflictTypeVal);

    // Now delete the row
    ODKDatabaseImplUtils.get().resolveServerConflictWithDeleteRowWithId(db, tableId, rowId, activeUser);

    // Run the query yet again to make sure that things worked as expected
    baseTable = ODKDatabaseImplUtils.get().query(db, tableId,
            QueryUtil.buildSqlStatement(tableId, whereClause, null, null, orderByKeys, orderByDirs),
            selectionArgs, null, accessContext);
    table = new UserTable(baseTable, orderedColumns, adminColArr);

    assertEquals(table.getNumberOfRows(), 0);

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

private void upsertDataIntoExistingDBTable(SQLiteDatabase db, String tableId,
        ArrayList<ColumnDefinition> orderedColumns, ContentValues cvValues, boolean shouldUpdate) {
    String rowId = null;/*from w  w w .  ja v a  2s  . co  m*/
    String whereClause = null;
    boolean specifiesConflictType = cvValues.containsKey(DataTableColumns.CONFLICT_TYPE);
    boolean nullConflictType = specifiesConflictType && (cvValues.get(DataTableColumns.CONFLICT_TYPE) == null);
    String[] whereArgs = new String[specifiesConflictType ? (1 + (nullConflictType ? 0 : 1)) : 1];
    boolean update = false;

    if (cvValues.size() <= 0) {
        throw new IllegalArgumentException(t + ": No values to add into table " + tableId);
    }

    ContentValues cvDataTableVal = new ContentValues();
    cvDataTableVal.putAll(cvValues);

    if (cvDataTableVal.containsKey(DataTableColumns.ID)) {
        // The user specified a row id; we need to determine whether to
        // insert or update the record, or to reject the action because
        // there are either checkpoint records for this row id, or, if
        // a server conflict is associated with this row, that the
        // _conflict_type to update was not specified.
        //
        // i.e., the tuple (_id, _conflict_type) should be unique. If
        // we find that there are more than 0 or 1 records matching this
        // tuple, then we should reject the update request.
        //
        // TODO: perhaps we want to allow updates to the local conflict
        // row if there are no checkpoints on it? I.e., change the
        // tri-state conflict type to a pair of states (local / remote).
        // and all local changes are flagged local. Remote only exists
        // if the server is in conflict.

        rowId = cvDataTableVal.getAsString(DataTableColumns.ID);
        if (rowId == null) {
            throw new IllegalArgumentException(DataTableColumns.ID + ", if specified, cannot be null");
        }

        if (specifiesConflictType) {
            if (nullConflictType) {
                whereClause = DataTableColumns.ID + " = ?" + " AND " + DataTableColumns.CONFLICT_TYPE
                        + " IS NULL";
                whereArgs[0] = rowId;
            } else {
                whereClause = DataTableColumns.ID + " = ?" + " AND " + DataTableColumns.CONFLICT_TYPE + " = ?";
                whereArgs[0] = rowId;
                whereArgs[1] = cvValues.getAsString(DataTableColumns.CONFLICT_TYPE);
            }
        } else {
            whereClause = DataTableColumns.ID + " = ?";
            whereArgs[0] = rowId;
        }

        String sel = "SELECT * FROM " + tableId + " WHERE " + whereClause;
        String[] selArgs = whereArgs;
        Cursor cursor = rawQuery(db, sel, selArgs);

        // There must be only one row in the db for the update to work
        if (shouldUpdate) {
            if (cursor.getCount() == 1) {
                update = true;
            } else if (cursor.getCount() > 1) {
                throw new IllegalArgumentException(
                        t + ": row id " + rowId + " has more than 1 row in table " + tableId);
            }
        } else {
            if (cursor.getCount() > 0) {
                throw new IllegalArgumentException(
                        t + ": id " + rowId + " is already present in table " + tableId);
            }
        }

    } else {
        rowId = "uuid:" + UUID.randomUUID().toString();
    }

    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields

    if (!cvDataTableVal.containsKey(DataTableColumns.ID)) {
        cvDataTableVal.put(DataTableColumns.ID, rowId);
    }

    if (update) {
        if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE)
                || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) {
            cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.changed.name());
        }

        if (cvDataTableVal.containsKey(DataTableColumns.LOCALE)
                && (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
            cvDataTableVal.put(DataTableColumns.LOCALE, DataTableColumns.DEFAULT_LOCALE);
        }

        if (cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
                && (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
                || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
            String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, DataTableColumns.DEFAULT_SAVEPOINT_CREATOR);
        }
    } else {

        if (!cvDataTableVal.containsKey(DataTableColumns.ROW_ETAG)
                || cvDataTableVal.get(DataTableColumns.ROW_ETAG) == null) {
            cvDataTableVal.put(DataTableColumns.ROW_ETAG, DataTableColumns.DEFAULT_ROW_ETAG);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE)
                || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) {
            cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.CONFLICT_TYPE)) {
            cvDataTableVal.putNull(DataTableColumns.CONFLICT_TYPE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FILTER_TYPE)
                || (cvDataTableVal.get(DataTableColumns.FILTER_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.FILTER_TYPE, DataTableColumns.DEFAULT_FILTER_TYPE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FILTER_VALUE)
                || (cvDataTableVal.get(DataTableColumns.FILTER_VALUE) == null)) {
            cvDataTableVal.put(DataTableColumns.FILTER_VALUE, DataTableColumns.DEFAULT_FILTER_VALUE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FORM_ID)) {
            cvDataTableVal.putNull(DataTableColumns.FORM_ID);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.LOCALE)
                || (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
            cvDataTableVal.put(DataTableColumns.LOCALE, DataTableColumns.DEFAULT_LOCALE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
                || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
            String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, DataTableColumns.DEFAULT_SAVEPOINT_CREATOR);
        }
    }

    cleanUpValuesMap(orderedColumns, cvDataTableVal);

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        if (update) {
            db.update(tableId, cvDataTableVal, whereClause, whereArgs);
        } else {
            db.insertOrThrow(tableId, null, cvDataTableVal);
        }

        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }

}

From source file:com.android.exchange.EasSyncService.java

/**
 * Performs FolderSync/*from   ww  w  .  ja va  2 s.c o m*/
 *
 * @throws IOException
 * @throws EasParserException
 */
public void runAccountMailbox() throws IOException, EasParserException {
    // Initialize exit status to success
    mExitStatus = EmailServiceStatus.SUCCESS;
    try {
        try {
            SyncManager.callback().syncMailboxListStatus(mAccount.mId, EmailServiceStatus.IN_PROGRESS, 0);
        } catch (RemoteException e1) {
            // Don't care if this fails
        }

        if (mAccount.mSyncKey == null) {
            mAccount.mSyncKey = "0";
            userLog("Account syncKey INIT to 0");
            ContentValues cv = new ContentValues();
            cv.put(AccountColumns.SYNC_KEY, mAccount.mSyncKey);
            mAccount.update(mContext, cv);
        }

        boolean firstSync = mAccount.mSyncKey.equals("0");
        if (firstSync) {
            userLog("Initial FolderSync");
        }

        // When we first start up, change all mailboxes to push.
        ContentValues cv = new ContentValues();
        cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH);
        if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING,
                new String[] { Long.toString(mAccount.mId) }) > 0) {
            SyncManager.kick("change ping boxes to push");
        }

        // Determine our protocol version, if we haven't already and save it in the Account
        // Also re-check protocol version at least once a day (in case of upgrade)
        if (mAccount.mProtocolVersion == null || ((System.currentTimeMillis() - mMailbox.mSyncTime) > DAYS)) {
            userLog("Determine EAS protocol version");
            HttpResponse resp = sendHttpClientOptions();
            int code = resp.getStatusLine().getStatusCode();
            userLog("OPTIONS response: ", code);
            if (code == HttpStatus.SC_OK) {
                Header header = resp.getFirstHeader("MS-ASProtocolCommands");
                userLog(header.getValue());
                header = resp.getFirstHeader("ms-asprotocolversions");
                try {
                    setupProtocolVersion(this, header);
                } catch (MessagingException e) {
                    // Since we've already validated, this can't really happen
                    // But if it does, we'll rethrow this...
                    throw new IOException();
                }
                // Save the protocol version
                cv.clear();
                // Save the protocol version in the account
                cv.put(Account.PROTOCOL_VERSION, mProtocolVersion);
                mAccount.update(mContext, cv);
                cv.clear();
                // Save the sync time of the account mailbox to current time
                cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis());
                mMailbox.update(mContext, cv);
            } else {
                errorLog("OPTIONS command failed; throwing IOException");
                throw new IOException();
            }
        }

        // Change all pushable boxes to push when we start the account mailbox
        if (mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH) {
            cv.clear();
            cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH);
            if (mContentResolver.update(Mailbox.CONTENT_URI, cv, SyncManager.WHERE_IN_ACCOUNT_AND_PUSHABLE,
                    new String[] { Long.toString(mAccount.mId) }) > 0) {
                userLog("Push account; set pushable boxes to push...");
            }
        }

        while (!mStop) {
            userLog("Sending Account syncKey: ", mAccount.mSyncKey);
            Serializer s = new Serializer();
            s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY).text(mAccount.mSyncKey).end().end()
                    .done();
            HttpResponse resp = sendHttpClientPost("FolderSync", s.toByteArray());
            if (mStop)
                break;
            int code = resp.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                HttpEntity entity = resp.getEntity();
                int len = (int) entity.getContentLength();
                if (len != 0) {
                    InputStream is = entity.getContent();
                    // Returns true if we need to sync again
                    if (new FolderSyncParser(is, new AccountSyncAdapter(mMailbox, this)).parse()) {
                        continue;
                    }
                }
            } else if (isProvisionError(code)) {
                // If the sync error is a provisioning failure (perhaps the policies changed),
                // let's try the provisioning procedure
                // Provisioning must only be attempted for the account mailbox - trying to
                // provision any other mailbox may result in race conditions and the creation
                // of multiple policy keys.
                if (!tryProvision()) {
                    // Set the appropriate failure status
                    mExitStatus = EXIT_SECURITY_FAILURE;
                    return;
                } else {
                    // If we succeeded, try again...
                    continue;
                }
            } else if (isAuthError(code)) {
                mExitStatus = EXIT_LOGIN_FAILURE;
                return;
            } else {
                userLog("FolderSync response error: ", code);
            }

            // Change all push/hold boxes to push
            cv.clear();
            cv.put(Mailbox.SYNC_INTERVAL, Account.CHECK_INTERVAL_PUSH);
            if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX,
                    new String[] { Long.toString(mAccount.mId) }) > 0) {
                userLog("Set push/hold boxes to push...");
            }

            try {
                SyncManager.callback().syncMailboxListStatus(mAccount.mId, mExitStatus, 0);
            } catch (RemoteException e1) {
                // Don't care if this fails
            }

            // Before each run of the pingLoop, if this Account has a PolicySet, make sure it's
            // active; otherwise, clear out the key/flag.  This should cause a provisioning
            // error on the next POST, and start the security sequence over again
            String key = mAccount.mSecuritySyncKey;
            if (!TextUtils.isEmpty(key)) {
                PolicySet ps = new PolicySet(mAccount);
                SecurityPolicy sp = SecurityPolicy.getInstance(mContext);
                if (!sp.isActive(ps)) {
                    cv.clear();
                    cv.put(AccountColumns.SECURITY_FLAGS, 0);
                    cv.putNull(AccountColumns.SECURITY_SYNC_KEY);
                    long accountId = mAccount.mId;
                    mContentResolver.update(ContentUris.withAppendedId(Account.CONTENT_URI, accountId), cv,
                            null, null);
                    sp.policiesRequired(accountId);
                }
            }

            // Wait for push notifications.
            String threadName = Thread.currentThread().getName();
            try {
                runPingLoop();
            } catch (StaleFolderListException e) {
                // We break out if we get told about a stale folder list
                userLog("Ping interrupted; folder list requires sync...");
            } catch (IllegalHeartbeatException e) {
                // If we're sending an illegal heartbeat, reset either the min or the max to
                // that heartbeat
                resetHeartbeats(e.mLegalHeartbeat);
            } finally {
                Thread.currentThread().setName(threadName);
            }
        }
    } catch (IOException e) {
        // We catch this here to send the folder sync status callback
        // A folder sync failed callback will get sent from run()
        try {
            if (!mStop) {
                SyncManager.callback().syncMailboxListStatus(mAccount.mId, EmailServiceStatus.CONNECTION_ERROR,
                        0);
            }
        } catch (RemoteException e1) {
            // Don't care if this fails
        }
        throw e;
    }
}