use of retrofit2.HttpException in project ps-advisor-app by wpi-poverty-stoplight.
the class SyncManager method sync.
/**
* Synchronizes the local database with the remote one.
* @return Whether the sync was successful.
*/
public boolean sync(AtomicBoolean isAlive) {
StopWatch watch = new StopWatch("SyncManager:sync");
long lastSyncDate = -1;
watch.start();
if (!isOnline)
return false;
Log.d(TAG, "sync: Synchronizing the database...");
updateProgress(SYNCING);
boolean result = true;
// TODO Sodep: We need to save sync status for each repository individually
// TODO Sodep: _result_ as a single boolean is not enough
BaseRepository[] repositoriesToSync = getBaseRepositories();
for (BaseRepository repo : repositoriesToSync) {
int i = 0;
if (!isAlive.get()) {
return false;
}
repo.setDashActivity(getDashActivity());
try {
// Ensure a valid session is active
if (mAuthenticationManager.isTokenExpired(mPreferences)) {
AuthenticationManager.AuthenticationStatus status = mAuthenticationManager.refreshLogin();
if (!AuthenticationManager.AuthenticationStatus.AUTHENTICATED.equals(status)) {
fallBackToLogin();
}
}
if (repo.needsSync()) {
result = resyncWithOneAuthentication(isAlive, result, repo);
Log.d(TAG, watch.lap(String.format(" Synced: %s", repo.getClass().getSimpleName())));
if (result) {
updateProgress(SYNCED, new Date().getTime());
repo.updateSyncDate();
lastSyncDate = repo.getLastSyncDate();
} else {
Log.d(TAG, String.format("Problem syncing repo %s", repo.getClass().getName()));
repo.clearSyncDate();
lastSyncDate = -1;
}
} else {
lastSyncDate = repo.getLastSyncDate();
updateProgress(SYNCED, lastSyncDate);
setLastSyncDate(lastSyncDate);
result = true;
Log.d(TAG, String.format("Not syncing. Waiting for %s seconds passed %s", SyncJob.SYNC_INTERVAL_MS, new Date(repo.getLastSyncDate())));
}
} catch (HttpException e) {
if (!result) {
Timber.e(TAG, unknownError, e);
stopSyncProcess();
}
} catch (Exception e) {
Log.e(TAG, "sync: Error while syncing!", e);
result = false;
Log.d(TAG, watch.lap(String.format("Error syncing: %s", e.getMessage())));
}
}
Log.d(TAG, watch.stop("Sync completed"));
if (result) {
updateProgress(SYNCED, lastSyncDate);
} else {
updateProgress(ERROR_OTHER);
}
Log.d(TAG, String.format("sync: Finished the synchronization %s.", result ? "successfully" : "with errors"));
return result;
}
use of retrofit2.HttpException in project Varis-Android by dkhmelenko.
the class AuthPresenter method doLogin.
private void doLogin(Single<Authorization> authorizationJob) {
Disposable subscription = authorizationJob.flatMap(this::doAuthorization).doOnSuccess(this::saveAccessToken).doAfterSuccess(accessToken -> cleanUpAfterAuthorization()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe((authorization, throwable) -> {
getView().hideProgress();
if (throwable == null) {
getView().finishView();
} else {
HttpException httpException = (HttpException) throwable;
if (isTwoFactorAuthRequired(httpException)) {
mSecurityCodeInput = true;
getView().showTwoFactorAuth();
} else {
getView().showErrorMessage(throwable.getMessage());
}
}
});
mSubscriptions.add(subscription);
}
use of retrofit2.HttpException in project Varis-Android by dkhmelenko.
the class AuthPresenter method isTwoFactorAuthRequired.
private boolean isTwoFactorAuthRequired(HttpException exception) {
Response response = exception.response();
boolean twoFactorAuthRequired = false;
for (String header : response.headers().names()) {
if (GithubApiService.TWO_FACTOR_HEADER.equals(header)) {
twoFactorAuthRequired = true;
break;
}
}
return response.code() == HttpURLConnection.HTTP_UNAUTHORIZED && twoFactorAuthRequired;
}
use of retrofit2.HttpException in project Varis-Android by dkhmelenko.
the class TestAuthPresenter method testTwoFactorAuth.
@Test
public void testTwoFactorAuth() {
final String login = "login";
final String password = "password";
String auth = EncryptionUtils.generateBasicAuthorization(login, password);
// rules for throwing a request for 2-factor auth
final String expectedUrl = "https://sample.org";
Request rawRequest = new Request.Builder().url(expectedUrl).build();
okhttp3.Response rawResponse = new okhttp3.Response.Builder().request(rawRequest).message("no body").protocol(Protocol.HTTP_1_1).code(401).header(GithubApiService.TWO_FACTOR_HEADER, "required").build();
Response response = Response.error(ResponseBody.create(null, ""), rawResponse);
HttpException exception = new HttpException(response);
when(mGitHubRestClient.getApiService().createNewAuthorization(eq(auth), any(AuthorizationRequest.class))).thenReturn(Single.error(exception));
mAuthPresenter.login(login, password);
verify(mAuthView).showTwoFactorAuth();
// rules for handling 2-factor auth continuation
final String securityCode = "123456";
final String gitHubToken = "gitHubToken";
Authorization authorization = new Authorization();
authorization.setToken(gitHubToken);
authorization.setId(1L);
when(mGitHubRestClient.getApiService().createNewAuthorization(eq(auth), eq(securityCode), any(AuthorizationRequest.class))).thenReturn(Single.just(authorization));
final String accessToken = "token";
AccessTokenRequest request = new AccessTokenRequest();
request.setGithubToken(gitHubToken);
AccessToken token = new AccessToken();
token.setAccessToken(accessToken);
when(mTravisRestClient.getApiService().auth(request)).thenReturn(Single.just(token));
when(mGitHubRestClient.getApiService().deleteAuthorization(auth, String.valueOf(authorization.getId()))).thenReturn(null);
mAuthPresenter.twoFactorAuth(securityCode);
verify(mAuthView, times(2)).hideProgress();
verify(mAuthView).finishView();
}
use of retrofit2.HttpException in project Palm300Heroes by nicolite.
the class ExceptionEngine method handleException.
public static APIException handleException(Throwable throwable) {
throwable.printStackTrace();
APIException apiException;
if (throwable instanceof HttpException) {
HttpException httpException = (HttpException) throwable;
apiException = new APIException(throwable, httpException.code());
apiException.setMsg("网络错误");
return apiException;
} else if (throwable instanceof JsonParseException || throwable instanceof JSONException || throwable instanceof ParseException || throwable instanceof MalformedJsonException) {
apiException = new APIException(throwable, PARSE_SERVER_DATA_ERROR);
apiException.setMsg("解析数据错误");
return apiException;
} else if (throwable instanceof ConnectException) {
apiException = new APIException(throwable, CONNECT_ERROR);
apiException.setMsg("网络连接失败");
return apiException;
} else if (throwable instanceof SocketTimeoutException) {
apiException = new APIException(throwable, CONNECT_TIME_OUT_ERROR);
apiException.setMsg("网络连接超时");
return apiException;
} else if (throwable instanceof ServerException) {
ServerException serverException = (ServerException) throwable;
apiException = new APIException(serverException, serverException.getCode());
apiException.setMsg(serverException.getMsg());
return apiException;
} else {
apiException = new APIException(throwable, UN_KNOWN_ERROR);
apiException.setMsg("未知错误");
return apiException;
}
}
Aggregations