Example usage for android.database Cursor isClosed

List of usage examples for android.database Cursor isClosed

Introduction

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

Prototype

boolean isClosed();

Source Link

Document

return true if the cursor is closed

Usage

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

@Test
public void testMultithreadedDBInsertionWithDBIntPerThreadWithTxn_ExpectPass()
        throws ActionNotAuthorizedException {
    int numOfThreads = 5;
    String tableId = testTable;/*from w w w  . j  av  a2s .  c  o m*/
    String colPrefix = "testColumn";
    String testColType = ElementDataType.integer.name();
    List<Column> columns = new ArrayList<Column>();

    // Create table with the right number of columns
    for (int i = 0; i <= numOfThreads; i++) {
        String testCol = colPrefix + 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);

    // Insert data so that the threads can all just update
    int testVal = 0;
    String setupTestCol = colPrefix + 0;
    ContentValues cvValues = new ContentValues();
    String rowId = LocalizationUtils.genUUID();
    cvValues.put(setupTestCol, testVal);
    ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, rowId, activeUser,
            RoleConsts.ADMIN_ROLES_LIST, currentLocale);

    // Ensure that the row exists
    String sel = "SELECT * FROM " + tableId + " WHERE " + setupTestCol + " = ?";
    String[] selArgs = { "" + testVal };
    Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

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

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

    // Have the threads all update the corresponding column in the table
    try {
        threadTest(numOfThreads, tableId, rowId, colPrefix, orderedColumns, true, false, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Ensure that the row exists
    boolean dbWithinTrxn = db.inTransaction();
    if (!dbWithinTrxn) {
        db.beginTransactionExclusive();
        String sel2 = "SELECT * FROM " + tableId;
        String[] selArgs2 = null;
        Cursor cursor2 = ODKDatabaseImplUtils.get().rawQuery(db, sel2, selArgs2, null, accessContext);

        assertEquals(cursor2.getCount(), 1);

        System.out.println("testMultithreadedDBInsertionWithDBIntPerThreadWithTxn_ExpectPass: before assert");
        OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().dumpInfo(false);

        while (cursor2.moveToNext()) {
            for (int i = 1; i <= numOfThreads; i++) {
                System.out
                        .println("testMultithreadedDBInsertionWithDBIntPerThreadWithTxn_ExpectPass: assertion "
                                + "for thread " + i);
                String columnName = colPrefix + i;
                int ind = cursor2.getColumnIndex(columnName);
                int type = cursor2.getType(ind);
                assertEquals(type, Cursor.FIELD_TYPE_INTEGER);
                int val = cursor2.getInt(ind);
                assertEquals(val, i);
            }
        }

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

        db.setTransactionSuccessful();
        db.endTransaction();
    }

    System.out.println("testMultithreadedDBInsertionWithDBIntPerThreadWithTxn_ExpectPass: after assert");
    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().dumpInfo(false);

    // 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 testMultithreadedDBInsertionWithClosingCursor_ExpectPass() throws ActionNotAuthorizedException {
    int numOfThreads = 5;
    String tableId = testTable;//from  w  ww .j a v  a  2s  .com
    String colPrefix = "testColumn";
    String testColType = ElementDataType.integer.name();
    List<Column> columns = new ArrayList<Column>();

    // Create table with the right number of columns
    for (int i = 0; i <= numOfThreads; i++) {
        String testCol = colPrefix + 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);

    // Insert data so that the threads can all just update
    int testVal = 0;
    String setupTestCol = colPrefix + 0;
    ContentValues cvValues = new ContentValues();
    String rowId = LocalizationUtils.genUUID();
    cvValues.put(setupTestCol, testVal);
    ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, rowId, activeUser,
            RoleConsts.ADMIN_ROLES_LIST, currentLocale);

    // Ensure that the row exists
    String sel = "SELECT * FROM " + tableId + " WHERE " + setupTestCol + " = ?";
    String[] selArgs = { "" + testVal };
    Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

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

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

    List<Long> returnedResults = null;

    // Have the threads all update the corresponding column in the table
    try {
        returnedResults = threadTest(numOfThreads, tableId, rowId, colPrefix, orderedColumns, false, false, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Extra check to make sure that this has finished before
    // anything continues
    List<Long> expectedList = new ArrayList<Long>(numOfThreads);
    for (long i = 1; i <= numOfThreads; i++) {
        expectedList.add(i);
    }
    if (returnedResults != null) {
        Collections.sort(returnedResults);
    }

    assertEquals(expectedList, returnedResults);

    // Ensure that the row exists
    String sel2 = "SELECT * FROM " + tableId;
    String[] selArgs2 = null;
    Cursor cursor2 = ODKDatabaseImplUtils.get().rawQuery(db, sel2, selArgs2, null, accessContext);

    assertEquals(cursor2.getCount(), 1);

    System.out.println("testMultithreadedDBInsertionWithClosingCursor_ExpectPass: before assert");
    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().dumpInfo(false);

    while (cursor2.moveToNext()) {
        assertEquals(cursor2.getColumnIndex(colPrefix), -1);
        for (int i = 0; i <= numOfThreads; i++) {
            String columnName = colPrefix + i;
            int ind = cursor2.getColumnIndex(columnName);
            int type = cursor2.getType(ind);
            assertEquals(type, Cursor.FIELD_TYPE_INTEGER);
            int val = cursor2.getInt(ind);
            assertEquals(val, i);
        }
    }

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

    // 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 testMultithreadedDBInsertionWithDBIntPerThreadAndForQuery_ExpectPass()
        throws ActionNotAuthorizedException {
    int numOfThreads = 5;
    String tableId = testTable;//from   w  w w.j  a  v a 2s. c o m
    String colPrefix = "testColumn";
    String testColType = ElementDataType.integer.name();
    List<Column> columns = new ArrayList<Column>();

    // Create table with the right number of columns
    for (int i = 0; i <= numOfThreads; i++) {
        String testCol = colPrefix + 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);

    // Insert data so that the threads can all just update
    int testVal = 0;
    String setupTestCol = colPrefix + 0;
    ContentValues cvValues = new ContentValues();
    String rowId = LocalizationUtils.genUUID();
    cvValues.put(setupTestCol, testVal);
    ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, rowId, activeUser,
            RoleConsts.ADMIN_ROLES_LIST, currentLocale);

    // Ensure that the row exists
    String sel = "SELECT * FROM " + tableId + " WHERE " + setupTestCol + " = ?";
    String[] selArgs = { "" + testVal };
    Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

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

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

    // Have the threads all update the corresponding column in the table
    try {
        threadTest(numOfThreads, tableId, rowId, colPrefix, orderedColumns, true, false, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Ensure that the row exists
    String sel2 = "SELECT * FROM " + tableId;
    String[] selArgs2 = null;

    // Query with new connection to see if this gets all recent operations
    DbHandle uniqueKey = new DbHandle(AbstractODKDatabaseUtilsTest.class.getSimpleName() + testVal
            + AndroidConnectFactory.INTERNAL_TYPE_SUFFIX);
    OdkConnectionInterface dbForQuery = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .getConnection(getAppName(), uniqueKey);

    Cursor cursor2 = ODKDatabaseImplUtils.get().rawQuery(dbForQuery, sel2, selArgs2, null, accessContext);

    assertEquals(cursor2.getCount(), 1);

    System.out.println("testMultithreadedDBInsertionWithDBIntPerThreadAndForQuery_ExpectPass: before assert");
    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().dumpInfo(false);

    while (cursor2.moveToNext()) {
        for (int i = 1; i <= numOfThreads; i++) {
            System.out
                    .println("testMultithreadedDBInsertionWithDBIntPerThreadAndForQuery_ExpectPass: assertion "
                            + "for thread " + i);
            String columnName = colPrefix + i;
            int ind = cursor2.getColumnIndex(columnName);
            int type = cursor2.getType(ind);
            assertEquals(type, Cursor.FIELD_TYPE_INTEGER);
            int val = cursor2.getInt(ind);
            assertEquals(val, i);
        }
    }

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

    System.out.println("testMultithreadedDBInsertionWithDBIntPerThreadAndForQuery_ExpectPass: after assert");
    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().dumpInfo(false);

    // Release the OdkConnectionInterface used for the query
    dbForQuery.releaseReference();

    // 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 testMultithreadedMultipleDBInsertionWithNewDBForQuery_ExpectPass()
        throws ActionNotAuthorizedException {
    int numOfThreads = 20;
    String tableId = testTable;//from   w  w  w.j a v  a  2  s .  c o m
    String colPrefix = "testColumn";
    String testColType = ElementDataType.integer.name();
    List<Column> columns = new ArrayList<Column>();

    // Create table with the right number of columns
    for (int i = 0; i <= numOfThreads; i++) {
        String testCol = colPrefix + 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);

    // Insert data so that the threads can all just update
    int testVal = 0;
    String setupTestCol = colPrefix + 0;
    ContentValues cvValues = new ContentValues();
    String rowId = LocalizationUtils.genUUID();
    cvValues.put(setupTestCol, testVal);
    ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, rowId, activeUser,
            RoleConsts.ADMIN_ROLES_LIST, currentLocale);

    // Ensure that the row exists
    String sel = "SELECT * FROM " + tableId + " WHERE " + setupTestCol + " = ?";
    String[] selArgs = { "" + testVal };
    Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

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

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

    // Have the threads all update the corresponding column in the table
    int numOfWritesForThreads = 100;
    try {
        threadTest(numOfThreads, tableId, rowId, colPrefix, orderedColumns, true, true, numOfWritesForThreads);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Ensure that the row exists
    Cursor cursor2 = null;

    // Try this to see if it makes a difference
    // Query with new connection to see if this gets all recent operations
    String uuid = LocalizationUtils.genUUID();
    DbHandle uniqueKey = new DbHandle(AbstractODKDatabaseUtilsTest.class.getSimpleName() + uuid
            + AndroidConnectFactory.INTERNAL_TYPE_SUFFIX);
    OdkConnectionInterface dbForQuery = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .getConnection(getAppName(), uniqueKey);

    String sel2 = "SELECT * FROM " + tableId;
    String[] selArgs2 = null;
    cursor2 = ODKDatabaseImplUtils.get().rawQuery(dbForQuery, sel2, selArgs2, null, accessContext);

    assertEquals(cursor2.getCount(), 1);

    System.out.println("testMultithreadedMultipleDBInsertion_ExpectPass: before assert");
    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().dumpInfo(false);

    while (cursor2.moveToNext()) {
        int indAgain = cursor2.getColumnIndex(setupTestCol);
        int typeAgain = cursor2.getType(indAgain);
        assertEquals(typeAgain, Cursor.FIELD_TYPE_INTEGER);
        int valAgain = cursor2.getInt(indAgain);
        assertEquals(valAgain, testVal);
        for (int i = 1; i <= numOfThreads; i++) {
            System.out
                    .println("testMultithreadedMultipleDBInsertion_ExpectPass: assertion " + "for thread " + i);
            String columnName = colPrefix + i;
            int ind = cursor2.getColumnIndex(columnName);
            int type = cursor2.getType(ind);
            assertEquals(type, Cursor.FIELD_TYPE_INTEGER);
            int val = cursor2.getInt(ind);
            assertEquals(val, numOfWritesForThreads);
        }
    }

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

    System.out.println("testMultithreadedMultipleDBInsertion_ExpectPass: after assert");
    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().dumpInfo(false);

    // 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 testMultithreadedDBInsertionWithDBIntPerThreadWithTxnOnUpdate_ExpectPass()
        throws ActionNotAuthorizedException {
    int numOfThreads = 5;
    String tableId = testTable;/* ww w.j  a v  a 2s  . co  m*/
    String colPrefix = "testColumn";
    String testColType = ElementDataType.integer.name();
    List<Column> columns = new ArrayList<Column>();

    // Create table with the right number of columns
    for (int i = 0; i <= numOfThreads; i++) {
        String testCol = colPrefix + 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);

    // Insert data so that the threads can all just update
    int testVal = 0;
    String setupTestCol = colPrefix + 0;
    ContentValues cvValues = new ContentValues();
    String rowId = LocalizationUtils.genUUID();
    cvValues.put(setupTestCol, testVal);
    ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, rowId, activeUser,
            RoleConsts.ADMIN_ROLES_LIST, currentLocale);

    // Ensure that the row exists
    String sel = "SELECT * FROM " + tableId + " WHERE " + setupTestCol + " = ?";
    String[] selArgs = { "" + testVal };
    Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

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

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

    // Have the threads all update the corresponding column in the table
    try {
        threadTest(numOfThreads, tableId, rowId, colPrefix, orderedColumns, true, false, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Ensure that the row exists
    boolean dbWithinTrxn = db.inTransaction();
    int testValAgain = 100;
    if (!dbWithinTrxn) {
        db.beginTransactionExclusive();
        ContentValues cvValuesAgain = new ContentValues();
        cvValuesAgain.put(setupTestCol, testValAgain);
        ODKDatabaseImplUtils.get().updateRowWithId(db, tableId, orderedColumns, cvValuesAgain, rowId,
                activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale);
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    String sel2 = "SELECT * FROM " + tableId;
    String[] selArgs2 = null;
    Cursor cursor2 = ODKDatabaseImplUtils.get().rawQuery(db, sel2, selArgs2, null, accessContext);

    assertEquals(cursor2.getCount(), 1);

    System.out.println("testMultithreadedDBInsertionWithDBIntPerThreadWithTxn_ExpectPass: before assert");
    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().dumpInfo(false);

    while (cursor2.moveToNext()) {
        int indAgain = cursor2.getColumnIndex(setupTestCol);
        int typeAgain = cursor2.getType(indAgain);
        assertEquals(typeAgain, Cursor.FIELD_TYPE_INTEGER);
        int valAgain = cursor2.getInt(indAgain);
        assertEquals(valAgain, testValAgain);
        for (int i = 1; i <= numOfThreads; i++) {
            System.out.println("testMultithreadedDBInsertionWithDBIntPerThreadWithTxn_ExpectPass: assertion "
                    + "for thread " + i);
            String columnName = colPrefix + i;
            int ind = cursor2.getColumnIndex(columnName);
            int type = cursor2.getType(ind);
            assertEquals(type, Cursor.FIELD_TYPE_INTEGER);
            int val = cursor2.getInt(ind);
            assertEquals(val, i);
        }
    }

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

    System.out.println("testMultithreadedDBInsertionWithDBIntPerThreadWithTxn_ExpectPass: after assert");
    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().dumpInfo(false);

    // 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 testMultithreadedDBInsertionWithClosingCursorAndOrigConn_ExpectPass()
        throws ActionNotAuthorizedException {
    int numOfThreads = 5;
    String tableId = testTable;/*from w  ww.  j  a  v  a 2  s . c o  m*/
    String colPrefix = "testColumn";
    String testColType = ElementDataType.integer.name();
    List<Column> columns = new ArrayList<Column>();

    // Create table with the right number of columns
    for (int i = 0; i <= numOfThreads; i++) {
        String testCol = colPrefix + i;
        columns.add(new Column(testCol, testCol, testColType, "[]"));
    }

    String uniqueUUID = LocalizationUtils.genUUID();
    DbHandle prevUniqueKey = new DbHandle(AbstractODKDatabaseUtilsTest.class.getSimpleName() + uniqueUUID
            + AndroidConnectFactory.INTERNAL_TYPE_SUFFIX);
    OdkConnectionInterface prevDb = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .getConnection(getAppName(), prevUniqueKey);

    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(prevDb, tableId,
            columns);

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

    // Insert data so that the threads can all just update
    int testVal = 0;
    String setupTestCol = colPrefix + 0;
    ContentValues cvValues = new ContentValues();
    String rowId = LocalizationUtils.genUUID();
    cvValues.put(setupTestCol, testVal);
    ODKDatabaseImplUtils.get().insertRowWithId(prevDb, tableId, orderedColumns, cvValues, rowId, activeUser,
            RoleConsts.ADMIN_ROLES_LIST, currentLocale);

    // Ensure that the row exists
    String sel = "SELECT * FROM " + tableId + " WHERE " + setupTestCol + " = ?";
    String[] selArgs = { "" + testVal };
    Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(prevDb, sel, selArgs, null, accessContext);

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

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

    List<Long> returnedResults = null;

    // Have the threads all update the corresponding column in the table
    try {
        returnedResults = threadTest(numOfThreads, tableId, rowId, colPrefix, orderedColumns, true, false, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Extra check to make sure that this has finished before
    // anything continues
    List<Long> expectedList = new ArrayList<Long>(numOfThreads);
    for (long i = 1; i <= numOfThreads; i++) {
        expectedList.add(i);
    }
    if (returnedResults != null) {
        Collections.sort(returnedResults);
    }

    assertEquals(expectedList, returnedResults);

    // Ensure that the row exists
    String sel2 = "SELECT * FROM " + tableId;
    String[] selArgs2 = null;
    Cursor cursor2 = ODKDatabaseImplUtils.get().rawQuery(prevDb, sel2, selArgs2, null, accessContext);

    assertEquals(cursor2.getCount(), 1);

    System.out.println("testMultithreadedDBInsertionWithClosingCursor_ExpectPass: before assert");
    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().dumpInfo(false);

    while (cursor2.moveToNext()) {
        assertEquals(cursor2.getColumnIndex(colPrefix), -1);
        for (int i = 0; i <= numOfThreads; i++) {
            String columnName = colPrefix + i;
            int ind = cursor2.getColumnIndex(columnName);
            int type = cursor2.getType(ind);
            assertEquals(type, Cursor.FIELD_TYPE_INTEGER);
            int val = cursor2.getInt(ind);
            assertEquals(val, i);
        }
    }

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

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

From source file:org.opendatakit.services.database.utlities.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  w w w  . j  a  v a 2  s .  co  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.FILTER_TYPE,
                            DataTableColumns.FILTER_VALUE },
                    whereClause, whereArgs, null, null, DataTableColumns.SAVEPOINT_TIMESTAMP + " ASC", null);
            boolean hasFirst = c.moveToFirst();

            int idxSyncState = c.getColumnIndex(DataTableColumns.SYNC_STATE);
            int idxFilterType = c.getColumnIndex(DataTableColumns.FILTER_TYPE);
            int idxFilterValue = c.getColumnIndex(DataTableColumns.FILTER_VALUE);

            List<String> rolesArray = getRolesArray(rolesList);

            TableSecuritySettings tss = getTableSecuritySettings(db, tableId);

            if (hasFirst) {
                do {
                    // verify each row
                    String priorSyncState = c.getString(idxSyncState);
                    String priorFilterType = c.isNull(idxFilterType) ? null : c.getString(idxFilterType);
                    String priorFilterValue = c.isNull(idxFilterValue) ? null : c.getString(idxFilterValue);

                    tss.allowRowChange(activeUser, rolesArray, priorSyncState, priorFilterType,
                            priorFilterValue, 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 {
            FileUtils.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);
        }
    }
}

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

/**
 * Return all the columns in the given table, including any metadata columns.
 * This does a direct query against the database and is suitable for accessing
 * non-managed tables. It does not access any metadata and therefore will not
 * report non-unit-of-retention (grouping) columns.
 *
 * @param db/*  w  ww . ja v  a  2s . c  o m*/
 * @param tableId
 * @return
 */
public String[] getAllColumnNames(OdkConnectionInterface db, String tableId) {
    Cursor cursor = null;
    try {
        StringBuilder b = new StringBuilder();
        b.append(K_SELECT_FROM).append(tableId).append(K_LIMIT).append("1");
        cursor = db.rawQuery(b.toString(), null);
        // If this query has been executed before, the cursor is created using the
        // previously-constructed PreparedStatement for the query. There is no actual
        // interaction with the database itself at the time the Cursor is constructed.
        // The first database interaction is when the content of the cursor is fetched.
        //
        // This can be triggered by a call to getCount().
        // At that time, if the table does not exist, it will throw an exception.
        cursor.moveToFirst();
        cursor.getCount();
        // Otherwise, when cached, getting the column names doesn't call into the database
        // and will not, itself, detect that the table has been dropped.
        String[] colNames = cursor.getColumnNames();
        return colNames;
    } finally {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    }
}

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

@Test
public void testWriteDataIntoExistingTableWithIdWhenIdAlreadyExists_ExpectPass()
        throws ActionNotAuthorizedException {
    String tableId = testTable;/*from   w w w.ja  v a  2 s .c  om*/
    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;
    boolean thrown = false;

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

    String uuid = UUID.randomUUID().toString();
    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 " + testCol + " = ?";
    String[] selArgs = { "" + testVal };
    Cursor cursor = null;
    try {
        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);
    } finally {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    }
    // Try updating that row in the database
    int testVal2 = 25;
    ContentValues cvValues2 = new ContentValues();
    cvValues2.put(testCol, testVal2);

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

    assertEquals(thrown, true);

    /**
     * NOTE: we expect the log to report a failure to close this cursor.
     * It is GC'd and closed in its finalizer. This is confirming that
     * the finalizer is doing the right thing.
     */

    // Select everything out of the table
    String sel2 = "SELECT * FROM " + tableId;
    String[] selArgs2 = {};
    Cursor cursor2 = ODKDatabaseImplUtils.get().rawQuery(db, sel2, selArgs2, null, accessContext);
    assertEquals(cursor2.getCount(), 1);

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

    assertEquals(val2, testVal);

    // 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 testQueryDistinct_ExpectPass() throws ActionNotAuthorizedException {
    String tableId = testTable;/*from  w  ww .  j a  v a2  s  .  c om*/
    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;
    boolean thrown = false;

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

    String uuid = UUID.randomUUID().toString();
    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 " + testCol + " = ?";
    String[] selArgs = { "" + testVal };
    Cursor cursor = null;
    try {
        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);
    } finally {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    }
    // Add another row in the database with the same value
    String uuid2 = UUID.randomUUID().toString();
    ContentValues cvValues2 = new ContentValues();
    cvValues2.put(testCol, testVal);

    ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues2, uuid2, activeUser,
            RoleConsts.ADMIN_ROLES_LIST, currentLocale);

    // Select everything out of the table
    String sel2 = "SELECT * FROM " + tableId;
    String[] selArgs2 = {};
    Cursor cursor2 = ODKDatabaseImplUtils.get().rawQuery(db, sel2, selArgs2, null, accessContext);
    assertEquals(cursor2.getCount(), 2);

    System.out.println("testQueryDistinct_ExpectPass: after select *  query");
    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().dumpInfo(false);

    // Make sure the values are correct
    int val2 = 0;
    while (cursor2.moveToNext()) {
        int ind = cursor2.getColumnIndex(testCol);
        int type = cursor2.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_INTEGER);
        val2 = cursor2.getInt(ind);
        assertEquals(val2, testVal);
    }

    // The moment of truth! test the queryDistinct
    // Get all of the rows of the database but only return testCol
    String[] retCols = { testCol };
    Cursor cursor3 = ODKDatabaseImplUtils.get().queryDistinctForTest(db, tableId, retCols, null, null, null,
            null, null, null);
    assertEquals(cursor3.getCount(), 1);

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

    assertEquals(val3, testVal);

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