下面列出了怎么用android.database.sqlite.SQLiteConstraintException的API类实例代码及写法,或者点击链接到github查看源代码。
private static final void readExceptionFromParcel(Parcel reply, String msg, int code) {
switch (code) {
case 2:
throw new IllegalArgumentException(msg);
case 3:
throw new UnsupportedOperationException(msg);
case 4:
throw new SQLiteAbortException(msg);
case 5:
throw new SQLiteConstraintException(msg);
case 6:
throw new SQLiteDatabaseCorruptException(msg);
case 7:
throw new SQLiteFullException(msg);
case 8:
throw new SQLiteDiskIOException(msg);
case 9:
throw new SQLiteException(msg);
case 11:
throw new OperationCanceledException(msg);
default:
reply.readException(code, msg);
}
}
public synchronized long insertEmoticonBean(EmoticonBean bean, String beanSetName) {
SQLiteDatabase db = mOpenDbHelper.getWritableDatabase();
long result = -1;
if (bean == null || db == null) {
return result;
}
ContentValues values = new ContentValues();
values.put(TableColumns.EmoticonColumns.EVENT_TYPE, bean.getEventType());
values.put(TableColumns.EmoticonColumns.TAG, bean.getTag());
values.put(TableColumns.EmoticonColumns.NAME, bean.getName());
values.put(TableColumns.EmoticonColumns.ICON_URI, bean.getIconUri());
values.put(TableColumns.EmoticonColumns.MSG_URI, bean.getMsgUri());
values.put(TableColumns.EmoticonColumns.EMOTICON_SET_NAME, beanSetName);
try {
result = db.insert(TABLE_NAME_EMOTICONS, null, values);
} catch (SQLiteConstraintException e) {
Log.e(TAG, "insert failed", e);
}
return result;
}
@Test
public void testOnUpgradeWithColumnChangeToNotNull() throws Exception {
getHelperInstance()
.getReadableDatabase()
.execSQL("CREATE TABLE testTable3 ("
+ " `xx` INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " `str` TEXT,"
+ " `unique` UNIQUE,"
+ " `foreign` INTEGER,"
+ " FOREIGN KEY(`foreign`) REFERENCES test_table(`unique`)"
+ ");"
);
SQLiteOperator<TestTable3> operator = SQLiteOperator.from(getContext(), TestTable3.class);
TestTable3 t = new TestTable3();
operator.save(t).executeBlocking();
operator.delete(t).executeBlocking();
getHelperInstance().onUpgrade(getHelperInstance().getWritableDatabase(), 1, 2);
exception.expect(SQLiteConstraintException.class);
operator.save(new TestTable3()).executeBlocking();
}
@Test
public void testOnUpgradeWithColumnChangeToUnique() throws Exception {
getHelperInstance()
.getReadableDatabase()
.execSQL("CREATE TABLE testTable3 ("
+ " `xx` INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " `str` TEXT,"
+ " `unique` TEXT,"
+ " `foreign` INTEGER,"
+ " FOREIGN KEY(`foreign`) REFERENCES test_table(`unique`)"
+ ");"
);
SQLiteOperator<TestTable3> operator = SQLiteOperator.from(getContext(), TestTable3.class);
getHelperInstance().onUpgrade(getHelperInstance().getWritableDatabase(), 1, 2);
exception.expect(SQLiteConstraintException.class);
TestTable3 t = new TestTable3();
t.str = "not null";
t.unique = "a";
operator.save(t).executeBlocking();
t = new TestTable3();
t.str = "xxx";
t.unique = "a";
operator.save(t).executeBlocking();
}
/**
* Inserts a new category into the database.
* @param c the current context.
* @param name the name of the category
*/
public static boolean addCategory(Context c, String name) {
boolean success = true;
DbOpenHelper dbHelper = new DbOpenHelper(c);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CategoryEntry.COLUMN_NAME, name.trim());
try {
db.insertOrThrow(CategoryEntry.TABLE_NAME, null, values);
} catch (SQLiteConstraintException e) {
success = false;
}
db.close();
return success;
}
/**
* Test run insert abort.
*
* @throws IOException Signals that an I/O exception has occurred.
* @throws InstantiationException the instantiation exception
* @throws IllegalAccessException the illegal access exception
*/
@Test
public void testRunInsertAbort() throws IOException, InstantiationException, IllegalAccessException {
this.expectedKriptonRuntimeExceptionWithCause(SQLiteConstraintException.class);
BindBean93DataSource dataSource = BindBean93DataSource.getInstance();
final Bean93 bean = new Bean93();
bean.name = "all";
dataSource.execute(new BindBean93DataSource.Transaction() {
@Override
public TransactionResult onExecute(BindBean93DaoFactory daoFactory) {
Bean93DaoImpl dao = daoFactory.getBean93Dao();
dao.insertDefault(bean);
dao.insertAbort(bean);
assertTrue(dao.selectAll().size() == 1);
return TransactionResult.ROLLBACK;
}
});
}
/**
* Test run insert fail.
*
* @throws IOException Signals that an I/O exception has occurred.
* @throws InstantiationException the instantiation exception
* @throws IllegalAccessException the illegal access exception
*/
@Test
public void testRunInsertFail() throws IOException, InstantiationException, IllegalAccessException {
this.expectedKriptonRuntimeExceptionWithCause(SQLiteConstraintException.class);
BindBean93DataSource dataSource = BindBean93DataSource.getInstance();
final Bean93 bean = new Bean93();
bean.name = "all";
dataSource.execute(new BindBean93DataSource.Transaction() {
@Override
public TransactionResult onExecute(BindBean93DaoFactory daoFactory) {
Bean93DaoImpl dao = daoFactory.getBean93Dao();
dao.insertDefault(bean);
dao.insertFail(bean);
assertTrue(dao.selectAll().size() == 1);
return TransactionResult.ROLLBACK;
}
});
}
/**
* Test run insert rollback.
*
* @throws IOException Signals that an I/O exception has occurred.
* @throws InstantiationException the instantiation exception
* @throws IllegalAccessException the illegal access exception
*/
@Test
public void testRunInsertRollback() throws IOException, InstantiationException, IllegalAccessException {
this.expectedKriptonRuntimeExceptionWithCause(SQLiteConstraintException.class);
BindBean93DataSource dataSource = BindBean93DataSource.getInstance();
final Bean93 bean = new Bean93();
bean.name = "all";
dataSource.execute(new BindBean93DataSource.Transaction() {
@Override
public TransactionResult onExecute(BindBean93DaoFactory daoFactory) {
Bean93DaoImpl dao = daoFactory.getBean93Dao();
dao.insertDefault(bean);
dao.insertRollback(bean);
assertTrue(dao.selectAll().size() == 0);
return TransactionResult.ROLLBACK;
}
});
}
public synchronized long insertEmoticonBean(EmoticonBean bean, String beanSetName) {
SQLiteDatabase db = mOpenDbHelper.getWritableDatabase();
long result = -1;
if (bean == null || db == null) {
return result;
}
ContentValues values = new ContentValues();
values.put(TableColumns.EmoticonItem.EVENT_TYPE, bean.getEventType());
values.put(TableColumns.EmoticonItem.TAG, bean.getTag());
values.put(TableColumns.EmoticonItem.NAME, bean.getName());
values.put(TableColumns.EmoticonItem.ICON_URI, bean.getIconUri());
values.put(TableColumns.EmoticonItem.MSG_URI, bean.getMsgUri());
values.put(TableColumns.EmoticonItem.EMOTICON_SET_NAME, beanSetName);
try {
result = db.insert(TABLE_NAME_EMOTICON, null, values);
} catch (SQLiteConstraintException e) {
Log.e(TAG, "insert failed", e);
}
return result;
}
public boolean update(AppRule appRule) {
ContentValues contentValues = new ContentValues();
contentValues.put(natDBHelper.COLUMN_APPNAME, appRule.getPkgName());
contentValues.put(natDBHelper.COLUMN_APPUID, String.valueOf(appRule.getAppUID()));
contentValues.put(natDBHelper.COLUMN_ONIONTYPE, appRule.getOnionType());
contentValues.put(natDBHelper.COLUMN_LOCALHOST, appRule.getLocalHost()?1:0);
contentValues.put(natDBHelper.COLUMN_LOCALNETWORK, appRule.getLocalNetwork()?1:0);
String filter = natDBHelper.COLUMN_APPUID + "=?";
String[] filterArgs = {String.valueOf(appRule.getAppUID())};
SQLiteDatabase db = this.dbHelper.getWritableDatabase();
int nb_row = 0;
try {
nb_row = db.update(natDBHelper.NAT_TABLE_NAME, contentValues, filter, filterArgs);
} catch (SQLiteConstraintException e) {
Log.e(TAG, "Constraint exception");
Log.e(TAG, e.getMessage());
}
db.close();
return (nb_row == 1);
}
public void createBookmarkModelEntry(BookmarkModel bookmarkModel) {
ContentValues values = new ContentValues();
try {
values.put(SQLiteHelper.COLUMN_NEWSPAPER_NAME, bookmarkModel.getNewspaperName());
values.put(SQLiteHelper.COLUMN_CATEGORY_NAME, bookmarkModel.getCategoryName());
values.put(SQLiteHelper.COLUMN_NEWS_HEADLINE, bookmarkModel.getmArticleHeadline());
values.put(SQLiteHelper.COLUMN_NEWS_BODY, bookmarkModel.getmArticleBody());
values.put(SQLiteHelper.COLUMN_NEWS_ARTICLE_URL, bookmarkModel.getmArticleURL());
values.put(SQLiteHelper.COLUMN_NEWS_PUB_DATE, bookmarkModel.getmArticlePubDate());
values.put(SQLiteHelper.COLUMN_NEWS_IMAGE_URL, bookmarkModel.getmArticleImageURL());
} catch (SQLiteConstraintException sqe){
Crashlytics.log("Exception while creating sqlite entry - " + sqe.getMessage());
}
long insertId = database.insert(SQLiteHelper.TABLE_READ_IT_LATER, null,
values);
//Log.d(TAG, "Created entry "+insertId);
Cursor cursor = database.query(SQLiteHelper.TABLE_READ_IT_LATER,
allColumns, SQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
cursor.close();
}
/**
* Special function for writing an exception result at the header of
* a parcel, to be used when returning an exception from a transaction.
* exception will be re-thrown by the function in another process
* @param reply Parcel to write to
* @param e The Exception to be written.
* @see Parcel#writeNoException
* @see Parcel#writeException
*/
public static final void writeExceptionToParcel(Parcel reply, Exception e) {
int code = 0;
boolean logException = true;
if (e instanceof FileNotFoundException) {
code = 1;
logException = false;
} else if (e instanceof IllegalArgumentException) {
code = 2;
} else if (e instanceof UnsupportedOperationException) {
code = 3;
} else if (e instanceof SQLiteAbortException) {
code = 4;
} else if (e instanceof SQLiteConstraintException) {
code = 5;
} else if (e instanceof SQLiteDatabaseCorruptException) {
code = 6;
} else if (e instanceof SQLiteFullException) {
code = 7;
} else if (e instanceof SQLiteDiskIOException) {
code = 8;
} else if (e instanceof SQLiteException) {
code = 9;
} else if (e instanceof OperationApplicationException) {
code = 10;
} else if (e instanceof OperationCanceledException) {
code = 11;
logException = false;
} else {
reply.writeException(e);
Log.e(TAG, "Writing exception to parcel", e);
return;
}
reply.writeInt(code);
reply.writeString(e.getMessage());
if (logException) {
Log.e(TAG, "Writing exception to parcel", e);
}
}
@Test(timeout = 1000)
public void singleContactInsert() throws Exception {
boolean foreignKeyConstraintFailed = false;
try {
mContactDao.insert(mContact2);
} catch (SQLiteConstraintException e) {
foreignKeyConstraintFailed = true;
}
assertThat(foreignKeyConstraintFailed, is(true));
}
@MediumTest
@Test
public void testStatementConstraint() {
mDatabase.execSQL("CREATE TABLE test (num INTEGER NOT NULL);");
SQLiteStatement statement = mDatabase.compileStatement("INSERT INTO test (num) VALUES (?)");
// Try to insert NULL, which violates the constraint
try {
statement.clearBindings();
statement.execute();
fail("expected exception not thrown");
} catch (SQLiteConstraintException e) {
// expected
}
// Make sure the statement can still be used
statement.bindLong(1, 1);
statement.execute();
statement.close();
Cursor c = mDatabase.query("test", null, null, null, null, null, null);
int numCol = c.getColumnIndexOrThrow("num");
c.moveToFirst();
long num = c.getLong(numCol);
assertEquals(1, num);
c.close();
}
@Test
public void test_message_shouldNotSaveMessageWithNullId() throws Exception {
Message message = new Message();
message.setMessageId(null);
try {
databaseHelper.save(new SqliteMessage(message));
fail();
} catch (SQLiteConstraintException ignored) {
}
}
public boolean deleteMyCamera(MyCameraInfo myCamera) {
try {
mDatabase.execSQL("DELETE FROM MyCamera WHERE IP=? AND PORT=?", new String[]{myCamera.getIP(), myCamera.getPort() + ""});
return true;
} catch (SQLiteConstraintException e) {
e.printStackTrace();
}
return false;
}
public boolean saveMyCamera(MyCameraInfo myCameraInfo) {
try {
mDatabase.execSQL("INSERT INTO MyCamera(IP,PORT,PASSWORD,NOTE,DEVICE_ID,CAM_NUMBER,TYPE) VALUES (?,?,?,?,?,?,?)",
new String[]{myCameraInfo.getIP(), myCameraInfo.getPort() + "", myCameraInfo.getPassword(), myCameraInfo.getNote(),
myCameraInfo.getDeviceId(), myCameraInfo.getCamNumber() + "", myCameraInfo.getType() + ""});
return true;
} catch (SQLiteConstraintException e) {
e.printStackTrace();
}
return false;
}
public boolean updateMyCamera(String oldIP, int oldPort, MyCameraInfo myCameraInfo) {
try {
mDatabase.execSQL("UPDATE MyCamera SET IP=?,PORT=?,PASSWORD=?,NOTE=?,DEVICE_ID=?,CAM_NUMBER=?,TYPE=? WHERE IP=? AND PORT=?", new String[]{
myCameraInfo.getIP(), myCameraInfo.getPort() + "", myCameraInfo.getPassword(), myCameraInfo.getNote(), myCameraInfo.getDeviceId(), myCameraInfo.getCamNumber() + "", myCameraInfo.getType() + "",
oldIP, oldPort + ""
});
return true;
} catch (SQLiteConstraintException e) {
e.printStackTrace();
}
return false;
}
@Test(expected = SQLiteConstraintException.class)
public void testFailingForeignKeyConstraint() throws Exception {
SQLiteOperator<TestTable4> operator = SQLiteOperator.from(getContext(), TestTable4.class);
TestTable4 table4 = new TestTable4();
table4.foreignKey = new TestTable();
operator.save(table4).executeBlocking();
}
@Test(expected = SQLiteConstraintException.class)
public void testFailingUniqueConstraint() throws Exception {
SQLiteOperator<TestTable4> operator = SQLiteOperator.from(getContext(), TestTable4.class);
TestTable4 t1 = new TestTable4();
t1.uniqueField = "notUnique";
operator.save(t1).executeBlocking();
TestTable4 t2 = new TestTable4();
t2.uniqueField = "notUnique";
operator.save(t2).executeBlocking();
}
/**
* @param url URL to the root of the used Nextcloud instance without trailing slash
* @param username Username of the account
* @param accountName Composed by the username and the host of the URL, separated by @-sign
* @param capabilities {@link Capabilities} object containing information about the brand colors, supported API versions, etc...
* @throws SQLiteConstraintException in case accountName already exists
*/
public void addAccount(@NonNull String url, @NonNull String username, @NonNull String accountName, @NonNull Capabilities capabilities) throws SQLiteConstraintException {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues(4);
values.put(key_url, url);
values.put(key_username, username);
values.put(key_account_name, accountName);
values.put(key_capabilities_etag, capabilities.getETag());
long accountId = db.insertOrThrow(table_accounts, null, values);
updateBrand(accountId, capabilities);
}
public long insertActivityReport(int type, long time, int year, int month, int day, int hour, int[] dataArray, String subData) throws SQLiteConstraintException {
if(time < 1 || dataArray == null || dataArray.length < 5)
return -1;
ContentValues insertValues = new ContentValues();
insertValues.put(KEY_ACCEL_TYPE, type);
insertValues.put(KEY_ACCEL_TIME, time);
insertValues.put(KEY_ACCEL_YEAR, year);
insertValues.put(KEY_ACCEL_MONTH, month);
insertValues.put(KEY_ACCEL_DAY, day);
insertValues.put(KEY_ACCEL_HOUR, hour);
insertValues.put(KEY_ACCEL_DATA1, dataArray[0]); // Sum of calorie
insertValues.put(KEY_ACCEL_DATA2, dataArray[1]); // Sum of walk count
insertValues.put(KEY_ACCEL_DATA3, dataArray[2]);
insertValues.put(KEY_ACCEL_DATA4, dataArray[3]);
insertValues.put(KEY_ACCEL_DATA5, dataArray[4]);
insertValues.put(KEY_ACCEL_ARG0, 0);
insertValues.put(KEY_ACCEL_ARG1, 0);
insertValues.put(KEY_ACCEL_ARG2, subData);
Logs.d(TAG, "+ Insert activity report : mStartTime="+time+", Year="+year+", Month="+month+", Day="+day+", Hour="+hour);
synchronized (mDb) {
if(mDb == null)
return -1;
return mDb.insertOrThrow(TABLE_NAME_ACCEL_REPORT, null, insertValues);
}
}
public long insertContactGroup(long contactID, long groupID){
ContentValues contentValues = new ContentValues();
contentValues.put(UDBID, contactID);
contentValues.put(GDBID, groupID);
try {
return databaseHelper.getWritableDatabase().insertWithOnConflict(TABLE_NAME, null, contentValues, SQLiteDatabase.CONFLICT_FAIL);
} catch(SQLiteConstraintException ce) {
return -1;
}
}
public long insertActivityReport(int type, long time, int year, int month, int day, int hour, int[] dataArray, String subData) throws SQLiteConstraintException {
if(time < 1 || dataArray == null || dataArray.length < 5)
return -1;
ContentValues insertValues = new ContentValues();
insertValues.put(KEY_ACCEL_TYPE, type);
insertValues.put(KEY_ACCEL_TIME, time);
insertValues.put(KEY_ACCEL_YEAR, year);
insertValues.put(KEY_ACCEL_MONTH, month);
insertValues.put(KEY_ACCEL_DAY, day);
insertValues.put(KEY_ACCEL_HOUR, hour);
insertValues.put(KEY_ACCEL_DATA1, dataArray[0]); // Sum of calorie
insertValues.put(KEY_ACCEL_DATA2, dataArray[1]); // Sum of walk count
insertValues.put(KEY_ACCEL_DATA3, dataArray[2]);
insertValues.put(KEY_ACCEL_DATA4, dataArray[3]);
insertValues.put(KEY_ACCEL_DATA5, dataArray[4]);
insertValues.put(KEY_ACCEL_ARG0, 0);
insertValues.put(KEY_ACCEL_ARG1, 0);
insertValues.put(KEY_ACCEL_ARG2, subData);
Logs.d(TAG, "+ Insert activity report : mStartTime="+time+", Year="+year+", Month="+month+", Day="+day+", Hour="+hour);
synchronized (mDb) {
if(mDb == null)
return -1;
return mDb.insertOrThrow(TABLE_NAME_ACCEL_REPORT, null, insertValues);
}
}
@Override
public long insertWithOnConflict(String table, ContentValues initialValues, int conflictAlgorithm) {
//android DB will thrown an exception rather than return a -1 row ID if there is a failure
// so we catch constraintException and return -1
try {
return this.database.insertWithOnConflict("\""+table+"\"", null,
createAndroidContentValues(initialValues), conflictAlgorithm);
} catch (SQLiteConstraintException sqlce){
return -1;
}
}
public long insertActivityReport(int type, long time, int year, int month, int day, int hour, int[] dataArray, String subData) throws SQLiteConstraintException {
if(time < 1 || dataArray == null || dataArray.length < 5)
return -1;
ContentValues insertValues = new ContentValues();
insertValues.put(KEY_ACCEL_TYPE, type);
insertValues.put(KEY_ACCEL_TIME, time);
insertValues.put(KEY_ACCEL_YEAR, year);
insertValues.put(KEY_ACCEL_MONTH, month);
insertValues.put(KEY_ACCEL_DAY, day);
insertValues.put(KEY_ACCEL_HOUR, hour);
insertValues.put(KEY_ACCEL_DATA1, dataArray[0]); // Sum of calorie
insertValues.put(KEY_ACCEL_DATA2, dataArray[1]); // Sum of walk count
insertValues.put(KEY_ACCEL_DATA3, dataArray[2]);
insertValues.put(KEY_ACCEL_DATA4, dataArray[3]);
insertValues.put(KEY_ACCEL_DATA5, dataArray[4]);
insertValues.put(KEY_ACCEL_ARG0, 0);
insertValues.put(KEY_ACCEL_ARG1, 0);
insertValues.put(KEY_ACCEL_ARG2, subData);
Logs.d(TAG, "+ Insert activity report : mStartTime="+time+", Year="+year+", Month="+month+", Day="+day+", Hour="+hour);
synchronized (mDb) {
if(mDb == null)
return -1;
return mDb.insertOrThrow(TABLE_NAME_ACCEL_REPORT, null, insertValues);
}
}
public long insertFilter(FilterObject filter) throws SQLiteConstraintException
{
if(filter.mType < 0 || filter.mCompareType < 0 || filter.mReplaceType < 0
|| filter.mOriginalString == null || filter.mOriginalString.length() < 1)
return -1;
ContentValues insertValues = new ContentValues();
insertValues.put(KEY_FILTER_TYPE, filter.mType);
insertValues.put(KEY_FILTER_ICON_TYPE, filter.mIconType);
insertValues.put(KEY_FILTER_MATCHING, filter.mCompareType);
insertValues.put(KEY_FILTER_REPLACE_TYPE, filter.mReplaceType);
insertValues.put(KEY_FILTER_ORIGINAL, filter.mOriginalString);
insertValues.put(KEY_FILTER_REPLACE, filter.mReplaceString);
// insertValues.put(KEY_FILTER_ARG0, 0); // for future use
// insertValues.put(KEY_FILTER_ARG1, 0);
// insertValues.put(KEY_FILTER_ARG2, "");
// insertValues.put(KEY_FILTER_ARG3, "");
Logs.d(TAG, "+ Insert filter: type="+filter.mType+", icon="+filter.mIconType
+", compare="+filter.mCompareType+", replace type"+filter.mReplaceType
+", original="+filter.mOriginalString+", replace="+filter.mReplaceString);
synchronized (mDb) {
if(mDb == null)
return -1;
return mDb.insertOrThrow(TABLE_NAME_FILTERS, null, insertValues);
}
}
public long insertFilter(FilterObject filter) throws SQLiteConstraintException
{
if(filter.mType < 0 || filter.mCompareType < 0 || filter.mReplaceType < 0
|| filter.mOriginalString == null || filter.mOriginalString.length() < 1)
return -1;
ContentValues insertValues = new ContentValues();
insertValues.put(KEY_FILTER_TYPE, filter.mType);
insertValues.put(KEY_FILTER_ICON_TYPE, filter.mIconType);
insertValues.put(KEY_FILTER_MATCHING, filter.mCompareType);
insertValues.put(KEY_FILTER_REPLACE_TYPE, filter.mReplaceType);
insertValues.put(KEY_FILTER_ORIGINAL, filter.mOriginalString);
insertValues.put(KEY_FILTER_REPLACE, filter.mReplaceString);
// insertValues.put(KEY_FILTER_ARG0, 0); // for future use
// insertValues.put(KEY_FILTER_ARG1, 0);
// insertValues.put(KEY_FILTER_ARG2, "");
// insertValues.put(KEY_FILTER_ARG3, "");
Logs.d(TAG, "+ Insert filter: type="+filter.mType+", icon="+filter.mIconType
+", compare="+filter.mCompareType+", replace type"+filter.mReplaceType
+", original="+filter.mOriginalString+", replace="+filter.mReplaceString);
synchronized (mDb) {
if(mDb == null)
return -1;
return mDb.insertOrThrow(TABLE_NAME_FILTERS, null, insertValues);
}
}
@NonNull
@Override
public Observable<Pair<String, String>> saveToEnroll(@NonNull String teiType, @NonNull String orgUnit, @NonNull String programUid, @Nullable String teiUid, HashMap<String, String> queryData, Date enrollmentDate) {
Single<String> enrollmentInitial;
if (teiUid == null)
enrollmentInitial = d2.trackedEntityModule().trackedEntityInstances().add(
TrackedEntityInstanceCreateProjection.builder()
.organisationUnit(orgUnit)
.trackedEntityType(teiType)
.build()
);
else
enrollmentInitial = Single.just(teiUid);
return enrollmentInitial.flatMap(uid -> {
if (uid == null) {
String message = String.format(Locale.US, "Failed to insert new tracked entity " +
"instance for organisationUnit=[%s] and trackedEntity=[%s]",
orgUnit, teiType);
return Single.error(new SQLiteConstraintException(message));
} else {
ValueStore valueStore = new ValueStoreImpl(d2, uid, DataEntryStore.EntryMode.ATTR);
if (queryData.containsKey(Constants.ENROLLMENT_DATE_UID))
queryData.remove(Constants.ENROLLMENT_DATE_UID);
for (String key : queryData.keySet()) {
String dataValue = queryData.get(key);
if (dataValue.contains("_os_"))
dataValue = dataValue.split("_os_")[1];
boolean isGenerated = d2.trackedEntityModule().trackedEntityAttributes().uid(key).blockingGet().generated();
if (!isGenerated) {
StoreResult toreResult = valueStore.save(key, dataValue).blockingFirst();
}
}
return Single.just(uid);
}
}
).flatMap(uid ->
d2.enrollmentModule().enrollments().add(
EnrollmentCreateProjection.builder()
.trackedEntityInstance(uid)
.program(programUid)
.organisationUnit(orgUnit)
.build())
.map(enrollmentUid -> {
boolean displayIncidentDate = d2.programModule().programs().uid(programUid).blockingGet().displayIncidentDate();
Date enrollmentDateNoTime = DateUtils.getInstance().getNextPeriod(PeriodType.Daily, enrollmentDate, 0);
d2.enrollmentModule().enrollments().uid(enrollmentUid).setEnrollmentDate(enrollmentDateNoTime);
if (displayIncidentDate) {
d2.enrollmentModule().enrollments().uid(enrollmentUid).setIncidentDate(
DateUtils.getInstance().getToday()
);
}
d2.enrollmentModule().enrollments().uid(enrollmentUid).setFollowUp(false);
return Pair.create(enrollmentUid, uid);
})
).toObservable();
}
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") // for #117
boolean store(SmsMessage sms) {
SmsUdh multi = SmsUdh.from(sms);
if(multi == null || multi.totalParts == 1) {
WtMessage m = new WtMessage(
sms.getOriginatingAddress(),
sms.getMessageBody(),
sms.getTimestampMillis());
return store(m);
} else {
try {
long id = db.insertOrThrow(tblWT_MESSAGE_PART, null, getContentValues(sms, multi));
if(id == -1) return false;
} catch(SQLiteConstraintException ex) {
logException(ex, "Failed to save multipart fragment - it likely already exists in the database.");
return false;
}
Cursor c = null;
db.beginTransaction();
try {
c = db.query(tblWT_MESSAGE_PART,
cols(WMP_clmCONTENT),
eq(WMP_clmFROM, WMP_clmMP_REF),
args(sms.getOriginatingAddress(), multi.multipartRef),
NO_GROUP, NO_GROUP,
SortDirection.ASC.apply(WMP_clmMP_PART));
if(c.getCount() == multi.totalParts) {
StringBuilder bob = new StringBuilder();
while(c.moveToNext()) {
bob.append(c.getString(0));
}
boolean success = store(new WtMessage(sms.getOriginatingAddress(), bob.toString(), multi.sentTimestamp));
if(success) {
rawUpdateOrDelete("DELETE FROM %s WHERE %s=? AND %s=?",
cols(tblWT_MESSAGE_PART, WMP_clmFROM, WMP_clmMP_REF),
args(sms.getOriginatingAddress(), multi.multipartRef));
db.setTransactionSuccessful();
} else {
return false;
}
}
return true;
} finally {
db.endTransaction();
if(c != null) c.close();
}
}
}