Skip to content

Commit

Permalink
JR| Accurate Sync Status
Browse files Browse the repository at this point in the history
Improve the way sync status are determined in PathUpdateActionsTask

Fix for issue #504, #527, #528

Signed-off-by: Jason Rogena <jasonrogena@gmail.com>
  • Loading branch information
jasonrogena committed Jun 8, 2017
1 parent f304237 commit 82bfe71
Show file tree
Hide file tree
Showing 8 changed files with 131 additions and 59 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ public enum FetchStatus implements Displayable, Serializable{
fetchStarted("Update started"),
fetched("Update successful."),
nothingFetched("Already up to date."),
fetchedFailed("Update failed. Please try again.");
fetchedFailed("Update failed. Please try again."),
noConnection("No network connection detected");
private String displayValue;

private FetchStatus(String displayValue) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
import java.util.Calendar;

import util.JsonFormUtils;
import util.NetworkUtils;

/**
* Base activity class for all other PATH activity classes. Implements:
Expand Down Expand Up @@ -152,16 +153,29 @@ public void onClick(View v) {
} else if (fetchStatus.equals(FetchStatus.fetched)
|| fetchStatus.equals(FetchStatus.nothingFetched)) {
syncStatusSnackbar = Snackbar.make(rootView, R.string.sync_complete, Snackbar.LENGTH_LONG);
} else if (fetchStatus.equals(FetchStatus.noConnection)) {
syncStatusSnackbar = Snackbar.make(rootView, R.string.sync_failed_no_internet, Snackbar.LENGTH_LONG);
}
syncStatusSnackbar.show();
}
String lastSync = getLastSyncTime();

if (!TextUtils.isEmpty(lastSync)) {
lastSync = " " + String.format(getString(R.string.last_sync), lastSync);
}
syncMenuItem.setTitle(String.format(getString(R.string.sync_), lastSync));
updateLastSyncText();
}
}
}
}

private void updateLastSyncText() {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null && navigationView.getMenu() != null) {
MenuItem syncMenuItem = navigationView.getMenu().findItem(R.id.nav_sync);
if (syncMenuItem != null) {
String lastSync = getLastSyncTime();

if (!TextUtils.isEmpty(lastSync)) {
lastSync = " " + String.format(getString(R.string.last_sync), lastSync);
}
syncMenuItem.setTitle(String.format(getString(R.string.sync_), lastSync));
}
}
}
Expand Down Expand Up @@ -563,6 +577,9 @@ public BaseActivityToggle(Activity activity, DrawerLayout drawerLayout, Toolbar
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!SyncStatusBroadcastReceiver.getInstance().isSyncing()) {
updateLastSyncText();
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@

import java.util.Calendar;

import util.NetworkUtils;

/**
* Base activity class for path regiters views
* Created by keyman.
Expand Down Expand Up @@ -232,20 +234,33 @@ public void onClick(View v) {
} else if (fetchStatus.equals(FetchStatus.fetched)
|| fetchStatus.equals(FetchStatus.nothingFetched)) {
syncStatusSnackbar = Snackbar.make(rootView, R.string.sync_complete, Snackbar.LENGTH_LONG);
} else if (fetchStatus.equals(FetchStatus.noConnection)) {
syncStatusSnackbar = Snackbar.make(rootView, R.string.sync_failed_no_internet, Snackbar.LENGTH_LONG);
}
syncStatusSnackbar.show();
}
String lastSync = getLastSyncTime();

if (!TextUtils.isEmpty(lastSync)) {
lastSync = " " + String.format(getString(R.string.last_sync), lastSync);
}
syncMenuItem.setTitle(String.format(getString(R.string.sync_), lastSync));
updateLastSyncText();
}
}
}
}

private void updateLastSyncText() {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null && navigationView.getMenu() != null) {
MenuItem syncMenuItem = navigationView.getMenu().findItem(R.id.nav_sync);
if (syncMenuItem != null) {
String lastSync = getLastSyncTime();

if (!TextUtils.isEmpty(lastSync)) {
lastSync = " " + String.format(getString(R.string.last_sync), lastSync);
}
syncMenuItem.setTitle(String.format(getString(R.string.sync_), lastSync));
}
}
}

private String getLastSyncTime() {
String lastSync = "";
long milliseconds = ECSyncUpdater.getInstance(this).getLastCheckTimeStamp();
Expand Down Expand Up @@ -282,6 +297,9 @@ public BaseActivityToggle(Activity activity, DrawerLayout drawerLayout, Toolbar
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!SyncStatusBroadcastReceiver.getInstance().isSyncing()) {
updateLastSyncText();
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import org.ei.opensrp.sync.SyncProgressIndicator;
import org.ei.opensrp.sync.UpdateActionsTask;

import util.NetworkUtils;

import static org.ei.opensrp.util.Log.logInfo;

public class PathSyncBroadcastReceiver extends BroadcastReceiver {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,35 +43,30 @@ public ECSyncUpdater(Context context) {
}


private JSONObject fetchAsJsonObject(String filter, String filterValue) {
try {
HTTPAgent httpAgent = org.ei.opensrp.Context.getInstance().getHttpAgent();
String baseUrl = org.ei.opensrp.Context.getInstance().configuration().dristhiBaseURL();
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf("/"));
}

Long lastSyncDatetime = getLastSyncTimeStamp();
Log.i(ECSyncUpdater.class.getName(), "LAST SYNC DT :" + new DateTime(lastSyncDatetime));
private JSONObject fetchAsJsonObject(String filter, String filterValue) throws Exception {
HTTPAgent httpAgent = org.ei.opensrp.Context.getInstance().getHttpAgent();
String baseUrl = org.ei.opensrp.Context.getInstance().configuration().dristhiBaseURL();
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf("/"));
}

String url = baseUrl + SEARCH_URL + "?" + filter + "=" + filterValue + "&serverVersion=" + lastSyncDatetime;
Log.i(ECSyncUpdater.class.getName(), "URL: " + url);
Long lastSyncDatetime = getLastSyncTimeStamp();
Log.i(ECSyncUpdater.class.getName(), "LAST SYNC DT :" + new DateTime(lastSyncDatetime));

if (httpAgent == null) {
throw new Exception(SEARCH_URL + " http agent is null");
}
String url = baseUrl + SEARCH_URL + "?" + filter + "=" + filterValue + "&serverVersion=" + lastSyncDatetime;
Log.i(ECSyncUpdater.class.getName(), "URL: " + url);

Response resp = httpAgent.fetch(url);
if (resp.isFailure()) {
throw new Exception(SEARCH_URL + " not returned data");
}
if (httpAgent == null) {
throw new Exception(SEARCH_URL + " http agent is null");
}

JSONObject jsonObject = new JSONObject((String) resp.payload());
return jsonObject;
} catch (Exception e) {
Log.e(getClass().getName(), "", e);
return new JSONObject();
Response resp = httpAgent.fetch(url);
if (resp.isFailure()) {
throw new Exception(SEARCH_URL + " not returned data");
}

JSONObject jsonObject = new JSONObject((String) resp.payload());
return jsonObject;
}

public int fetchAllClientsAndEvents(String filterName, String filterValue) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
import java.util.Calendar;
import java.util.Map;

import util.NetworkUtils;

import static org.ei.opensrp.domain.FetchStatus.fetched;
import static org.ei.opensrp.domain.FetchStatus.fetchedFailed;
import static org.ei.opensrp.domain.FetchStatus.nothingFetched;
Expand Down Expand Up @@ -83,46 +85,53 @@ public void updateFromServer(final PathAfterFetchListener pathAfterFetchListener

task.doActionInBackground(new BackgroundAction<FetchStatus>() {
public FetchStatus actionToDoInBackgroundThread() {
if (NetworkUtils.isNetworkAvailable()) {
FetchStatus fetchStatusForForms = sync();
FetchStatus fetchStatusForActions = actionService.fetchNewActions();
pathAfterFetchListener.partialFetch(fetchStatusForActions);

FetchStatus fetchStatusForForms = sync();
FetchStatus fetchStatusForActions = actionService.fetchNewActions();
pathAfterFetchListener.partialFetch(fetchStatusForActions);
startPullUniqueIdsIntentService(context);

startPullUniqueIdsIntentService(context);
startVaccineIntentService(context);
startWeightIntentService(context);
startRecurringIntentService(context);

startVaccineIntentService(context);
startWeightIntentService(context);
startRecurringIntentService(context);
startReplicationIntentService(context);

startReplicationIntentService(context);
startImageUploadIntentService(context);

startImageUploadIntentService(context);

FetchStatus fetchStatusAdditional = additionalSyncService == null ? nothingFetched : additionalSyncService.sync();

FetchStatus fetchStatusAdditional = additionalSyncService == null ? nothingFetched : additionalSyncService.sync();
if (org.ei.opensrp.Context.getInstance().configuration().shouldSyncForm()) {

if (org.ei.opensrp.Context.getInstance().configuration().shouldSyncForm()) {
allFormVersionSyncService.verifyFormsInFolder();
FetchStatus fetchVersionStatus = allFormVersionSyncService.pullFormDefinitionFromServer();
DownloadStatus downloadStatus = allFormVersionSyncService.downloadAllPendingFormFromServer();

allFormVersionSyncService.verifyFormsInFolder();
FetchStatus fetchVersionStatus = allFormVersionSyncService.pullFormDefinitionFromServer();
DownloadStatus downloadStatus = allFormVersionSyncService.downloadAllPendingFormFromServer();
if (downloadStatus == DownloadStatus.downloaded) {
allFormVersionSyncService.unzipAllDownloadedFormFile();
}

if (downloadStatus == DownloadStatus.downloaded) {
allFormVersionSyncService.unzipAllDownloadedFormFile();
if (fetchVersionStatus == fetched || downloadStatus == DownloadStatus.downloaded) {
return fetched;
}
}

if (fetchVersionStatus == fetched || downloadStatus == DownloadStatus.downloaded) {
if (fetchStatusForActions == fetched || fetchStatusForForms == fetched || fetchStatusAdditional == fetched)
return fetched;
}
}

if (fetchStatusForActions == fetched || fetchStatusForForms == fetched || fetchStatusAdditional == fetched)
return fetched;
return fetchStatusForForms;
}

return fetchStatusForForms;
return FetchStatus.noConnection;
}

public void postExecuteInUIThread(FetchStatus result) {
if (result.equals(FetchStatus.nothingFetched) || result.equals(FetchStatus.fetched)) {
ECSyncUpdater ecSyncUpdater = ECSyncUpdater.getInstance(context);
ecSyncUpdater.updateLastCheckTimeStamp(Calendar.getInstance().getTimeInMillis());
}
pathAfterFetchListener.afterFetch(result);
sendSyncStatusBroadcastMessage(context, result);
}
Expand All @@ -138,14 +147,14 @@ private FetchStatus sync() {
// Retrieve database host from preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
AllSharedPreferences allSharedPreferences = new AllSharedPreferences(preferences);
ecUpdater.updateLastCheckTimeStamp(Calendar.getInstance().getTimeInMillis());
while (true) {
long startSyncTimeStamp = ecUpdater.getLastSyncTimeStamp();

int eCount = ecUpdater.fetchAllClientsAndEvents(AllConstants.SyncFilters.FILTER_PROVIDER, allSharedPreferences.fetchRegisteredANM());
totalCount += eCount;

if (eCount == 0 || eCount < 0) {
if (eCount <= 0) {
if (eCount < 0) totalCount = eCount;
break;
}

Expand Down
29 changes: 29 additions & 0 deletions opensrp-path/src/main/java/util/NetworkUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import org.ei.opensrp.path.application.VaccinatorApplication;

/**
* Created by Jason Rogena - jrogena@ona.io on 08/06/2017.
*/

public class NetworkUtils {
private static final String TAG = NetworkUtils.class.getName();
public static boolean isNetworkAvailable() {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) VaccinatorApplication
.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();

} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}

return false;
}
}
1 change: 1 addition & 0 deletions opensrp-path/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -226,5 +226,6 @@
<string name="boys">Boys</string>
<string name="weight_for_age">Weight-for-age %1$s</string>
<string name="previous_weights">PREVIOUS WEIGHTS</string>
<string name="sync_failed_no_internet">Sync failed. Check your internet connection.</string>

</resources>

0 comments on commit 82bfe71

Please sign in to comment.