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.test.AbstractODKDatabaseUtilsTest.java

public void testMultithreadedMultipleDBInsertionWithNewDBForQuery_ExpectPass()
        throws ActionNotAuthorizedException {
    int numOfThreads = 20;
    String tableId = testTable;//from   www  .  ja  va 2s.c  om
    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.test.AbstractODKDatabaseUtilsTest.java

public void testMultithreadedDBInsertionWithDBIntPerThreadWithTxnOnUpdate_ExpectPass()
        throws ActionNotAuthorizedException {
    int numOfThreads = 5;
    String tableId = testTable;/*  www . j  a va 2  s .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();
    }

    // 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.test.AbstractODKDatabaseUtilsTest.java

public void testMultithreadedDBInsertionWithClosingCursorAndOrigConn_ExpectPass()
        throws ActionNotAuthorizedException {
    int numOfThreads = 5;
    String tableId = testTable;//w w  w .ja 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, "[]"));
    }

    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.survey.android.tasks.InitializationTask.java

/**
 * Scan the given formDir and update the Forms database. If it is the
 * formsFolder, then any 'framework' forms should be forbidden. If it is not
 * the formsFolder, only 'framework' forms should be allowed
 *
 * @param mediaPath//from ww w. j a  va2 s.  c om
 *          -- full formDir
 * @param isFormsFolder
 * @param baseStaleMediaPath
 *          -- path prefix to the stale forms/framework directory.
 */
private final void updateFormDir(File formDir, boolean isFormsFolder, String baseStaleMediaPath) {
    Uri formsProviderContentUri = Uri.parse("content://" + FormsProviderAPI.AUTHORITY);
    String formDirectoryPath = formDir.getAbsolutePath();
    WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath);

    boolean needUpdate = true;
    FormInfo fi = null;
    Uri uri = null;
    Cursor c = null;
    try {
        File formDef = new File(formDir, ODKFileUtils.FORMDEF_JSON_FILENAME);

        String selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "=?";
        String[] selectionArgs = { ODKFileUtils.asRelativePath(appName, formDir) };
        c = appContext.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null,
                selection, selectionArgs, null);

        if (c == null) {
            WebLogger.getLogger(appName).w(t,
                    "updateFormDir: " + formDirectoryPath + " null cursor -- cannot update!");
            return;
        }

        if (c.getCount() > 1) {
            c.close();
            WebLogger.getLogger(appName).w(t, "updateFormDir: " + formDirectoryPath
                    + " multiple records from cursor -- delete all and restore!");
            // we have multiple records for this one directory.
            // Rename the directory. Delete the records, and move the
            // directory back.
            File tempMediaPath = moveToStaleDirectory(formDir, baseStaleMediaPath);
            appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                    selection, selectionArgs);
            FileUtils.moveDirectory(tempMediaPath, formDir);
            // we don't know which of the above records was correct, so
            // reparse this to get ground truth...
            fi = new FormInfo(appContext, appName, formDef);
        } else if (c.getCount() == 1) {
            c.moveToFirst();
            String id = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID));
            uri = Uri.withAppendedPath(Uri.withAppendedPath(formsProviderContentUri, appName), id);
            Long lastModificationDate = ODKDatabaseUtils.get().getIndexAsType(c, Long.class,
                    c.getColumnIndex(FormsColumns.DATE));
            Long formDefModified = ODKFileUtils.getMostRecentlyModifiedDate(formDir);
            if (lastModificationDate.compareTo(formDefModified) == 0) {
                WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath + " formDef unchanged");
                fi = new FormInfo(appName, c, false);
                needUpdate = false;
            } else {
                WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath + " formDef revised");
                fi = new FormInfo(appContext, appName, formDef);
                needUpdate = true;
            }
        } else if (c.getCount() == 0) {
            // it should be new, try to parse it...
            fi = new FormInfo(appContext, appName, formDef);
        }

        // Enforce that a formId == FormsColumns.COMMON_BASE_FORM_ID can only be
        // in the Framework directory
        // and that no other formIds can be in that directory. If this is not the
        // case, ensure that
        // this record is moved to the stale directory.

        if (fi.formId.equals(FormsColumns.COMMON_BASE_FORM_ID)) {
            if (isFormsFolder) {
                // we have a 'framework' form in the forms directory.
                // Move it to the stale directory.
                // Delete all records referring to this directory.
                moveToStaleDirectory(formDir, baseStaleMediaPath);
                appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                        selection, selectionArgs);
                return;
            }
        } else {
            if (!isFormsFolder) {
                // we have a non-'framework' form in the framework directory.
                // Move it to the stale directory.
                // Delete all records referring to this directory.
                moveToStaleDirectory(formDir, baseStaleMediaPath);
                appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                        selection, selectionArgs);
                return;
            }
        }
    } catch (SQLiteException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } catch (IOException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } catch (IllegalArgumentException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        try {
            FileUtils.deleteDirectory(formDir);
            WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath
                    + " Removing -- unable to parse formDef file: " + e.toString());
        } catch (IOException e1) {
            WebLogger.getLogger(appName).printStackTrace(e1);
            WebLogger.getLogger(appName)
                    .i(t, "updateFormDir: " + formDirectoryPath
                            + " Removing -- unable to delete form directory: " + formDir.getName() + " error: "
                            + e.toString());
        }
        return;
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }

    // Delete any entries matching this FORM_ID, but not the same directory and
    // which have a version that is equal to or older than this version.
    String selection;
    String[] selectionArgs;
    if (fi.formVersion == null) {
        selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND "
                + FormsColumns.FORM_VERSION + " IS NULL";
        String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId };
        selectionArgs = temp;
    } else {
        selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND "
                + "( " + FormsColumns.FORM_VERSION + " IS NULL" + " OR " + FormsColumns.FORM_VERSION + " <=?"
                + " )";
        String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId, fi.formVersion };
        selectionArgs = temp;
    }

    try {
        appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                selection, selectionArgs);
    } catch (SQLiteException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } catch (Exception e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    }

    // See if we have any newer versions already present...
    if (fi.formVersion == null) {
        selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND "
                + FormsColumns.FORM_VERSION + " IS NOT NULL";
        String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId };
        selectionArgs = temp;
    } else {
        selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND "
                + FormsColumns.FORM_VERSION + " >?";
        String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId, fi.formVersion };
        selectionArgs = temp;
    }

    try {
        Uri uriApp = Uri.withAppendedPath(formsProviderContentUri, appName);
        c = appContext.getContentResolver().query(uriApp, null, selection, selectionArgs, null);

        if (c == null) {
            WebLogger.getLogger(appName).w(t,
                    "updateFormDir: " + uriApp.toString() + " null cursor -- cannot update!");
            return;
        }

        if (c.moveToFirst()) {
            // the directory we are processing is stale -- move it to stale
            // directory
            moveToStaleDirectory(formDir, baseStaleMediaPath);
            return;
        }
    } catch (SQLiteException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } catch (IOException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }

    if (!needUpdate) {
        // no change...
        return;
    }

    try {
        // Now insert or update the record...
        ContentValues v = new ContentValues();
        String[] values = fi.asRowValues(FormsColumns.formsDataColumnNames);
        for (int i = 0; i < values.length; ++i) {
            v.put(FormsColumns.formsDataColumnNames[i], values[i]);
        }

        if (uri != null) {
            int count = appContext.getContentResolver().update(uri, v, null, null);
            WebLogger.getLogger(appName).i(t,
                    "updateFormDir: " + formDirectoryPath + " " + count + " records successfully updated");
        } else {
            appContext.getContentResolver().insert(Uri.withAppendedPath(formsProviderContentUri, appName), v);
            WebLogger.getLogger(appName).i(t,
                    "updateFormDir: " + formDirectoryPath + " one record successfully inserted");
        }

    } catch (SQLiteException ex) {
        WebLogger.getLogger(appName).printStackTrace(ex);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + ex.toString());
        return;
    }
}

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

