Skip to content

Commit

Permalink
MI | Updating Aplication and repository for Gizi #6
Browse files Browse the repository at this point in the history
Signed-off-by: mib-iqbal <[email protected]>
  • Loading branch information
mib-iqbal committed Nov 3, 2017
1 parent cf9a13b commit 6ec46f2
Show file tree
Hide file tree
Showing 3 changed files with 353 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.acra.ACRA;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;
import org.ei.opensrp.gizi.repository.GiziRepository;
import org.smartregister.Context;
import org.smartregister.CoreLibrary;
import org.smartregister.commonregistry.CommonFtsObject;
Expand All @@ -31,32 +32,54 @@ public class GiziApplication extends DrishtiApplication {

@Override
public void onCreate() {

mInstance = this;
context = Context.getInstance();

context.updateApplicationContext(getApplicationContext());

//Initialize Modules
CoreLibrary.init(context);


DrishtiSyncScheduler.setReceiverClass(SyncBroadcastReceiver.class);
super.onCreate();
// ACRA.init(this);

DrishtiSyncScheduler.setReceiverClass(SyncBroadcastReceiver.class);
ErrorReportingFacade.initErrorHandler(getApplicationContext());
// ErrorReportingFacade.initErrorHandler(getApplicationContext());
/**
* ENABLE THIS AGAIN AFTER FINISH TESTING*/
FlurryFacade.init(this);
context = Context.getInstance();
// context = Context.getInstance();
context.updateApplicationContext(getApplicationContext());
context.updateCommonFtsObject(createCommonFtsObject());
applyUserLanguagePreference();
cleanUpSyncState();
}

public static synchronized GiziApplication getInstance() {
return (GiziApplication) mInstance;
}

public Context getContext(){
return context;
}
public Context context() {
return context;
}

@Override
public Repository getRepository() {
try {
if (repository == null) {
repository = new GiziRepository(getInstance().getApplicationContext(), context());

}
} catch (UnsatisfiedLinkError e) {
logError("Error on getRepository: " + e);

}
return repository;
}
@Override
public void logoutCurrentUser(){
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
Expand Down Expand Up @@ -94,18 +117,18 @@ private void updateConfiguration(Configuration config) {
getBaseContext().getResources().getDisplayMetrics());
}

private String[] getFtsSearchFields(String tableName){
private static String[] getFtsSearchFields(String tableName){
if(tableName.equals("ec_anak")){
String[] ftsSearchFields = { "namaBayi","tanggalLahirAnak" };
return ftsSearchFields;
return new String[]{ "namaBayi","tanggalLahirAnak" };
// return ftsSearchFields;
} else if (tableName.equals("ec_kartu_ibu")){
String[] ftsSearchFields = { "namalengkap", "namaSuami" };
return ftsSearchFields;
return new String[]{ "namalengkap", "namaSuami" };
// return ftsSearchFields;
}
return null;
}

private String[] getFtsSortFields(String tableName){
private static String[] getFtsSortFields(String tableName){
if(tableName.equals("ec_anak")){
String[] sortFields = { "namaBayi","tanggalLahirAnak"};
return sortFields;
Expand All @@ -116,7 +139,7 @@ private String[] getFtsSortFields(String tableName){
return null;
}

private String[] getFtsMainConditions(String tableName){
private static String[] getFtsMainConditions(String tableName){
if(tableName.equals("ec_anak")){
String[] mainConditions = {"is_closed", "details" , "namaBayi"};
return mainConditions;
Expand All @@ -126,11 +149,16 @@ private String[] getFtsMainConditions(String tableName){
}
return null;
}
private String[] getFtsTables(){

/* private String[] getFtsTables(){
String[] ftsTables = { "ec_anak", "ec_kartu_ibu" };
return ftsTables;
}*/

private static String[] getFtsTables() {
return new String[]{"ec_anak", "ec_kartu_ibu" };
}
private CommonFtsObject createCommonFtsObject(){
public static CommonFtsObject createCommonFtsObject(){
CommonFtsObject commonFtsObject = new CommonFtsObject(getFtsTables());
for(String ftsTable: commonFtsObject.getTables()){
commonFtsObject.updateSearchFields(ftsTable, getFtsSearchFields(ftsTable));
Expand All @@ -139,4 +167,6 @@ private CommonFtsObject createCommonFtsObject(){
}
return commonFtsObject;
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
package org.ei.opensrp.gizi.repository;

import android.content.Context;
import android.util.Log;

import net.sqlcipher.database.SQLiteDatabase;

import org.apache.commons.lang3.StringUtils;
import org.ei.opensrp.gizi.application.GiziApplication;
import org.smartregister.commonregistry.CommonFtsObject;
import org.smartregister.repository.EventClientRepository;
import org.smartregister.repository.Repository;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import util.GiziConstants;

public class GiziRepository extends Repository {

private static final String TAG = GiziRepository.class.getCanonicalName();
private SQLiteDatabase readableDatabase;
private SQLiteDatabase writableDatabase;
private final Context context;

public GiziRepository(Context context, org.smartregister.Context opensrpContext) {
super(context, GiziConstants.DATABASE_NAME, GiziConstants.DATABASE_VERSION, opensrpContext.session(), GiziApplication.createCommonFtsObject(), opensrpContext.sharedRepositoriesArray());
this.context = context;
}

@Override
public void onCreate(SQLiteDatabase database) {
super.onCreate(database);
EventClientRepository.createTable(database, EventClientRepository.Table.client, EventClientRepository.client_column.values());
EventClientRepository.createTable(database, EventClientRepository.Table.address, EventClientRepository.address_column.values());
EventClientRepository.createTable(database, EventClientRepository.Table.event, EventClientRepository.event_column.values());
EventClientRepository.createTable(database, EventClientRepository.Table.obs, EventClientRepository.obs_column.values());

onUpgrade(database, 1, GiziConstants.DATABASE_VERSION);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(GiziRepository.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");


}




@Override
public SQLiteDatabase getReadableDatabase() {
return getReadableDatabase(GiziApplication.getInstance().getPassword());
}

@Override
public SQLiteDatabase getWritableDatabase() {
return getWritableDatabase(GiziApplication.getInstance().getPassword());
}

@Override
public synchronized SQLiteDatabase getReadableDatabase(String password) {
try {
if (readableDatabase == null || !readableDatabase.isOpen()) {
if (readableDatabase != null) {
readableDatabase.close();
}
readableDatabase = super.getReadableDatabase(password);
}
return readableDatabase;
} catch (Exception e) {
Log.e(TAG, "Database Error. " + e.getMessage());
return null;
}

}

@Override
public synchronized SQLiteDatabase getWritableDatabase(String password) {
if (writableDatabase == null || !writableDatabase.isOpen()) {
if (writableDatabase != null) {
writableDatabase.close();
}
writableDatabase = super.getWritableDatabase(password);
}
return writableDatabase;
}

@Override
public synchronized void close() {
if (readableDatabase != null) {
readableDatabase.close();
}

if (writableDatabase != null) {
writableDatabase.close();
}
super.close();
}

/**
* Version 2 added some columns to the ec_child table
*
* @param database
*/
private void upgradeToVersion2(SQLiteDatabase database) {
try {
// Run insert query
ArrayList<String> newlyAddedFields = new ArrayList<>();
newlyAddedFields.add("BCG_2");
newlyAddedFields.add("inactive");
newlyAddedFields.add("lost_to_follow_up");

addFieldsToFTSTable(database, GiziConstants.CHILD_TABLE_NAME, newlyAddedFields);
} catch (Exception e) {
Log.e(TAG, "upgradeToVersion2 " + Log.getStackTraceString(e));
}
}


private void addFieldsToFTSTable(SQLiteDatabase database, String originalTableName, List<String> newlyAddedFields) {

// Create the new ec_child table

String newTableNameSuffix = "_v2";

Set<String> searchColumns = new LinkedHashSet<>();
searchColumns.add(CommonFtsObject.idColumn);
searchColumns.add(CommonFtsObject.relationalIdColumn);
searchColumns.add(CommonFtsObject.phraseColumn);
searchColumns.add(CommonFtsObject.isClosedColumn);

String[] mainConditions = this.commonFtsObject.getMainConditions(originalTableName);
if (mainConditions != null)
for (String mainCondition : mainConditions) {
if (!mainCondition.equals(CommonFtsObject.isClosedColumnName))
searchColumns.add(mainCondition);
}

String[] sortFields = this.commonFtsObject.getSortFields(originalTableName);
if (sortFields != null) {
for (String sortValue : sortFields) {
if (sortValue.startsWith("alerts.")) {
sortValue = sortValue.split("\\.")[1];
}
searchColumns.add(sortValue);
}
}

String joinedSearchColumns = StringUtils.join(searchColumns, ",");

String searchSql = "create virtual table "
+ CommonFtsObject.searchTableName(originalTableName) + newTableNameSuffix
+ " using fts4 (" + joinedSearchColumns + ");";
Log.d(TAG, "Create query is\n---------------------------\n" + searchSql);

database.execSQL(searchSql);

ArrayList<String> oldFields = new ArrayList<>();

for (String curColumn : searchColumns) {
curColumn = curColumn.trim();
if (curColumn.contains(" ")) {
String[] curColumnParts = curColumn.split(" ");
curColumn = curColumnParts[0];
}

if (!newlyAddedFields.contains(curColumn)) {
oldFields.add(curColumn);
} else {
Log.d(TAG, "Skipping field " + curColumn + " from the select query");
}
}

String insertQuery = "insert into "
+ CommonFtsObject.searchTableName(originalTableName) + newTableNameSuffix
+ " (" + StringUtils.join(oldFields, ", ") + ")"
+ " select " + StringUtils.join(oldFields, ", ") + " from "
+ CommonFtsObject.searchTableName(originalTableName);

Log.d(TAG, "Insert query is\n---------------------------\n" + insertQuery);
database.execSQL(insertQuery);

// Run the drop query
String dropQuery = "drop table " + CommonFtsObject.searchTableName(originalTableName);
Log.d(TAG, "Drop query is\n---------------------------\n" + dropQuery);
database.execSQL(dropQuery);

// Run rename query
String renameQuery = "alter table "
+ CommonFtsObject.searchTableName(originalTableName) + newTableNameSuffix
+ " rename to " + CommonFtsObject.searchTableName(originalTableName);
Log.d(TAG, "Rename query is\n---------------------------\n" + renameQuery);
database.execSQL(renameQuery);

}



}
Loading

0 comments on commit 6ec46f2

Please sign in to comment.