Skip to content

Commit

Permalink
Code clean up/Refactor
Browse files Browse the repository at this point in the history
Refactor unit tests
Merge branch 'master' into migrate-crashlytics
  • Loading branch information
ndegwamartin committed Sep 20, 2022
2 parents 9b385bf + a9b06f4 commit aea5366
Show file tree
Hide file tree
Showing 16 changed files with 268 additions and 93 deletions.
2 changes: 1 addition & 1 deletion opensrp-core/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ dependencies {
testRuntimeOnly platform('com.google.firebase:firebase-bom:30.0.2')
testRuntimeOnly 'com.google.firebase:firebase-crashlytics'
// Add the dependency for the Performance Monitoring library
testRuntimeOnly 'com.google.firebase:firebase-perf'
testImplementation 'com.google.firebase:firebase-perf'

// PowerMock
def powerMockVersion = '2.0.9'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public Bundle getAuthToken(AccountAuthenticatorResponse response, Account accoun
accountManager.setAuthToken(account, authTokenType, authToken);
accountManager.setUserData(account, AccountHelper.INTENT_KEY.ACCOUNT_ACCESS_TOKEN_EXPIRES_IN, Utils.toStringNullable(accountResponse.getExpiresIn()));
accountManager.setUserData(account, AccountHelper.INTENT_KEY.ACCOUNT_REFRESH_TOKEN_EXPIRES_IN, Utils.toStringNullable(accountResponse.getRefreshExpiresIn()));
accountManager.setUserData(account, AccountHelper.INTENT_KEY.ACCOUNT_ACCESS_TOKEN_CREATED_AT, Utils.toStringNullable(Calendar.getInstance().getTimeInMillis()));
accountManager.setUserData(account, AccountHelper.INTENT_KEY.ACCOUNT_REFRESH_TOKEN_CREATED_AT, Utils.toStringNullable(Calendar.getInstance().getTimeInMillis()));

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
accountManager.notifyAccountAuthenticated(account);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,11 @@ public static AccountManagerFuture<Bundle> reAuthenticateUserAfterSessionExpired
}

/**
* A Helper method to check if the Access Token is valid
* A Helper method to check if the Refresh Token is valid.
* Note: We only need to manually enter credentials if the Refresh Token is expired
*/
public static boolean isAccessTokenValid(String accountName, String accountType) {
String createdAt = getAccountManagerValue(INTENT_KEY.ACCOUNT_ACCESS_TOKEN_CREATED_AT, accountName, accountType);
public static boolean isRefreshTokenValid(String accountName, String accountType) {
String createdAt = getAccountManagerValue(INTENT_KEY.ACCOUNT_REFRESH_TOKEN_CREATED_AT, accountName, accountType);
String accountExpires = getAccountManagerValue(INTENT_KEY.ACCOUNT_REFRESH_TOKEN_EXPIRES_IN, accountName, accountType);
Long createdAtLong = createdAt != null ? Long.parseLong(createdAt) : null;
Long accountExpiresLong = accountExpires != null ? Long.parseLong(accountExpires) : null;
Expand Down Expand Up @@ -166,7 +167,7 @@ public static final class INTENT_KEY {
public final static String ACCOUNT_ROLES = "ACCOUNT_ROLES";
public final static String ACCOUNT_REFRESH_TOKEN_EXPIRES_IN = "ACCOUNT_REFRESH_TOKEN_EXPIRES_IN";
public final static String ACCOUNT_ACCESS_TOKEN_EXPIRES_IN = "ACCOUNT_ACCESS_TOKEN_EXPIRES_IN";
public final static String ACCOUNT_ACCESS_TOKEN_CREATED_AT = "ACCOUNT_ACCESS_TOKEN_CREATED_AT";
public final static String ACCOUNT_REFRESH_TOKEN_CREATED_AT = "ACCOUNT_ACCESS_TOKEN_CREATED_AT";
}

public static final class TOKEN_TYPE {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package org.smartregister.cursoradapter;

import static android.os.Looper.getMainLooper;

import android.database.Cursor;
import android.os.Handler;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.ViewGroup;

import org.smartregister.commonregistry.CommonPersonObject;
import org.smartregister.commonregistry.CommonPersonObjectClient;
Expand Down Expand Up @@ -42,7 +46,10 @@ public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, Cursor cursor) {
if (listItemProvider.isFooterViewHolder(viewHolder)) {
listItemProvider.getFooterView(viewHolder, getCurrentPageCount(), getTotalPageCount(), hasNextPage(), hasPreviousPage());
// make sure counts are updated before updating the view
(new Handler(getMainLooper())).post(() -> {
listItemProvider.getFooterView(viewHolder, getCurrentPageCount(), getTotalPageCount(), hasNextPage(), hasPreviousPage());
});
} else {
CommonPersonObject personinlist = commonRepository.readAllcommonforCursorAdapter(cursor);
CommonPersonObjectClient pClient = new CommonPersonObjectClient(personinlist.getCaseId(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public abstract class BaseLoginInteractor implements BaseLoginContract.Interacto
private static final int MINIMUM_JOB_FLEX_VALUE = 5;
private BaseLoginContract.Presenter mLoginPresenter;
private RemoteLoginTask remoteLoginTask;
private boolean localLogin;
private boolean isLocalLogin;

private ResetAppHelper resetAppHelper;

Expand All @@ -77,23 +77,22 @@ public void login(WeakReference<BaseLoginContract.View> view, String userName, c
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> {

localLogin = !getSharedPreferences().fetchForceRemoteLogin(userName);
isLocalLogin = !getSharedPreferences().fetchForceRemoteLogin(userName);
org.smartregister.Context opensrpContext = CoreLibrary.getInstance().context();
if ((NetworkUtils.isNetworkAvailable() && isAuthTokenExpired(userName)) || (opensrpContext.getAppProperties().getPropertyBoolean(AllConstants.PROPERTY.ALLOW_OFFLINE_LOGIN_WITH_INVALID_TOKEN)
&& localLogin
&& HttpURLConnection.HTTP_UNAUTHORIZED == getSharedPreferences().getLastAuthenticationHttpStatus()
&& NetworkUtils.isNetworkAvailable())) {
localLogin = false;
if (NetworkUtils.isNetworkAvailable() && (isRefreshTokenExpired(userName) || (opensrpContext.getAppProperties().getPropertyBoolean(AllConstants.PROPERTY.ALLOW_OFFLINE_LOGIN_WITH_INVALID_TOKEN)
&& isLocalLogin
&& HttpURLConnection.HTTP_UNAUTHORIZED == getSharedPreferences().getLastAuthenticationHttpStatus()))) {
isLocalLogin = false;
}

getLoginView().getAppCompatActivity().runOnUiThread(() -> loginWithLocalFlag(view, localLogin && getSharedPreferences().isRegisteredANM(userName), userName, password));
getLoginView().getAppCompatActivity().runOnUiThread(() -> loginWithLocalFlag(view, isLocalLogin && getSharedPreferences().isRegisteredANM(userName), userName, password));

});
}

@VisibleForTesting
protected boolean isAuthTokenExpired(String userName) {
return !AccountHelper.isAccessTokenValid(userName, CoreLibrary.getInstance().getAccountAuthenticatorXml().getAccountType());
protected boolean isRefreshTokenExpired(String userName) {
return !AccountHelper.isRefreshTokenValid(userName, CoreLibrary.getInstance().getAccountAuthenticatorXml().getAccountType());
}

public void loginWithLocalFlag(WeakReference<BaseLoginContract.View> view, boolean localLogin, String userName, char[] password) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public boolean isCancelled() {

public void cancel(boolean cancelled) {
this.cancelled = cancelled;
mLoginView.showProgress(false);
mLoginView.showProgress(!cancelled);
}

public void execute() {
Expand Down Expand Up @@ -162,7 +162,7 @@ protected LoginResponse doInBackground() {
mAccountManager.setUserData(account, AccountHelper.INTENT_KEY.ACCOUNT_NAME, userData.getString(AccountHelper.INTENT_KEY.ACCOUNT_NAME));
mAccountManager.setUserData(account, AccountHelper.INTENT_KEY.ACCOUNT_REFRESH_TOKEN, response.getRefreshToken());
mAccountManager.setUserData(account, AccountHelper.INTENT_KEY.ACCOUNT_ACCESS_TOKEN_EXPIRES_IN, Utils.toStringNullable(response.getExpiresIn()));
mAccountManager.setUserData(account, AccountHelper.INTENT_KEY.ACCOUNT_ACCESS_TOKEN_CREATED_AT, Utils.toStringNullable(Calendar.getInstance().getTimeInMillis()));
mAccountManager.setUserData(account, AccountHelper.INTENT_KEY.ACCOUNT_REFRESH_TOKEN_CREATED_AT, Utils.toStringNullable(Calendar.getInstance().getTimeInMillis()));
mAccountManager.setUserData(account, AccountHelper.INTENT_KEY.ACCOUNT_REFRESH_TOKEN_EXPIRES_IN, Utils.toStringNullable(response.getRefreshExpiresIn()));
mAccountManager.setUserData(account, AccountHelper.INTENT_KEY.ACCOUNT_ROLES, user.getRoles() != null ? user.getRoles().toString() : Collections.EMPTY_LIST.toString());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

package org.smartregister.repository;

import static org.smartregister.AllConstants.ROWID;

import android.content.ContentValues;
import android.database.Cursor;
import android.text.TextUtils;
Expand Down Expand Up @@ -52,8 +54,6 @@

import timber.log.Timber;

import static org.smartregister.AllConstants.ROWID;

/**
* Created by keyman on 27/07/2017.
*/
Expand Down Expand Up @@ -354,12 +354,13 @@ public Boolean checkIfExistsByFormSubmissionId(Table table, String
return false;
}

private boolean populateStatement(SQLiteStatement statement, Table table, JSONObject
jsonObject, Map<String, Integer> columnOrder) {
private boolean populateStatement(SQLiteStatement statement, Table table, JSONObject jsonObject, Map<String, Integer> columnOrder) {
if (statement == null)
return false;

statement.clearBindings();
List columns;

try {
if (table.equals(clientTable)) {
columns = Arrays.asList(client_column.values());
Expand All @@ -373,10 +374,24 @@ private boolean populateStatement(SQLiteStatement statement, Table table, JSONOb

List<? extends Column> otherColumns = new ArrayList(columns);
if (!otherColumns.isEmpty()) {
otherColumns.removeAll(Arrays.asList(client_column.json, client_column.updatedAt, client_column.syncStatus, client_column.validationStatus, client_column.baseEntityId,
client_column.residence, client_column.locationId, client_column.clientType,
event_column.json, event_column.updatedAt, event_column.syncStatus, event_column.validationStatus, event_column.baseEntityId, event_column.eventId
, event_column.planId, event_column.taskId));
otherColumns.removeAll(Arrays.asList(
client_column.json,
client_column.updatedAt,
client_column.syncStatus,
client_column.validationStatus,
client_column.baseEntityId,
client_column.residence,
client_column.locationId,
client_column.clientType,
event_column.json,
event_column.updatedAt,
event_column.syncStatus,
event_column.validationStatus,
event_column.baseEntityId,
event_column.eventId,
event_column.planId,
event_column.taskId
));
}

for (Column column : otherColumns) {
Expand Down Expand Up @@ -2142,32 +2157,39 @@ public void markEventAsTaskUnprocessed(String formSubmissionId) {
}
}

public void markEventsAsSynced(Map<String, Object> syncedEventsClients) {
markEventsAsSynced(syncedEventsClients, null, null);
}

@SuppressWarnings("unchecked")
public void markEventsAsSynced(Map<String, Object> syncedEvents) {
public void markEventsAsSynced(Map<String, Object> syncedEventsClients, Set<String> failedEvents, Set<String> failedClients) {
try {
List<JSONObject> clients =
syncedEvents.containsKey(AllConstants.KEY.CLIENTS) ? (List<JSONObject>) syncedEvents.get(
AllConstants.KEY.CLIENTS) : null;
List<JSONObject> events =
syncedEvents.containsKey(AllConstants.KEY.EVENTS) ? (List<JSONObject>) syncedEvents.get(
AllConstants.KEY.EVENTS) : null;
List<JSONObject> clients = syncedEventsClients.containsKey(AllConstants.KEY.CLIENTS)
? (List<JSONObject>) syncedEventsClients.get(AllConstants.KEY.CLIENTS)
: null;

List<JSONObject> events = syncedEventsClients.containsKey(AllConstants.KEY.EVENTS)
? (List<JSONObject>) syncedEventsClients.get(AllConstants.KEY.EVENTS)
: null;

if (clients != null && !clients.isEmpty()) {
for (JSONObject client : clients) {
String baseEntityId = client.getString(client_column.baseEntityId.name());
markClientAsSynced(baseEntityId);
if (failedClients == null || !failedClients.contains(baseEntityId))
markClientAsSynced(baseEntityId);
}
}

if (events != null && !events.isEmpty()) {
for (JSONObject event : events) {
String formSubmissionId = event.getString(event_column.formSubmissionId.name());
markEventAsSynced(formSubmissionId);
if (failedEvents == null || !failedEvents.contains(formSubmissionId))
markEventAsSynced(formSubmissionId);
}
}
} catch (Exception e) {
Timber.e(e);
}

}

protected List<Client> fetchClients(String query, String[] params) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

Expand Down Expand Up @@ -672,12 +673,21 @@ public AccountResponse oauth2authenticateCore(StringBuffer requestParamBuffer, S
}

public AccountResponse oauth2authenticate(String username, char[] password, String grantType, String tokenEndpointURL) {
StringBuffer requestParamBuilder = getRequestParams(username, password);
return oauth2authenticateCore(requestParamBuilder, grantType, tokenEndpointURL);
}

private StringBuffer getRequestParams(String username, char[] password) {
StringBuffer requestParamBuilder = new StringBuffer();
requestParamBuilder.append("&username=").append(username);
requestParamBuilder.append("&password=").append(password);

return oauth2authenticateCore(requestParamBuilder, grantType, tokenEndpointURL);
String urlEncodedPassword = new String(password);
try {
urlEncodedPassword = URLEncoder.encode(urlEncodedPassword, "utf-8");
} catch (UnsupportedEncodingException e) {
Timber.e(e);
}
requestParamBuilder.append("&password=").append(urlEncodedPassword);
return requestParamBuilder;
}

public AccountResponse oauth2authenticateRefreshToken(String refreshToken) {
Expand Down
Loading

0 comments on commit aea5366

Please sign in to comment.