Example usage for android.database Cursor isNull

List of usage examples for android.database Cursor isNull

Introduction

In this page you can find the example usage for android.database Cursor isNull.

Prototype

boolean isNull(int columnIndex);

Source Link

Document

Returns true if the value in the indicated column is null.

Usage

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

@Test
public void testDeleteLastCheckpointRowWithId_ExpectPass() throws ActionNotAuthorizedException {
    String tableId = testTable;//from   ww w .ja va  2 s.co  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);

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

    ContentValues cvValues = new ContentValues();
    cvValues.put(testCol, testVal);
    ODKDatabaseImplUtils.get().insertCheckpointRowWithId(db, tableId, orderedColumns, cvValues, rowId,
            activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale);

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

    String val = null;
    while (cursor.moveToNext()) {
        int ind = cursor.getColumnIndex(testCol);
        int type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        val = cursor.getString(ind);

        ind = cursor.getColumnIndex(DataTableColumns.SAVEPOINT_TYPE);
        assertTrue(cursor.isNull(ind));

        // Get the conflict_type and make sure that it is null
        ind = cursor.getColumnIndex(DataTableColumns.CONFLICT_TYPE);
        assertTrue(cursor.isNull(ind));
    }

    assertEquals(val, testVal);

    ODKDatabaseImplUtils.get().deleteLastCheckpointRowWithId(db, tableId, rowId, activeUser,
            RoleConsts.ADMIN_ROLES_LIST);
    // Select everything out of the table
    sel = "SELECT * FROM " + tableId;
    selArgs = new String[0];
    cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

    assertEquals(cursor.getCount(), 0);

    // 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 testDeleteCheckpointRowsWithValidId_ExpectPass() throws ActionNotAuthorizedException {
    String tableId = testTable;//w w w  .  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);

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

    ContentValues cvValues = new ContentValues();
    cvValues.put(testCol, testVal);
    ODKDatabaseImplUtils.get().insertCheckpointRowWithId(db, tableId, orderedColumns, cvValues, rowId,
            activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale);

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

    String val = null;
    while (cursor.moveToNext()) {
        int ind = cursor.getColumnIndex(testCol);
        int type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        val = cursor.getString(ind);

        ind = cursor.getColumnIndex(DataTableColumns.SAVEPOINT_TYPE);
        assertTrue(cursor.isNull(ind));

        // Get the conflict_type and make sure that it is null
        ind = cursor.getColumnIndex(DataTableColumns.CONFLICT_TYPE);
        assertTrue(cursor.isNull(ind));
    }

    assertEquals(val, testVal);

    ODKDatabaseImplUtils.get().deleteAllCheckpointRowsWithId(db, tableId, rowId, activeUser,
            RoleConsts.ADMIN_ROLES_LIST);
    // Select everything out of the table
    sel = "SELECT * FROM " + tableId;
    selArgs = new String[0];
    cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

    assertEquals(cursor.getCount(), 0);

    // 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 testDeleteCheckpointRowsWithInvalidId_ExpectFail() throws ActionNotAuthorizedException {
    String tableId = testTable;/*  w w w. ja v a2  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);

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

    ContentValues cvValues = new ContentValues();
    cvValues.put(testCol, testVal);
    ODKDatabaseImplUtils.get().insertCheckpointRowWithId(db, tableId, orderedColumns, cvValues, rowId,
            activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale);

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

    String val = null;
    while (cursor.moveToNext()) {
        int ind = cursor.getColumnIndex(testCol);
        int type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        val = cursor.getString(ind);

        ind = cursor.getColumnIndex(DataTableColumns.SAVEPOINT_TYPE);
        assertTrue(cursor.isNull(ind));

        // Get the conflict_type and make sure that it is null
        ind = cursor.getColumnIndex(DataTableColumns.CONFLICT_TYPE);
        assertTrue(cursor.isNull(ind));
    }

    assertEquals(val, testVal);

    String invalidRowId = LocalizationUtils.genUUID();
    boolean thrown = true;
    try {
        ODKDatabaseImplUtils.get().deleteAllCheckpointRowsWithId(db, tableId, invalidRowId, activeUser,
                RoleConsts.ADMIN_ROLES_LIST);
    } catch (ActionNotAuthorizedException ex) {
        throw ex;
    } catch (Exception e) {
        thrown = true;
        e.printStackTrace();
    }

    assertTrue(thrown);

    // Select everything out of the table
    sel = "SELECT * FROM " + tableId;
    selArgs = new String[0];
    cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

    assertEquals(cursor.getCount(), 1);

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

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

public void testInsertCheckpointRowIntoExistingTableWithIdWhenRowIdNotProvided_ExpectPass()
        throws ActionNotAuthorizedException {
    String tableId = testTable;/*from   w ww  .ja  v  a2 s .com*/
    String testCol = "testColumn";
    String testColType = ElementDataType.string.name();
    String testVal = "test";
    String rowId = null;
    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);

    ContentValues cvValues = new ContentValues();
    cvValues.put(testCol, testVal);
    ODKDatabaseImplUtils.get().insertCheckpointRowWithId(db, tableId, orderedColumns, cvValues, rowId,
            activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale);

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

    String val = null;
    String saveptType = null;
    while (cursor.moveToNext()) {
        int ind = cursor.getColumnIndex(testCol);
        int type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        val = cursor.getString(ind);

        ind = cursor.getColumnIndex(DataTableColumns.SAVEPOINT_TIMESTAMP);
        type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        saveptType = cursor.getString(ind);

        // Get the conflict_type and make sure that it is null
        ind = cursor.getColumnIndex(DataTableColumns.CONFLICT_TYPE);
        assertTrue(cursor.isNull(ind));
    }

    assertEquals(val, testVal);

    // Also make sure that the savepoint_type
    // is empty
    assertNotSame(saveptType, SavepointTypeManipulator.incomplete());
    assertNotSame(saveptType, SavepointTypeManipulator.complete());

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

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