/**
 * Return all the tableIds in the database.
 *
 * @param db//w  w  w .jav  a  2  s  . co  m
 * @return an ArrayList<String> of tableIds
 */
public ArrayList<String> getAllTableIds(OdkConnectionInterface db) {
    ArrayList<String> tableIds = new ArrayList<String>();
    Cursor c = null;
    try {
        c = db.query(DatabaseConstants.TABLE_DEFS_TABLE_NAME, new String[] { TableDefinitionsColumns.TABLE_ID },
                null, null, null, null, TableDefinitionsColumns.TABLE_ID + " ASC", null);

        if (c.moveToFirst()) {
            int idxId = c.getColumnIndex(TableDefinitionsColumns.TABLE_ID);
            do {
                String tableId = c.getString(idxId);
                if (tableId == null || tableId.length() == 0) {
                    c.close();
                    throw new IllegalStateException("getAllTableIds: Unexpected tableId found!");
                }
                tableIds.add(tableId);
            } while (c.moveToNext());
        }
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
    return tableIds;
}

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

public void testWriteDataIntoExisitingTableWithIdWhenIdAlreadyExists_ExpectPass()
        throws ActionNotAuthorizedException {
    String tableId = testTable;/*from  w ww. j  a  v a2s. 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;
    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.test.AbstractODKDatabaseUtilsTest.java

public void testQueryDistinct_ExpectPass() throws ActionNotAuthorizedException {
    String tableId = testTable;/*from  w  w  w. j  a  va2 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);
}

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

public String getTableDefinitionRevId(OdkConnectionInterface db, String tableId) {
    String revId = null;/*from   w  w w. j a  va  2 s. c o  m*/
    Cursor c = null;
    try {
        StringBuilder b = new StringBuilder();
        ArrayList<String> selArgs = new ArrayList<String>();
        b.append(K_KVS_TABLE_ID_EQUALS_PARAM);
        selArgs.add(tableId);

        c = db.query(DatabaseConstants.TABLE_DEFS_TABLE_NAME, null, b.toString(),
                selArgs.toArray(new String[selArgs.size()]), null, null, null, null);
        if (c.moveToFirst()) {
            int idxRevId = c.getColumnIndex(TableDefinitionsColumns.REV_ID);

            if (c.getCount() != 1) {
                throw new IllegalStateException(
                        "Two or more TableDefinitionEntry records found for tableId " + tableId);
            }

            revId = c.getString(idxRevId);
        }
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
    return revId;
}

From source file:org.opendatakit.services.database.utlities.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  a  2  s.  c  om*/
        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.FILTER_TYPE,
                    DataTableColumns.FILTER_VALUE }, whereClause, whereArgs, null, null, null, null);
            boolean hasRow = 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 (hasRow) {
                do {
                    // the row is entirely removed -- delete the attachments
                    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;
        }

        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 {
            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.utilities.AbstractODKDatabaseUtilsTest.java

@Test
public void testMultithreadedMultipleDBInsertionWithSameSelect_ExpectPass()
        throws ActionNotAuthorizedException {
    int numOfThreads = 20;
    String tableId = testTable;/*from   ww w  .ja v  a  2  s  .  c om*/
    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;
    String[] selArgs = null;
    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();
    }

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

    assertEquals(cursor2.getCount(), 1);

    System.out.println("testMultithreadedMultipleDBInsertionWithSameSelect_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("testMultithreadedMultipleDBInsertionWithSameSelect_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("testMultithreadedMultipleDBInsertionWithSameSelect_ExpectPass: after assert");
    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().dumpInfo(false);

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