List of usage examples for android.database Cursor isClosed
boolean isClosed();
From source file:org.adaway.service.ApplyService.java
/** * Downloads files from hosts sources//from w w w . j a va2 s .c om * * @return return code */ private int download() { Cursor enabledHostsSourcesCursor; byte data[]; int count; long currentLastModifiedOnline; int returnCode = StatusCodes.SUCCESS; // default return code if (Utils.isAndroidOnline(mService)) { showApplyNotification(mService, mService.getString(R.string.download_dialog), mService.getString(R.string.download_dialog), mService.getString(R.string.download_dialog)); // output to write into FileOutputStream out = null; try { out = mService.openFileOutput(Constants.DOWNLOADED_HOSTS_FILENAME, Context.MODE_PRIVATE); mNumberOfFailedDownloads = 0; mNumberOfDownloads = 0; // get cursor over all enabled hosts source enabledHostsSourcesCursor = ProviderHelper.getEnabledHostsSourcesCursor(mService); // iterate over all hosts sources in db with cursor if (enabledHostsSourcesCursor.moveToFirst()) { do { mNumberOfDownloads++; InputStream is = null; BufferedInputStream bis = null; String currentUrl = enabledHostsSourcesCursor .getString(enabledHostsSourcesCursor.getColumnIndex("url")); try { Log.v(Constants.TAG, "Downloading hosts file: " + currentUrl); /* change URL in download dialog */ updateApplyNotification(mService, mService.getString(R.string.download_dialog), currentUrl); /* build connection */ URL mURL = new URL(currentUrl); URLConnection connection = mURL.openConnection(); connection.setConnectTimeout(15000); connection.setReadTimeout(30000); /* connect */ connection.connect(); is = connection.getInputStream(); bis = new BufferedInputStream(is); if (is == null) { Log.e(Constants.TAG, "Stream is null"); } /* download with progress */ data = new byte[1024]; count = 0; // run while only when thread is not cancelled while ((count = bis.read(data)) != -1) { out.write(data, 0, count); } // add line seperator to add files together in one file out.write(Constants.LINE_SEPERATOR.getBytes()); // save last modified online for later use currentLastModifiedOnline = connection.getLastModified(); ProviderHelper.updateHostsSourceLastModifiedOnline(mService, enabledHostsSourcesCursor .getInt(enabledHostsSourcesCursor.getColumnIndex(HostsSources._ID)), currentLastModifiedOnline); } catch (IOException e) { Log.e(Constants.TAG, "Exception while downloading from " + currentUrl, e); mNumberOfFailedDownloads++; // set last_modified_online of failed download to 0 (not available) ProviderHelper.updateHostsSourceLastModifiedOnline(mService, enabledHostsSourcesCursor .getInt(enabledHostsSourcesCursor.getColumnIndex(HostsSources._ID)), 0); } finally { // flush and close streams try { if (out != null) { out.flush(); } if (bis != null) { bis.close(); } if (is != null) { is.close(); } } catch (Exception e) { Log.e(Constants.TAG, "Exception on flush and closing streams.", e); } } } while (enabledHostsSourcesCursor.moveToNext()); } // close cursor in the end if (enabledHostsSourcesCursor != null && !enabledHostsSourcesCursor.isClosed()) { enabledHostsSourcesCursor.close(); } // if all downloads failed return download_fail error if (mNumberOfDownloads == mNumberOfFailedDownloads && mNumberOfDownloads != 0) { returnCode = StatusCodes.DOWNLOAD_FAIL; } } catch (Exception e) { Log.e(Constants.TAG, "Private File can not be created, Exception: " + e); returnCode = StatusCodes.PRIVATE_FILE_FAIL; } finally { try { if (out != null) { out.close(); } } catch (Exception e) { Log.e(Constants.TAG, "Exception on close of out.", e); } } } else { returnCode = StatusCodes.NO_CONNECTION; } return returnCode; }
From source file:org.opendatakit.services.database.utilities.ODKDatabaseImplUtils.java
/** * Get a {@link BaseTable} for this table based on the given sql query. All * columns from the table are returned. Up to sqlLimit rows are returned * (zero is infinite)./* w w w. ja va2 s . c o m*/ * <p/> * The result set is filtered according to the supplied rolesList if there * is a DEFAULT_ACCESS column present in the result set. * * @param db * @param sqlCommand the query to run * @param sqlBindArgs the selection parameters * @param sqlCommand * @param sqlQueryBounds offset and max number of rows to return (zero is infinite) * @param accessContext for managing what effective accesses to return * @return */ public BaseTable query(OdkConnectionInterface db, String tableId, String sqlCommand, Object[] sqlBindArgs, QueryBounds sqlQueryBounds, AccessContext accessContext) { Cursor c = null; try { c = rawQuery(db, sqlCommand, sqlBindArgs, sqlQueryBounds, accessContext); BaseTable table = buildBaseTable(db, c, tableId, accessContext.canCreateRow); return table; } finally { if (c != null && !c.isClosed()) { c.close(); } } }
From source file:org.opendatakit.common.android.provider.impl.FormsDiscoveryRunnable.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/*from w w w. j a va 2 s .co m*/ * formsFolder, only 'framework' forms should be allowed * * @param mediaPath * -- full formDir * @param isFormsFolder * @param baseStaleMediaPath * -- path prefix to the stale forms/framework directory. */ private final void updateFormDir(File formDir, boolean isFormsFolder, String baseStaleMediaPath) { String formDirectoryPath = formDir.getAbsolutePath(); Log.i(t, "[" + instanceCounter + "] 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 = context.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null, selection, selectionArgs, null); if (c == null) { Log.w(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " null cursor -- cannot update!"); return; } if (c.getCount() > 1) { c.close(); Log.w(t, "[" + instanceCounter + "] 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); context.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(context, appName, formDef); } else if (c.getCount() == 1) { c.moveToFirst(); String id = c.getString(c.getColumnIndex(FormsColumns.FORM_ID)); uri = Uri.withAppendedPath(Uri.withAppendedPath(formsProviderContentUri, appName), id); Long lastModificationDate = c.getLong(c.getColumnIndex(FormsColumns.DATE)); Long formDefModified = ODKFileUtils.getMostRecentlyModifiedDate(formDir); if (lastModificationDate.compareTo(formDefModified) == 0) { Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " formDef unchanged"); fi = new FormInfo(appName, c, false); needUpdate = false; } else { Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " formDef revised"); fi = new FormInfo(context, appName, formDef); needUpdate = true; } } else if (c.getCount() == 0) { // it should be new, try to parse it... fi = new FormInfo(context, 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); context.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); context.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName), selection, selectionArgs); return; } } } catch (SQLiteException e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); return; } catch (IOException e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); return; } catch (IllegalArgumentException e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); try { FileUtils.deleteDirectory(formDir); Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " Removing -- unable to parse formDef file: " + e.toString()); } catch (IOException e1) { e1.printStackTrace(); Log.i(t, "[" + instanceCounter + "] 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 { context.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName), selection, selectionArgs); } catch (SQLiteException e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); return; } catch (Exception e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] 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 = context.getContentResolver().query(uriApp, null, selection, selectionArgs, null); if (c == null) { Log.w(t, "[" + instanceCounter + "] 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) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); return; } catch (IOException e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] 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 = context.getContentResolver().update(uri, v, null, null); Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " " + count + " records successfully updated"); } else { context.getContentResolver().insert(Uri.withAppendedPath(formsProviderContentUri, appName), v); Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " one record successfully inserted"); } } catch (SQLiteException ex) { ex.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + ex.toString()); return; } }
From source file:org.opendatakit.services.database.utilities.ODKDatabaseImplUtils.java
/** * Verifies that the tableId exists in the database. * * @param db//from ww w . j av a 2 s.co m * @param tableId * @return true if table is listed in table definitions. */ public boolean hasTableId(OdkConnectionInterface db, String tableId) { Cursor c = null; try { //@formatter:off c = db.query(DatabaseConstants.TABLE_DEFS_TABLE_NAME, null, K_TABLE_DEFS_TABLE_ID_EQUALS_PARAM, new Object[] { tableId }, null, null, null, null); //@formatter:on // we know about the table... // tableId is the database table name... return (c != null) && c.moveToFirst() && (c.getCount() != 0); } finally { if (c != null && !c.isClosed()) { c.close(); } } }
From source file:org.opendatakit.services.database.utlities.ODKDatabaseImplUtils.java
/** * Return the health of a data table. The health can be one of * <ul>/*from w w w . j a v a2 s . co m*/ * <li>TABLE_HEALTH_IS_CLEAN = 0</li> * <li>TABLE_HEALTH_HAS_CONFLICTS = 1</li> * <li>TABLE_HEALTH_HAS_CHECKPOINTS = 2</li> * <li>TABLE_HEALTH_HAS_CHECKPOINTS_AND_CONFLICTS = 3</li> * <ul> * * @param db * @param tableId * @return */ public int getTableHealth(OdkConnectionInterface db, String tableId) { StringBuilder b = new StringBuilder(); b.append("SELECT SUM(case when _savepoint_type is null then 1 else 0 end) as checkpoints,") .append("SUM(case when _conflict_type is not null then 1 else 0 end) as conflicts from ") .append(tableId); Cursor c = null; try { c = db.rawQuery(b.toString(), null); Integer checkpoints = null; Integer conflicts = null; if (c != null) { if (c.moveToFirst()) { int idxCheckpoints = c.getColumnIndex("checkpoints"); int idxConflicts = c.getColumnIndex("conflicts"); checkpoints = CursorUtils.getIndexAsType(c, Integer.class, idxCheckpoints); conflicts = CursorUtils.getIndexAsType(c, Integer.class, idxConflicts); } c.close(); } int outcome = CursorUtils.TABLE_HEALTH_IS_CLEAN; if (checkpoints != null && checkpoints != 0) { outcome += CursorUtils.TABLE_HEALTH_HAS_CHECKPOINTS; } if (conflicts != null && conflicts != 0) { outcome += CursorUtils.TABLE_HEALTH_HAS_CONFLICTS; } return outcome; } finally { if (c != null && !c.isClosed()) { c.close(); } } }
From source file:org.opendatakit.survey.android.tasks.InstanceUploaderTask.java
@Override protected InstanceUploadOutcome doInBackground(String... toUpload) { mOutcome = new InstanceUploadOutcome(); mOutcome.mResults = new HashMap<String, String>(); mOutcome.mAuthRequestingServer = null; String auth = PropertiesSingleton.getProperty(appName, PreferencesActivity.KEY_AUTH); setAuth(auth);/*w ww . j a v a2 s . co m*/ String urlString = null; /** * retrieve the URL string for the table, if defined... otherwise, use the * app property values to construct it. */ { SQLiteDatabase db = null; Cursor c = null; try { db = DatabaseFactory.get().getDatabase(appContext, appName); c = db.query(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, null, KeyValueStoreColumns.TABLE_ID + "=? AND " + KeyValueStoreColumns.PARTITION + "=? AND " + KeyValueStoreColumns.ASPECT + "=? AND " + KeyValueStoreColumns.KEY + "=?", new String[] { uploadTableId, KeyValueStoreConstants.PARTITION_TABLE, KeyValueStoreConstants.ASPECT_DEFAULT, KeyValueStoreConstants.XML_SUBMISSION_URL }, null, null, null); if (c.getCount() == 1) { c.moveToFirst(); int idxValue = c.getColumnIndex(KeyValueStoreColumns.VALUE); urlString = c.getString(idxValue); } else if (c.getCount() != 0) { throw new IllegalStateException( "two or more entries for " + KeyValueStoreConstants.XML_SUBMISSION_URL); } } finally { c.close(); db.releaseReference(); } if (urlString == null) { urlString = PropertiesSingleton.getProperty(appName, PreferencesActivity.KEY_SERVER_URL); String submissionUrl = PropertiesSingleton.getProperty(appName, PreferencesActivity.KEY_SUBMISSION_URL); urlString = urlString + submissionUrl; } } // FormInfo fi = new FormInfo(appContext, appName, // ODKFileUtils.getuploadingForm.formDefFile); // get shared HttpContext so that authentication and cookies are // retained. HttpContext localContext = ClientConnectionManagerFactory.get(appName).getHttpContext(); HttpClient httpclient = ClientConnectionManagerFactory.get(appName) .createHttpClient(WebUtils.CONNECTION_TIMEOUT); Map<URI, URI> uriRemap = new HashMap<URI, URI>(); for (int i = 0; i < toUpload.length; ++i) { if (isCancelled()) { return mOutcome; } publishProgress(i + 1, toUpload.length); Uri toUpdate = Uri.withAppendedPath(InstanceProviderAPI.CONTENT_URI, appName + "/" + uploadTableId + "/" + StringEscapeUtils.escapeHtml4(toUpload[i])); Cursor c = null; try { c = appContext.getContentResolver().query(toUpdate, null, null, null, null); if (c.getCount() == 1 && c.moveToFirst()) { String id = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(InstanceColumns._ID)); String dataTableInstanceId = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID)); String lastOutcome = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(InstanceColumns.XML_PUBLISH_STATUS)); String submissionInstanceId = ODKDataUtils.genUUID(); // submissions always get a new legacy instance id UNLESS the last // submission failed, // in which case we retry the submission using the legacy instance id // associated with // that failure. This supports resumption of sends of forms with many // attachments. if (lastOutcome != null && lastOutcome.equals(InstanceColumns.STATUS_SUBMISSION_FAILED)) { String lastId = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(InstanceColumns.SUBMISSION_INSTANCE_ID)); if (lastId != null) { submissionInstanceId = lastId; } } c.close(); FileSet instanceFiles; try { instanceFiles = constructSubmissionFiles(dataTableInstanceId, submissionInstanceId); // NOTE: /submission must not be translated! It is // the well-known path on the server. if (!uploadOneSubmission(urlString, toUpdate, id, submissionInstanceId, instanceFiles, httpclient, localContext, uriRemap)) { return mOutcome; // get credentials... } } catch (JsonParseException e) { WebLogger.getLogger(appName).printStackTrace(e); mOutcome.mResults.put(id, fail + "unable to obtain manifest: " + dataTableInstanceId + " :: details: " + e.toString()); } catch (JsonMappingException e) { WebLogger.getLogger(appName).printStackTrace(e); mOutcome.mResults.put(id, fail + "unable to obtain manifest: " + dataTableInstanceId + " :: details: " + e.toString()); } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); mOutcome.mResults.put(id, fail + "unable to obtain manifest: " + dataTableInstanceId + " :: details: " + e.toString()); } } else { mOutcome.mResults.put("unknown", fail + "unable to retrieve instance information via: " + toUpdate.toString()); } } finally { if (c != null && !c.isClosed()) { c.close(); } } } return mOutcome; }
From source file:org.opendatakit.utilities.test.AbstractODKDatabaseUtilsTest.java
public void testMultithreadedMultipleDBInsertionWithSameSelect_ExpectPass() throws ActionNotAuthorizedException { int numOfThreads = 20; String tableId = testTable;//w ww .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; 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); }
From source file:org.opendatakit.utilities.test.AbstractODKDatabaseUtilsTest.java
public void testMultithreadedDBInsertionWithDBIntPerThreadWithTxn_ExpectPass() throws ActionNotAuthorizedException { int numOfThreads = 5; String tableId = testTable;/* w ww .j a v a2 s . 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(); 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.test.AbstractODKDatabaseUtilsTest.java
public void testMultithreadedDBInsertionWithClosingCursor_ExpectPass() throws ActionNotAuthorizedException { int numOfThreads = 5; String tableId = testTable;/* w ww. j a 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(); } 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.test.AbstractODKDatabaseUtilsTest.java
public void testMultithreadedDBInsertionWithDBIntPerThreadAndForQuery_ExpectPass() throws ActionNotAuthorizedException { int numOfThreads = 5; String tableId = testTable;//www . ja v a 2 s . 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 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); }