List of usage examples for android.database SQLException SQLException
public SQLException(String error)
From source file:com.csipsimple.db.DBProvider.java
@Override public Uri insert(Uri uri, ContentValues initialValues) { int matched = URI_MATCHER.match(uri); String matchedTable = null;//ww w. j ava 2s .c om Uri baseInsertedUri = null; switch (matched) { case ACCOUNTS: case ACCOUNTS_ID: matchedTable = SipProfile.ACCOUNTS_TABLE_NAME; baseInsertedUri = SipProfile.ACCOUNT_ID_URI_BASE; break; case CALLLOGS: case CALLLOGS_ID: matchedTable = SipManager.CALLLOGS_TABLE_NAME; baseInsertedUri = SipManager.CALLLOG_ID_URI_BASE; break; case FILTERS: case FILTERS_ID: matchedTable = SipManager.FILTERS_TABLE_NAME; baseInsertedUri = SipManager.FILTER_ID_URI_BASE; break; case MESSAGES: case MESSAGES_ID: matchedTable = SipMessage.MESSAGES_TABLE_NAME; baseInsertedUri = SipMessage.MESSAGE_ID_URI_BASE; break; case ACCOUNTS_STATUS_ID: long id = ContentUris.parseId(uri); synchronized (profilesStatus) { SipProfileState ps = new SipProfileState(); if (profilesStatus.containsKey(id)) { ContentValues currentValues = profilesStatus.get(id); ps.createFromContentValue(currentValues); } ps.createFromContentValue(initialValues); ContentValues cv = ps.getAsContentValue(); cv.put(SipProfileState.ACCOUNT_ID, id); profilesStatus.put(id, cv); Log.d(THIS_FILE, "Added " + cv); } getContext().getContentResolver().notifyChange(uri, null); return uri; default: break; } if (matchedTable == null) { throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri); } ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long rowId = db.insert(matchedTable, null, values); // If the insert succeeded, the row ID exists. if (rowId >= 0) { // TODO : for inserted account register it here Uri retUri = ContentUris.withAppendedId(baseInsertedUri, rowId); getContext().getContentResolver().notifyChange(retUri, null); if (matched == ACCOUNTS || matched == ACCOUNTS_ID) { broadcastAccountChange(rowId); } if (matched == CALLLOGS || matched == CALLLOGS_ID) { db.delete(SipManager.CALLLOGS_TABLE_NAME, CallLog.Calls._ID + " IN " + "(SELECT " + CallLog.Calls._ID + " FROM " + SipManager.CALLLOGS_TABLE_NAME + " ORDER BY " + CallLog.Calls.DEFAULT_SORT_ORDER + " LIMIT -1 OFFSET 500)", null); } if (matched == ACCOUNTS_STATUS || matched == ACCOUNTS_STATUS_ID) { broadcastRegistrationChange(rowId); } if (matched == FILTERS || matched == FILTERS_ID) { Filter.resetCache(); } return retUri; } throw new SQLException("Failed to insert row into " + uri); }
From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java
/** * This method removes the entry from the content provider, and also removes * any associated files. files: form.xml, [formmd5].formdef, formname * {directory}/*from w w w. jav a 2 s . c om*/ */ @Override public int delete(Uri uri, String where, String[] whereArgs) { List<String> segments = uri.getPathSegments(); if (segments.size() < 1 || segments.size() > 2) { throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri); } String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); WebLogger log = WebLogger.getLogger(appName); String uriFormId = ((segments.size() == 2) ? segments.get(1) : null); boolean isNumericId = StringUtils.isNumeric(uriFormId); // Modify the where clause to account for the presence of // a form id. Accept either: // (1) numeric _ID value // (2) string FORM_ID value. String whereId; String[] whereIdArgs; if (uriFormId == null) { whereId = where; whereIdArgs = whereArgs; } else { if (TextUtils.isEmpty(where)) { whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?"; whereIdArgs = new String[1]; whereIdArgs[0] = uriFormId; } else { whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")"; whereIdArgs = new String[whereArgs.length + 1]; whereIdArgs[0] = uriFormId; for (int i = 0; i < whereArgs.length; ++i) { whereIdArgs[i + 1] = whereArgs[i]; } } } Cursor del = null; Integer idValue = null; String tableIdValue = null; String formIdValue = null; HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>(); try { del = this.query(uri, null, whereId, whereIdArgs, null); if (del == null) { throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records"); } del.moveToPosition(-1); while (del.moveToNext()) { idValue = ODKDatabaseUtils.get().getIndexAsType(del, Integer.class, del.getColumnIndex(FormsColumns._ID)); tableIdValue = ODKDatabaseUtils.get().getIndexAsString(del, del.getColumnIndex(FormsColumns.TABLE_ID)); formIdValue = ODKDatabaseUtils.get().getIndexAsString(del, del.getColumnIndex(FormsColumns.FORM_ID)); File mediaDir = ODKFileUtils.asAppFile(appName, ODKDatabaseUtils.get().getIndexAsString(del, del.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH))); mediaDirs.put(mediaDir, (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS); } } catch (Exception e) { log.w(t, "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString()); } } finally { if (del != null && !del.isClosed()) { del.close(); } } SQLiteDatabase db = null; int count; try { db = DatabaseFactory.get().getDatabase(getContext(), appName); db.beginTransaction(); count = db.delete(DatabaseConstants.FORMS_TABLE_NAME, whereId, whereIdArgs); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); log.w(t, "Unable to perform deletion " + e.toString()); return 0; } finally { if (db != null) { db.endTransaction(); db.close(); } } // and attempt to move these directories to the stale forms location // so that they do not immediately get rescanned... for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) { try { moveDirectory(appName, entry.getValue(), entry.getKey()); } catch (IOException e) { e.printStackTrace(); log.e(t, "Unable to move directory " + e.toString()); } } if (count == 1) { Uri formUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), Long.toString(idValue)); getContext().getContentResolver().notifyChange(idUri, null); } else { getContext().getContentResolver().notifyChange(uri, null); } return count; }
From source file:fr.openbike.android.database.OpenBikeDBAdapter.java
public Cursor getStation(int id, String[] columns) throws SQLException { Cursor cursor = mDb.query(true, STATIONS_TABLE, columns, BaseColumns._ID + " = ? AND " + KEY_NETWORK + " = ?", new String[] { String.valueOf(id), String.valueOf(mPreferences.getInt(AbstractPreferencesActivity.NETWORK_PREFERENCE, AbstractPreferencesActivity.NO_NETWORK)) }, null, null, null, null);//from w w w . java 2 s. c o m if ((cursor.getCount() == 0) || !cursor.moveToFirst()) { throw new SQLException("No Station found with ID " + id); } return cursor; }
From source file:org.opendatakit.services.forms.provider.FormsProvider.java
/** * This method removes the entry from the content provider, and also removes * any associated files. files: form.xml, [formmd5].formdef, formname * {directory}//from ww w. ja va 2 s . co m */ @Override public synchronized int delete(@NonNull Uri uri, String where, String[] whereArgs) { possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs); WebLoggerIf logger = WebLogger.getLogger(pf.appName); String[] projection = { FormsColumns._ID, FormsColumns.TABLE_ID, FormsColumns.FORM_ID }; HashMap<String, FormSpec> directories = new HashMap<String, FormSpec>(); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; Cursor c = null; Integer idValue = null; String tableIdValue = null; String formIdValue = null; try { // Get the database and run the query // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName, dbHandleName); db.beginTransactionNonExclusive(); c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, pf.whereId, pf.whereIdArgs, null, null, null, null); if (c == null) { throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records"); } int idxId = c.getColumnIndex(FormsColumns._ID); int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID); int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID); if (c.moveToFirst()) { do { idValue = CursorUtils.getIndexAsType(c, Integer.class, idxId); tableIdValue = CursorUtils.getIndexAsString(c, idxTableId); formIdValue = CursorUtils.getIndexAsString(c, idxFormId); FormSpec formSpec = new FormSpec(); formSpec.tableId = tableIdValue; formSpec.formId = formIdValue; formSpec.success = false; directories.put(idValue.toString(), formSpec); } while (c.moveToNext()); } c.close(); c = null; // and now go through this list moving the directories // into the pending-deletion location and deleting them. for (Entry<String, FormSpec> de : directories.entrySet()) { String id = de.getKey(); FormSpec fs = de.getValue(); File srcDir = new File(ODKFileUtils.getFormFolder(pf.appName, fs.tableId, fs.formId)); File destDir = new File(ODKFileUtils.getPendingDeletionTablesFolder(pf.appName), fs.tableId + "." + fs.formId + "." + System.currentTimeMillis()); try { FileUtils.moveDirectory(srcDir, destDir); if (db.delete(DatabaseConstants.FORMS_TABLE_NAME, FormsColumns._ID + "=?", new String[] { id }) > 0) { fs.success = true; } } catch (IOException e) { logger.e(t, "Unable to move directory prior to deleting it: " + e.toString()); logger.printStackTrace(e); } } // commit the transaction... db.setTransactionSuccessful(); } catch (Exception e) { logger.w(t, "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString()); } } finally { if (db != null) { try { try { if (c != null && !c.isClosed()) { c.close(); } } finally { if (db.inTransaction()) { db.endTransaction(); } } } finally { try { db.releaseReference(); } finally { // this closes the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .removeConnection(pf.appName, dbHandleName); } } } } // and now, go through all the files in the pending-deletion // directory and try to release them. File destFolder = new File(ODKFileUtils.getPendingDeletionTablesFolder(pf.appName)); File[] delDirs = destFolder.listFiles(); for (File formIdDir : delDirs) { try { FileUtils.deleteDirectory(formIdDir); } catch (IOException e) { logger.e(t, "Unable to remove directory " + e.toString()); logger.printStackTrace(e); } } int failureCount = 0; for (Entry<String, FormSpec> e : directories.entrySet()) { String id = e.getKey(); FormSpec fs = e.getValue(); if (fs.success) { Uri formUri = Uri .withAppendedPath( Uri.withAppendedPath(Uri.withAppendedPath( Uri.parse("content://" + getFormsAuthority()), pf.appName), fs.tableId), fs.formId); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), pf.appName), id); getContext().getContentResolver().notifyChange(idUri, null); } else { ++failureCount; } } getContext().getContentResolver().notifyChange(uri, null); int count = directories.size(); if (failureCount != 0) { throw new SQLiteException( "Unable to delete all forms (" + (count - failureCount) + " of " + count + " deleted)"); } return count; }
From source file:org.opendatakit.common.android.provider.impl.InstanceProviderImpl.java
@Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { List<String> segments = uri.getPathSegments(); if (segments.size() != 3) { throw new SQLException("Unknown URI (does not specify instance!) " + uri); }/* ww w . jav a 2s . c o m*/ String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); String tableId = segments.get(1); // _ID in UPLOADS_TABLE_NAME String instanceId = segments.get(2); SQLiteDatabase db = null; int count = 0; try { db = DatabaseFactory.get().getDatabase(getContext(), appName); boolean success = false; try { success = ODKDatabaseUtils.get().hasTableId(db, tableId); } catch (Exception e) { e.printStackTrace(); throw new SQLException("Unknown URI (exception testing for tableId) " + uri); } if (!success) { throw new SQLException("Unknown URI (missing data table for tableId) " + uri); } String dbTableName = "\"" + tableId + "\""; // run the query to get all the ids... List<IdStruct> idStructs = new ArrayList<IdStruct>(); Cursor ref = null; try { // use this provider's query interface to get the set of ids that // match (if any) ref = this.query(uri, null, where, whereArgs, null); if (ref.getCount() != 0) { ref.moveToFirst(); do { String iId = ODKDatabaseUtils.get().getIndexAsString(ref, ref.getColumnIndex(InstanceColumns._ID)); String iIdDataTable = ODKDatabaseUtils.get().getIndexAsString(ref, ref.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID)); idStructs.add(new IdStruct(iId, iIdDataTable)); } while (ref.moveToNext()); } } finally { if (ref != null) { ref.close(); } } // update the values string... if (values.containsKey(InstanceColumns.XML_PUBLISH_STATUS)) { Date xmlPublishDate = new Date(); values.put(InstanceColumns.XML_PUBLISH_TIMESTAMP, TableConstants.nanoSecondsFromMillis(xmlPublishDate.getTime())); String xmlPublishStatus = values.getAsString(InstanceColumns.XML_PUBLISH_STATUS); if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) { String text = getDisplaySubtext(xmlPublishStatus, xmlPublishDate); values.put(InstanceColumns.DISPLAY_SUBTEXT, text); } } db.beginTransaction(); String[] args = new String[1]; for (IdStruct idStruct : idStructs) { args[0] = idStruct.idUploadsTable; count += db.update(DatabaseConstants.UPLOADS_TABLE_NAME, values, InstanceColumns._ID + "=?", args); } db.setTransactionSuccessful(); } finally { if (db != null) { db.endTransaction(); db.close(); } } getContext().getContentResolver().notifyChange(uri, null); return count; }
From source file:org.opendatakit.services.instance.provider.InstanceProvider.java
/** * This method removes the entry from the content provider, and also removes * any associated files. files: form.xml, [formmd5].formdef, formname * {directory}// ww w . ja v a 2s . co m */ @Override public synchronized int delete(@NonNull Uri uri, String where, String[] whereArgs) { possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); if (segments.size() < 2 || segments.size() > 3) { throw new SQLException("Unknown URI (too many segments!) " + uri); } String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); String tableId = segments.get(1); // _ID in UPLOADS_TABLE_NAME String instanceId = (segments.size() == 3 ? segments.get(2) : null); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; List<IdStruct> idStructs = new ArrayList<IdStruct>(); try { // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName, dbHandleName); db.beginTransactionNonExclusive(); boolean success = false; try { success = ODKDatabaseImplUtils.get().hasTableId(db, tableId); } catch (Exception e) { WebLogger.getLogger(appName).printStackTrace(e); throw new SQLException("Unknown URI (exception testing for tableId) " + uri); } if (success) { // delete the entries matching the filter criteria if (segments.size() == 2) { where = "(" + where + ") AND (" + InstanceColumns.DATA_INSTANCE_ID + "=? )"; if (whereArgs != null) { String[] args = new String[whereArgs.length + 1]; System.arraycopy(whereArgs, 0, args, 0, whereArgs.length); args[whereArgs.length] = instanceId; whereArgs = args; } else { whereArgs = new String[] { instanceId }; } } internalUpdate(db, uri, appName, tableId); Cursor del = null; try { del = internalQuery(db, uri, appName, tableId, instanceId, null, where, whereArgs, null); del.moveToPosition(-1); while (del.moveToNext()) { String iId = CursorUtils.getIndexAsString(del, del.getColumnIndex(InstanceColumns._ID)); String iIdDataTable = CursorUtils.getIndexAsString(del, del.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID)); idStructs.add(new IdStruct(iId, iIdDataTable)); String path = ODKFileUtils.getInstanceFolder(appName, tableId, iIdDataTable); File f = new File(path); if (f.exists()) { if (f.isDirectory()) { FileUtils.deleteDirectory(f); } else { f.delete(); } } } } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); throw new IllegalArgumentException("Unable to delete instance directory: " + e.toString()); } finally { if (del != null) { del.close(); } } } else { // delete anything we find, since the table doesn't exist Cursor del = null; try { where = InstanceColumns.DATA_TABLE_TABLE_ID + "=?"; whereArgs = new String[] { tableId }; del = db.query(DatabaseConstants.UPLOADS_TABLE_NAME, null, where, whereArgs, null, null, null, null); del.moveToPosition(-1); while (del.moveToNext()) { String iId = CursorUtils.getIndexAsString(del, del.getColumnIndex(InstanceColumns._ID)); String iIdDataTable = CursorUtils.getIndexAsString(del, del.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID)); idStructs.add(new IdStruct(iId, iIdDataTable)); String path = ODKFileUtils.getInstanceFolder(appName, tableId, iIdDataTable); File f = new File(path); if (f.exists()) { if (f.isDirectory()) { FileUtils.deleteDirectory(f); } else { f.delete(); } } } } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); throw new IllegalArgumentException("Unable to delete instance directory: " + e.toString()); } finally { if (del != null) { del.close(); } } } for (IdStruct idStruct : idStructs) { db.delete(DatabaseConstants.UPLOADS_TABLE_NAME, InstanceColumns.DATA_INSTANCE_ID + "=?", new String[] { idStruct.idUploadsTable }); db.delete(tableId, DATA_TABLE_ID_COLUMN + "=?", new String[] { idStruct.idDataTable }); } db.setTransactionSuccessful(); } finally { if (db != null) { try { if (db.inTransaction()) { db.endTransaction(); } } finally { try { db.releaseReference(); } finally { // this closes the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName, dbHandleName); } } } } getContext().getContentResolver().notifyChange(uri, null); return idStructs.size(); }
From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java
@Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { List<String> segments = uri.getPathSegments(); if (segments.size() < 1 || segments.size() > 2) { throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri); }/* w w w . j a v a 2s .c om*/ String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); WebLogger log = WebLogger.getLogger(appName); String uriFormId = ((segments.size() == 2) ? segments.get(1) : null); boolean isNumericId = StringUtils.isNumeric(uriFormId); // Modify the where clause to account for the presence of // a form id. Accept either: // (1) numeric _ID value // (2) string FORM_ID value. String whereId; String[] whereIdArgs; if (uriFormId == null) { whereId = where; whereIdArgs = whereArgs; } else { if (TextUtils.isEmpty(where)) { whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?"; whereIdArgs = new String[1]; whereIdArgs[0] = uriFormId; } else { whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")"; whereIdArgs = new String[whereArgs.length + 1]; whereIdArgs[0] = uriFormId; for (int i = 0; i < whereArgs.length; ++i) { whereIdArgs[i + 1] = whereArgs[i]; } } } /* * First, find out what records match this query, and if they refer to two * or more (formId,formVersion) tuples, then be sure to remove all * FORM_MEDIA_PATH references. Otherwise, if they are all for the same * tuple, and the update specifies a FORM_MEDIA_PATH, move all the * non-matching directories elsewhere. */ Integer idValue = null; String tableIdValue = null; String formIdValue = null; HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>(); boolean multiset = false; Cursor c = null; try { c = this.query(uri, null, whereId, whereIdArgs, null); if (c == null) { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row did not return a cursor"); } if (c.getCount() >= 1) { FormIdVersion ref = null; c.moveToPosition(-1); while (c.moveToNext()) { idValue = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, c.getColumnIndex(FormsColumns._ID)); tableIdValue = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.TABLE_ID)); formIdValue = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID)); String tableId = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.TABLE_ID)); String formId = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID)); String formVersion = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_VERSION)); FormIdVersion cur = new FormIdVersion(tableId, formId, formVersion); int appRelativeMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH); String mediaPath = ODKDatabaseUtils.get().getIndexAsString(c, appRelativeMediaPathIdx); if (mediaPath != null) { mediaDirs.put(ODKFileUtils.asAppFile(appName, mediaPath), (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS); } if (ref != null && !ref.equals(cur)) { multiset = true; break; } else { ref = cur; } } } } catch (Exception e) { log.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString()); } } finally { if (c != null) { c.close(); } } if (multiset) { // don't let users manually update media path // we are referring to two or more (formId,formVersion) tuples. if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) { values.remove(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH); } } else if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) { // we are not a multiset and we are setting the media path // try to move all the existing non-matching media paths to // somewhere else... File mediaPath = ODKFileUtils.asAppFile(appName, values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)); for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) { File altPath = entry.getKey(); if (!altPath.equals(mediaPath)) { try { moveDirectory(appName, entry.getValue(), altPath); } catch (IOException e) { e.printStackTrace(); log.e(t, "Attempt to move " + altPath.getAbsolutePath() + " failed: " + e.toString()); } } } // OK. we have moved the existing form definitions elsewhere. We can // proceed with update... } // ensure that all values are correct and ignore some user-supplied // values... patchUpValues(appName, values); // Make sure that the necessary fields are all set if (values.containsKey(FormsColumns.DATE) == true) { Date today = new Date(); String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(today); values.put(FormsColumns.DISPLAY_SUBTEXT, ts); } SQLiteDatabase db = null; int count; try { // OK Finally, now do the update... db = DatabaseFactory.get().getDatabase(getContext(), appName); db.beginTransaction(); count = db.update(DatabaseConstants.FORMS_TABLE_NAME, values, whereId, whereIdArgs); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); log.w(t, "Unable to perform update " + uri); return 0; } finally { if (db != null) { db.endTransaction(); db.close(); } } if (count == 1) { Uri formUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), Long.toString(idValue)); getContext().getContentResolver().notifyChange(idUri, null); } else { getContext().getContentResolver().notifyChange(uri, null); } return count; }
From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java
private Uri insertArtwork(@NonNull final Uri uri, final ContentValues values) { Context context = getContext(); if (context == null) { return null; }//from w w w . j ava 2 s . c o m if (values == null) { throw new IllegalArgumentException("Invalid ContentValues: must not be null"); } if (!values.containsKey(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME) || TextUtils.isEmpty(values.getAsString(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME))) { throw new IllegalArgumentException("Initial values must contain component name: " + values); } // Check to make sure the component name is valid ComponentName componentName = ComponentName .unflattenFromString(values.getAsString(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME)); if (componentName == null) { throw new IllegalArgumentException("Invalid component name: " + values.getAsString(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME)); } // Make sure they are using the short string format values.put(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME, componentName.flattenToShortString()); // Ensure the app inserting the artwork is either Muzei or the same app as the source String callingPackageName = getCallingPackage(); if (!context.getPackageName().equals(callingPackageName) && !TextUtils.equals(callingPackageName, componentName.getPackageName())) { throw new IllegalArgumentException("Calling package name (" + callingPackageName + ") must match the source's package name (" + componentName.getPackageName() + ")"); } if (values.containsKey(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT)) { String viewIntentString = values.getAsString(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT); Intent viewIntent; try { if (!TextUtils.isEmpty(viewIntentString)) { // Make sure it is a valid Intent URI viewIntent = Intent.parseUri(viewIntentString, Intent.URI_INTENT_SCHEME); // Make sure we can construct a PendingIntent for the Intent PendingIntent.getActivity(context, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT); } } catch (URISyntaxException e) { Log.w(TAG, "Removing invalid View Intent: " + viewIntentString, e); values.remove(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT); } catch (RuntimeException e) { // This is actually meant to catch a FileUriExposedException, but you can't // have catch statements for exceptions that don't exist at your minSdkVersion Log.w(TAG, "Removing invalid View Intent that contains a file:// URI: " + viewIntentString, e); values.remove(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT); } } // Ensure the related source has been added to the database. // This should be true in 99.9% of cases, but the insert will fail if this isn't true Cursor sourceQuery = querySource(MuzeiContract.Sources.CONTENT_URI, new String[] { BaseColumns._ID }, MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME + "=?", new String[] { componentName.flattenToShortString() }, null); if (sourceQuery == null || sourceQuery.getCount() == 0) { ContentValues initialValues = new ContentValues(); initialValues.put(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME, componentName.flattenToShortString()); insertSource(MuzeiContract.Sources.CONTENT_URI, initialValues); } if (sourceQuery != null) { sourceQuery.close(); } values.put(MuzeiContract.Artwork.COLUMN_NAME_DATE_ADDED, System.currentTimeMillis()); final SQLiteDatabase db = databaseHelper.getWritableDatabase(); long rowId = db.insert(MuzeiContract.Artwork.TABLE_NAME, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI, values); // If the insert succeeded, the row ID exists. if (rowId > 0) { // Creates a URI with the artwork ID pattern and the new row ID appended to it. final Uri artworkUri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, rowId); File artwork = getCacheFileForArtworkUri(artworkUri); if (artwork != null && artwork.exists()) { // The image already exists so we'll notifyChange() to say the new artwork is ready // Otherwise, this will be called when the file is written with openFile() // using this Uri and the actual artwork is written successfully notifyChange(artworkUri); } return artworkUri; } // If the insert didn't succeed, then the rowID is <= 0 throw new SQLException("Failed to insert row into " + uri); }
From source file:org.opendatakit.services.forms.provider.FormsProvider.java
@Override public synchronized int update(@NonNull Uri uri, ContentValues values, String where, String[] whereArgs) { possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs); WebLoggerIf logger = WebLogger.getLogger(pf.appName); /*/*from w w w . j a va2 s .co m*/ * First, find out what records match this query. Replicate the * ContentValues if there are multiple tableIds/formIds involved * and the contentValues do not have formId and tableId specified. * * Otherwise, it is an error to specify the tableId or formId in * the ContentValues and have those not match the where results. * */ String contentTableId = (values != null && values.containsKey(FormsColumns.TABLE_ID)) ? values.getAsString(FormsColumns.TABLE_ID) : null; String contentFormId = (values != null && values.containsKey(FormsColumns.FORM_ID)) ? values.getAsString(FormsColumns.FORM_ID) : null; HashMap<FormSpec, HashMap<String, Object>> matchedValues = new HashMap<FormSpec, HashMap<String, Object>>(); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; try { // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName, dbHandleName); db.beginTransactionNonExclusive(); Cursor c = null; try { c = db.query(DatabaseConstants.FORMS_TABLE_NAME, null, pf.whereId, pf.whereIdArgs, null, null, null, null); if (c == null) { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row did not return a cursor"); } if (c.moveToFirst()) { int idxId = c.getColumnIndex(FormsColumns._ID); int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID); int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID); Integer idValue = null; String tableIdValue = null; String formIdValue = null; do { idValue = CursorUtils.getIndexAsType(c, Integer.class, idxId); tableIdValue = CursorUtils.getIndexAsString(c, idxTableId); formIdValue = CursorUtils.getIndexAsString(c, idxFormId); if (contentTableId != null && !contentTableId.equals(tableIdValue)) { throw new SQLException("Modification of tableId for an existing form is prohibited"); } if (contentFormId != null && !contentFormId.equals(formIdValue)) { throw new SQLException("Modification of formId for an existing form is prohibited"); } HashMap<String, Object> cv = new HashMap<String, Object>(); if (values != null) { for (String key : values.keySet()) { cv.put(key, values.get(key)); } } cv.put(FormsColumns.TABLE_ID, tableIdValue); cv.put(FormsColumns.FORM_ID, formIdValue); for (int idx = 0; idx < c.getColumnCount(); ++idx) { String colName = c.getColumnName(idx); if (colName.equals(FormsColumns._ID)) { // don't insert the PK continue; } if (c.isNull(idx)) { cv.put(colName, null); } else { // everything else, we control... Class<?> dataType = CursorUtils.getIndexDataType(c, idx); if (dataType == String.class) { cv.put(colName, CursorUtils.getIndexAsString(c, idx)); } else if (dataType == Long.class) { cv.put(colName, CursorUtils.getIndexAsType(c, Long.class, idx)); } else if (dataType == Double.class) { cv.put(colName, CursorUtils.getIndexAsType(c, Double.class, idx)); } } } FormSpec formSpec = patchUpValues(pf.appName, cv); formSpec._id = idValue.toString(); formSpec.success = false; matchedValues.put(formSpec, cv); } while (c.moveToNext()); } else { // no match on where clause... return 0; } } finally { if (c != null && !c.isClosed()) { c.close(); } } // go through the entries and update the database with these patched-up values... for (Entry<FormSpec, HashMap<String, Object>> e : matchedValues.entrySet()) { FormSpec fs = e.getKey(); HashMap<String, Object> cv = e.getValue(); if (db.update(DatabaseConstants.FORMS_TABLE_NAME, cv, FormsColumns._ID + "=?", new String[] { fs._id }) > 0) { fs.success = true; } } db.setTransactionSuccessful(); } catch (Exception e) { logger.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString()); } } finally { if (db != null) { try { if (db.inTransaction()) { db.endTransaction(); } } finally { try { db.releaseReference(); } finally { // this closes the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .removeConnection(pf.appName, dbHandleName); } } } } int failureCount = 0; for (FormSpec fs : matchedValues.keySet()) { if (fs.success) { Uri formUri = Uri .withAppendedPath( Uri.withAppendedPath(Uri.withAppendedPath( Uri.parse("content://" + getFormsAuthority()), pf.appName), fs.tableId), fs.formId); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), pf.appName), fs._id); getContext().getContentResolver().notifyChange(idUri, null); } else { ++failureCount; } } getContext().getContentResolver().notifyChange(uri, null); int count = matchedValues.size(); if (failureCount != 0) { throw new SQLiteException( "Unable to update all forms (" + (count - failureCount) + " of " + count + " updated)"); } return count; }
From source file:org.opendatakit.services.instance.provider.InstanceProvider.java
@Override public synchronized int update(@NonNull Uri uri, ContentValues cv, String where, String[] whereArgs) { possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); if (segments.size() != 3) { throw new SQLException("Unknown URI (does not specify instance!) " + uri); }//from ww w. ja va 2 s .c om String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); String tableId = segments.get(1); // _ID in UPLOADS_TABLE_NAME String instanceId = segments.get(2); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; int count = 0; try { // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName, dbHandleName); db.beginTransactionNonExclusive(); boolean success = false; try { success = ODKDatabaseImplUtils.get().hasTableId(db, tableId); } catch (Exception e) { WebLogger.getLogger(appName).printStackTrace(e); throw new SQLException("Unknown URI (exception testing for tableId) " + uri); } if (!success) { throw new SQLException("Unknown URI (missing data table for tableId) " + uri); } internalUpdate(db, uri, appName, tableId); // run the query to get all the ids... List<IdStruct> idStructs = new ArrayList<IdStruct>(); Cursor ref = null; try { // use this provider's query interface to get the set of ids that // match (if any) ref = internalQuery(db, uri, appName, tableId, instanceId, null, where, whereArgs, null); ref.moveToFirst(); if (ref.getCount() != 0) { do { String iId = CursorUtils.getIndexAsString(ref, ref.getColumnIndex(InstanceColumns._ID)); String iIdDataTable = CursorUtils.getIndexAsString(ref, ref.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID)); idStructs.add(new IdStruct(iId, iIdDataTable)); } while (ref.moveToNext()); } } finally { if (ref != null) { ref.close(); } } // update the values string... if (cv.containsKey(InstanceColumns.XML_PUBLISH_STATUS)) { Date xmlPublishDate = new Date(); cv.put(InstanceColumns.XML_PUBLISH_TIMESTAMP, TableConstants.nanoSecondsFromMillis(xmlPublishDate.getTime())); String xmlPublishStatus = cv.getAsString(InstanceColumns.XML_PUBLISH_STATUS); if (!cv.containsKey(InstanceColumns.DISPLAY_SUBTEXT)) { String text = getDisplaySubtext(xmlPublishStatus, xmlPublishDate); cv.put(InstanceColumns.DISPLAY_SUBTEXT, text); } } Map<String, Object> values = new HashMap<String, Object>(); for (String key : cv.keySet()) { values.put(key, cv.get(key)); } Object[] args = new String[1]; for (IdStruct idStruct : idStructs) { args[0] = idStruct.idUploadsTable; count += db.update(DatabaseConstants.UPLOADS_TABLE_NAME, values, InstanceColumns._ID + "=?", args); } db.setTransactionSuccessful(); } finally { if (db != null) { try { if (db.inTransaction()) { db.endTransaction(); } } finally { try { db.releaseReference(); } finally { // this closes the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName, dbHandleName); } } } } getContext().getContentResolver().notifyChange(uri, null); return count; }