From 6ec46f209fd255fa6e5a830b490d44c28ab6ac6d Mon Sep 17 00:00:00 2001 From: mib-iqbal Date: Fri, 3 Nov 2017 16:54:22 +0800 Subject: [PATCH] MI | Updating Aplication and repository for Gizi #6 Signed-off-by: mib-iqbal --- .../gizi/application/GiziApplication.java | 56 +++-- .../gizi/repository/GiziRepository.java | 206 ++++++++++++++++++ .../src/main/java/util/GiziConstants.java | 104 +++++++++ 3 files changed, 353 insertions(+), 13 deletions(-) create mode 100644 opensrp-gizi/src/main/java/org/ei/opensrp/gizi/repository/GiziRepository.java create mode 100644 opensrp-gizi/src/main/java/util/GiziConstants.java diff --git a/opensrp-gizi/src/main/java/org/ei/opensrp/gizi/application/GiziApplication.java b/opensrp-gizi/src/main/java/org/ei/opensrp/gizi/application/GiziApplication.java index 5ee2641..d0e7026 100644 --- a/opensrp-gizi/src/main/java/org/ei/opensrp/gizi/application/GiziApplication.java +++ b/opensrp-gizi/src/main/java/org/ei/opensrp/gizi/application/GiziApplication.java @@ -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; @@ -31,25 +32,34 @@ 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; } @@ -57,6 +67,19 @@ 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); @@ -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; @@ -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; @@ -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)); @@ -139,4 +167,6 @@ private CommonFtsObject createCommonFtsObject(){ } return commonFtsObject; } + + } diff --git a/opensrp-gizi/src/main/java/org/ei/opensrp/gizi/repository/GiziRepository.java b/opensrp-gizi/src/main/java/org/ei/opensrp/gizi/repository/GiziRepository.java new file mode 100644 index 0000000..6630121 --- /dev/null +++ b/opensrp-gizi/src/main/java/org/ei/opensrp/gizi/repository/GiziRepository.java @@ -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 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 newlyAddedFields) { + + // Create the new ec_child table + + String newTableNameSuffix = "_v2"; + + Set 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 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); + + } + + + +} diff --git a/opensrp-gizi/src/main/java/util/GiziConstants.java b/opensrp-gizi/src/main/java/util/GiziConstants.java new file mode 100644 index 0000000..7b87bcd --- /dev/null +++ b/opensrp-gizi/src/main/java/util/GiziConstants.java @@ -0,0 +1,104 @@ +package util; + +import org.ei.opensrp.gizi.BuildConfig; +import org.smartregister.AllConstants; + +/** + * Created by coder on 2/14/17. + */ +public class +GiziConstants extends AllConstants { + /*public static final int DATABASE_VERSION = BuildConfig.DATABASE_VERSION; + + public static final int OPENMRS_UNIQUE_ID_INITIAL_BATCH_SIZE = BuildConfig.OPENMRS_UNIQUE_ID_INITIAL_BATCH_SIZE; + public static final int OPENMRS_UNIQUE_ID_BATCH_SIZE = BuildConfig.OPENMRS_UNIQUE_ID_BATCH_SIZE; + public static final int OPENMRS_UNIQUE_ID_SOURCE = BuildConfig.OPENMRS_UNIQUE_ID_SOURCE;*/ + public static final long MAX_SERVER_TIME_DIFFERENCE = BuildConfig.MAX_SERVER_TIME_DIFFERENCE; + public static final boolean TIME_CHECK = BuildConfig.TIME_CHECK; + + public static final String CHILD_TABLE_NAME = "ec_child"; + public static final String MOTHER_TABLE_NAME = "ec_mother"; + public static final String CURRENT_LOCATION_ID = "CURRENT_LOCATION_ID"; + + public static final String DEFAULT_DATE_STRING = "1970-1-1"; + + public static final String ID = "id"; + + public static final class ServiceType { + + public static final int DATA_SYNCHRONIZATION = 1; + public static final int DAILY_TALLIES_GENERATION = 2; + public static final int MONTHLY_TALLIES_GENERATION = 3; + public static final int PULL_UNIQUE_IDS = 4; + public static final int VACCINE_SYNC_PROCESSING = 5; + public static final int WEIGHT_SYNC_PROCESSING = 6; + public static final int RECURRING_SERVICES_SYNC_PROCESSING = 7; + public static final int IMAGE_UPLOAD = 8; + } + + public static final class EventType { + + public static final String DEATH = "Death"; + } + + public static final class EntityType { + + public static final String CHILD = "child"; + } + + public static final class EC_CHILD_TABLE { + + public static final String DOD = "dod"; + } + + public static final class GENDER { + + public static final String MALE = "male"; + public static final String FEMALE = "female"; + public static final String TRANSGENDER = "transgender"; + } + + public static final class KEY { + public static final String CHILD = "child"; + public static final String MOTHER_FIRST_NAME = "mother_first_name"; + public static final String FIRST_NAME = "first_name"; + public static final String LAST_NAME = "last_name"; + public static final String BIRTHDATE = "birthdate"; + public static final String DEATHDATE = "deathdate"; + public static final String DEATHDATE_ESTIMATED = "deathdate_estimated"; + public static final String BIRTHDATE_ESTIMATED = "birthdate_estimated"; + public static final String EPI_CARD_NUMBER = "epi_card_number"; + public static final String MOTHER_LAST_NAME = "mother_last_name"; + public static final String ZEIR_ID = "zeir_id"; + public static final String LOST_TO_FOLLOW_UP = "lost_to_follow_up"; + public static final String DOB = "dob"; + public static final String GENDER = "gender"; + public static final String MOTHER_BASE_ENTITY_ID = "mother_base_entity_id"; + public static final String INACTIVE = "inactive"; + public static final String DATE = "date"; + public static final String VACCINE = "vaccine"; + public static final String ALERT = "alert"; + public static final String WEEK = "week"; + public static final String MONTH = "month"; + public static final String DAY = "day"; + public static final String NORMAL = "normal"; + public static final String UPCOMING = "upcoming"; + public static final String URGENT = "urgent"; + public static final String EXPIRED = "expired"; + public static final String PMTCT_STATUS = "pmtct_status"; + public static final String LOCATION_NAME = "location_name"; + public static final String LAST_INTERACTED_WITH = "last_interacted_with"; + public static final String BIRTH_WEIGHT = "Birth_Weight"; + public static final String RELATIONAL_ID = "relational_id"; + public static final String MOTHER = "mother"; + public static final String ENTITY_ID = "entity_id"; + public static final String VALUE = "value"; + public static final String STEPNAME = "stepName"; + public static final String TITLE = "title"; + public static final String ERR = "err"; + public static final String HIA_2_INDICATOR = "hia2_indicator"; + public static final String LOOK_UP = "look_up"; + public static final String NUMBER_PICKER = "number_picker"; + } + +}