private void internalTestMemoryLeakCycling_ExpectPass(int maxIterations) throws ActionNotAuthorizedException {

    LinkedList<byte[]> byteQueue = new LinkedList<byte[]>();

    String tableId = "memoryTest";
    int maxBytes = 32;
    String testColType = ElementDataType.string.name();

    for (int j = 0; j < maxIterations; ++j) {
        if (j % 10 == 0) {
            System.out.println("iteration " + j + " of " + maxIterations);
        }/*  w  w w .ja va  2  s  .  c o  m*/

        int maxCols = 10 + (j % 7);
        // construct table
        List<Column> columns = new ArrayList<Column>();
        for (int i = 0; i < maxCols; ++i) {
            String testCol = "testColumn_" + Integer.toString(i);
            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);

        String rowId = LocalizationUtils.genUUID();

        ContentValues cvValues = new ContentValues();
        for (int i = 0; i < maxCols; ++i) {
            String testCol = "testColumn_" + Integer.toString(i);
            String testVal = "testVal_" + Integer.toString(i);
            cvValues.put(testCol, testVal);
        }

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

        // Select everything out of the table
        String queryCol = "testColumn_" + Integer.toString(j % maxCols);
        String queryVal = "testVal_" + Integer.toString(j % maxCols);
        String sel = "SELECT * FROM " + tableId + " WHERE " + queryCol + " = ?";
        String[] selArgs = { queryVal };
        Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

        String val = null;
        while (cursor.moveToNext()) {
            int ind = cursor.getColumnIndex(queryCol);
            int type = cursor.getType(ind);
            assertEquals(type, Cursor.FIELD_TYPE_STRING);
            val = cursor.getString(ind);

            ind = cursor.getColumnIndex(DataTableColumns.SAVEPOINT_TYPE);
            assertFalse(cursor.isNull(ind));

            // Get the conflict_type and make sure that it is null
            ind = cursor.getColumnIndex(DataTableColumns.CONFLICT_TYPE);
            assertTrue(cursor.isNull(ind));
        }

        assertEquals(val, queryVal);
        cursor.close();

        ODKDatabaseImplUtils.get().deleteRowWithId(db, tableId, rowId, activeUser, RoleConsts.ADMIN_ROLES_LIST);

        // Select everything out of the table
        sel = "SELECT * FROM " + tableId;
        selArgs = new String[0];
        cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

        assertEquals(cursor.getCount(), 0);

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

        for (int len = 1; len < maxBytes; len += 4) {
            byte[] bytes = new byte[len];
            for (int k = 0; k < len; ++k) {
                bytes[k] = (byte) k;
            }
            byteQueue.add(bytes);
        }
        for (int len = 1; len < maxBytes; len += 4) {
            byte[] bytes = new byte[len];
            for (int k = 0; k < len; ++k) {
                bytes[k] = (byte) k;
            }
            byteQueue.add(bytes);
        }
        for (int len = 1; len < maxBytes; len += 4) {
            byte[] bytes = byteQueue.pop();
            for (int k = 0; k < len; ++k) {
                assertEquals(bytes[k], (byte) k);
            }
        }
    }
}

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

@Test
public void testInsertCheckpointRowIntoExistingTableWithIdWhenRowIdNotProvided_ExpectPass()
        throws ActionNotAuthorizedException {
    String tableId = testTable;//from   w w  w . ja  v a 2  s . co m
    String testCol = "testColumn";
    String testColType = ElementDataType.string.name();
    String testVal = "test";
    String rowId = null;
    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);

    ContentValues cvValues = new ContentValues();
    cvValues.put(testCol, testVal);
    ODKDatabaseImplUtils.get().insertCheckpointRowWithId(db, tableId, orderedColumns, cvValues, rowId,
            activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale);

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

    String val = null;
    String saveptType = null;
    while (cursor.moveToNext()) {
        int ind = cursor.getColumnIndex(testCol);
        int type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        val = cursor.getString(ind);

        ind = cursor.getColumnIndex(DataTableColumns.SAVEPOINT_TIMESTAMP);
        type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        saveptType = cursor.getString(ind);

        // Get the conflict_type and make sure that it is null
        ind = cursor.getColumnIndex(DataTableColumns.CONFLICT_TYPE);
        assertTrue(cursor.isNull(ind));
    }

    assertEquals(val, testVal);

    // Also make sure that the savepoint_type
    // is empty
    assertNotSame(saveptType, SavepointTypeManipulator.incomplete());
    assertNotSame(saveptType, SavepointTypeManipulator.complete());

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

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

public void testUpdateTableETags() throws ActionNotAuthorizedException {
    String tableId = testTable;/*www .j  av  a 2s  .  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;

    ContentValues cvValues = new ContentValues();
    String rowId = LocalizationUtils.genUUID();
    cvValues.put(testCol, testVal);
    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 " + testCol + " = ?";
    String[] selArgs = { "" + testVal };
    Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);
    assertEquals(cursor.getCount(), 1);

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

    assertEquals(val, testVal);

    ODKDatabaseImplUtils.AccessContext accessContextNoTableId = ODKDatabaseImplUtils.get().getAccessContext(db,
            null, activeUser, RoleConsts.ADMIN_ROLES_LIST);

    // Select everything out of the table
    String sel2 = "SELECT * FROM " + DatabaseConstants.TABLE_DEFS_TABLE_NAME + " WHERE "
            + TableDefinitionsColumns.TABLE_ID + " = ?";
    String[] selArgs2 = { "" + tableId };
    cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel2, selArgs2, null, accessContextNoTableId);
    assertEquals(cursor.getCount(), 1);

    while (cursor.moveToNext()) {
        int ind = cursor.getColumnIndex(TableDefinitionsColumns.SCHEMA_ETAG);
        assertTrue(cursor.isNull(ind));

        int ind2 = cursor.getColumnIndex(TableDefinitionsColumns.LAST_DATA_ETAG);
        assertTrue(cursor.isNull(ind2));
    }

    // update db schema etag and last data etag
    String newSchemaETag = LocalizationUtils.genUUID();
    String newLastDataETag = LocalizationUtils.genUUID();
    ODKDatabaseImplUtils.get().privilegedUpdateTableETags(db, tableId, newSchemaETag, newLastDataETag);

    // Select everything out of the table
    cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel2, selArgs2, null, accessContextNoTableId);
    assertEquals(cursor.getCount(), 1);

    while (cursor.moveToNext()) {
        int ind = cursor.getColumnIndex(TableDefinitionsColumns.SCHEMA_ETAG);
        int type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        assertEquals(newSchemaETag, cursor.getString(ind));

        int ind2 = cursor.getColumnIndex(TableDefinitionsColumns.LAST_DATA_ETAG);
        int type2 = cursor.getType(ind2);
        assertEquals(type2, Cursor.FIELD_TYPE_STRING);
        assertEquals(newLastDataETag, cursor.getString(ind2));
    }

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

From source file:org.opendatakit.services.database.utilities.ODKDatabaseImplUtils.java

private void rawCheckpointDeleteDataInTable(OdkConnectionInterface db, String tableId, String rowId,
        String whereClause, Object[] whereArgs, String activeUser, String rolesList)
        throws ActionNotAuthorizedException {

    boolean shouldPhysicallyDelete = false;

    boolean dbWithinTransaction = db.inTransaction();
    try {//from  w ww .  j a  v  a2 s.co m
        if (!dbWithinTransaction) {
            db.beginTransactionNonExclusive();
        }

        // first need to test whether we can delete all the rows that are selected
        // by the where clause. If we can't, then throw an access violation
        Cursor c = null;
        try {
            c = db.query(tableId,
                    new String[] { DataTableColumns.SYNC_STATE, DataTableColumns.DEFAULT_ACCESS,
                            DataTableColumns.ROW_OWNER, DataTableColumns.GROUP_READ_ONLY,
                            DataTableColumns.GROUP_MODIFY, DataTableColumns.GROUP_PRIVILEGED },
                    whereClause, whereArgs, null, null, null, null);
            boolean hasRow = c.moveToFirst();

            int idxSyncState = c.getColumnIndex(DataTableColumns.SYNC_STATE);
            int idxDefaultAccess = c.getColumnIndex(DataTableColumns.DEFAULT_ACCESS);
            int idxOwner = c.getColumnIndex(DataTableColumns.ROW_OWNER);
            int idxGroupReadOnly = c.getColumnIndex(DataTableColumns.GROUP_READ_ONLY);
            int idxGroupModify = c.getColumnIndex(DataTableColumns.GROUP_MODIFY);
            int idxGroupPrivileged = c.getColumnIndex(DataTableColumns.GROUP_PRIVILEGED);

            List<String> rolesArray = getRolesArray(rolesList);

            TableSecuritySettings tss = getTableSecuritySettings(db, tableId);

            if (hasRow) {
                do {
                    // the row is entirely removed -- delete the attachments
                    String priorSyncState = c.getString(idxSyncState);
                    String priorDefaultAccess = c.isNull(idxDefaultAccess) ? null
                            : c.getString(idxDefaultAccess);
                    String priorOwner = c.isNull(idxOwner) ? null : c.getString(idxOwner);
                    String priorGroupReadOnly = c.isNull(idxGroupReadOnly) ? null
                            : c.getString(idxGroupReadOnly);
                    String priorGroupModify = c.isNull(idxGroupModify) ? null : c.getString(idxGroupModify);
                    String priorGroupPrivileged = c.isNull(idxGroupPrivileged) ? null
                            : c.getString(idxGroupPrivileged);

                    tss.allowRowChange(activeUser, rolesArray, priorSyncState, priorDefaultAccess, priorOwner,
                            priorGroupReadOnly, priorGroupModify, priorGroupPrivileged, RowChange.CHANGE_ROW);
                } while (c.moveToNext());
            }

        } finally {
            if (c != null && !c.isClosed()) {
                c.close();
            }
            c = null;
        }

        db.delete(tableId, whereClause, whereArgs);

        // see how many rows remain.
        // If there are none, then we should delete all the attachments for this row.
        c = null;
        try {
            c = db.query(tableId, new String[] { DataTableColumns.SYNC_STATE }, K_DATATABLE_ID_EQUALS_PARAM,
                    new Object[] { rowId }, null, null, null, null);
            c.moveToFirst();
            // the row is entirely removed -- delete the attachments
            shouldPhysicallyDelete = (c.getCount() == 0);
        } finally {
            if (c != null && !c.isClosed()) {
                c.close();
            }
        }

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

    if (shouldPhysicallyDelete) {
        File instanceFolder = new File(ODKFileUtils.getInstanceFolder(db.getAppName(), tableId, rowId));
        try {
            ODKFileUtils.deleteDirectory(instanceFolder);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            WebLogger.getLogger(db.getAppName()).e(t,
                    "Unable to delete this directory: " + instanceFolder.getAbsolutePath());
            WebLogger.getLogger(db.getAppName()).printStackTrace(e);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            WebLogger.getLogger(db.getAppName()).e(t,
                    "Unable to delete this directory: " + instanceFolder.getAbsolutePath());
            WebLogger.getLogger(db.getAppName()).printStackTrace(e);
        }
    }
}

From source file:org.opendatakit.services.database.utilities.ODKDatabaseImplUtils.java

/**
 * Delete the specified rowId in this tableId. Deletion respects sync
 * semantics. If the row is in the SyncState.new_row state, then the row and
 * its associated file attachments are immediately deleted. Otherwise, the row
 * is placed into the SyncState.deleted state and will be retained until the
 * device can delete the record on the server.
 * <p/>/*from  ww w.  j  ava  2s .c o m*/
 * If you need to immediately delete a record that would otherwise sync to the
 * server, call updateRowETagAndSyncState(...) to set the row to
 * SyncState.new_row, and then call this method and it will be immediately
 * deleted (in this case, unless the record on the server was already deleted,
 * it will remain and not be deleted during any subsequent synchronizations).
 *
 * @param db
 * @param tableId
 * @param rowId
 * @param activeUser
 * @param rolesList
 * @throws ActionNotAuthorizedException
 */
public void deleteRowWithId(OdkConnectionInterface db, String tableId, String rowId, String activeUser,
        String rolesList) throws ActionNotAuthorizedException {

    // TODO: rolesList of user may impact whether we can delete the record.
    // Particularly with sync'd records, is there anything special to do here?
    // consider sync path vs. tools path.
    // I.e., if the user is super-user or higher, we should take local FilterScope.
    // otherwise, we should take server FilterScope. Or should we allow user to select
    // which to take?

    boolean shouldPhysicallyDelete = false;

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

        Object[] whereArgs = new Object[] { rowId };
        String whereClause = K_DATATABLE_ID_EQUALS_PARAM;

        // first need to test whether we can delete all the rows under this rowId.
        // If we can't, then throw an access violation
        Cursor c = null;
        try {
            c = db.query(tableId,
                    new String[] { DataTableColumns.SYNC_STATE, DataTableColumns.DEFAULT_ACCESS,
                            DataTableColumns.ROW_OWNER, DataTableColumns.GROUP_READ_ONLY,
                            DataTableColumns.GROUP_MODIFY, DataTableColumns.GROUP_PRIVILEGED },
                    whereClause, whereArgs, null, null, DataTableColumns.SAVEPOINT_TIMESTAMP + " ASC", null);
            boolean hasFirst = c.moveToFirst();

            int idxSyncState = c.getColumnIndex(DataTableColumns.SYNC_STATE);
            int idxDefaultAccess = c.getColumnIndex(DataTableColumns.DEFAULT_ACCESS);
            int idxOwner = c.getColumnIndex(DataTableColumns.ROW_OWNER);
            int idxGroupReadOnly = c.getColumnIndex(DataTableColumns.GROUP_READ_ONLY);
            int idxGroupModify = c.getColumnIndex(DataTableColumns.GROUP_MODIFY);
            int idxGroupPrivileged = c.getColumnIndex(DataTableColumns.GROUP_PRIVILEGED);

            List<String> rolesArray = getRolesArray(rolesList);

            TableSecuritySettings tss = getTableSecuritySettings(db, tableId);

            if (hasFirst) {
                do {
                    // verify each row
                    String priorSyncState = c.getString(idxSyncState);
                    String priorDefaultAccess = c.isNull(idxDefaultAccess) ? null
                            : c.getString(idxDefaultAccess);
                    String priorOwner = c.isNull(idxOwner) ? null : c.getString(idxOwner);
                    String priorGroupReadOnly = c.isNull(idxGroupReadOnly) ? null
                            : c.getString(idxGroupReadOnly);
                    String priorGroupModify = c.isNull(idxGroupModify) ? null : c.getString(idxGroupModify);
                    String priorGroupPrivileged = c.isNull(idxGroupPrivileged) ? null
                            : c.getString(idxGroupPrivileged);

                    tss.allowRowChange(activeUser, rolesArray, priorSyncState, priorDefaultAccess, priorOwner,
                            priorGroupReadOnly, priorGroupModify, priorGroupPrivileged, RowChange.DELETE_ROW);

                } while (c.moveToNext());
            }

        } finally {
            if (c != null && !c.isClosed()) {
                c.close();
            }
            c = null;
        }

        // delete any checkpoints
        whereClause = K_DATATABLE_ID_EQUALS_PARAM + S_AND + DataTableColumns.SAVEPOINT_TYPE + S_IS_NULL;
        db.delete(tableId, whereClause, whereArgs);

        // this will return null if there are no rows.
        SyncState syncState = getSyncState(db, tableId, rowId);

        if (syncState == null) {
            // the rowId no longer exists (we deleted all checkpoints)
            shouldPhysicallyDelete = true;

        } else if (syncState == SyncState.new_row) {
            // we can safely remove this record from the database
            whereClause = K_DATATABLE_ID_EQUALS_PARAM;

            db.delete(tableId, whereClause, whereArgs);
            shouldPhysicallyDelete = true;

        } else if (syncState != SyncState.in_conflict) {

            TreeMap<String, Object> values = new TreeMap<String, Object>();
            values.put(DataTableColumns.SYNC_STATE, SyncState.deleted.name());
            values.put(DataTableColumns.SAVEPOINT_TIMESTAMP,
                    TableConstants.nanoSecondsFromMillis(System.currentTimeMillis()));

            db.update(tableId, values, K_DATATABLE_ID_EQUALS_PARAM, whereArgs);
        }
        // TODO: throw exception if in the SyncState.in_conflict state?

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

    if (shouldPhysicallyDelete) {
        File instanceFolder = new File(ODKFileUtils.getInstanceFolder(db.getAppName(), tableId, rowId));
        try {
            ODKFileUtils.deleteDirectory(instanceFolder);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            WebLogger.getLogger(db.getAppName()).e(t,
                    "Unable to delete this directory: " + instanceFolder.getAbsolutePath());
            WebLogger.getLogger(db.getAppName()).printStackTrace(e);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            WebLogger.getLogger(db.getAppName()).e(t,
                    "Unable to delete this directory: " + instanceFolder.getAbsolutePath());
            WebLogger.getLogger(db.getAppName()).printStackTrace(e);
        }
    }
}

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

@Test
public void testUpdateTableETags() throws ActionNotAuthorizedException {
    String tableId = testTable;/*from   w w w .  j a  va2s.  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;

    ContentValues cvValues = new ContentValues();
    String rowId = LocalizationUtils.genUUID();
    cvValues.put(testCol, testVal);
    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 " + testCol + " = ?";
    String[] selArgs = { "" + testVal };
    Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);
    assertEquals(cursor.getCount(), 1);

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

    assertEquals(val, testVal);

    ODKDatabaseImplUtils.AccessContext accessContextNoTableId = ODKDatabaseImplUtils.get().getAccessContext(db,
            null, activeUser, RoleConsts.ADMIN_ROLES_LIST);

    // Select everything out of the table
    String sel2 = "SELECT * FROM " + DatabaseConstants.TABLE_DEFS_TABLE_NAME + " WHERE "
            + TableDefinitionsColumns.TABLE_ID + " = ?";
    String[] selArgs2 = { "" + tableId };
    cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel2, selArgs2, null, accessContextNoTableId);
    assertEquals(cursor.getCount(), 1);

    while (cursor.moveToNext()) {
        int ind = cursor.getColumnIndex(TableDefinitionsColumns.SCHEMA_ETAG);
        assertTrue(cursor.isNull(ind));

        int ind2 = cursor.getColumnIndex(TableDefinitionsColumns.LAST_DATA_ETAG);
        assertTrue(cursor.isNull(ind2));
    }

    // update db schema etag and last data etag
    String newSchemaETag = LocalizationUtils.genUUID();
    String newLastDataETag = LocalizationUtils.genUUID();
    ODKDatabaseImplUtils.get().privilegedUpdateTableETags(db, tableId, newSchemaETag, newLastDataETag);

    // Select everything out of the table
    cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel2, selArgs2, null, accessContextNoTableId);
    assertEquals(cursor.getCount(), 1);

    while (cursor.moveToNext()) {
        int ind = cursor.getColumnIndex(TableDefinitionsColumns.SCHEMA_ETAG);
        int type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        assertEquals(newSchemaETag, cursor.getString(ind));

        int ind2 = cursor.getColumnIndex(TableDefinitionsColumns.LAST_DATA_ETAG);
        int type2 = cursor.getType(ind2);
        assertEquals(type2, Cursor.FIELD_TYPE_STRING);
        assertEquals(newLastDataETag, cursor.getString(ind2));
    }

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