Search in sources :

Example 21 with HttpException

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;
}
Also used : AuthenticationManager(org.fundacionparaguaya.adviserplatform.data.remote.AuthenticationManager) HttpException(retrofit2.HttpException) Date(java.util.Date) HttpException(retrofit2.HttpException) StopWatch(org.perf4j.StopWatch)

Example 22 with HttpException

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);
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) HttpURLConnection(java.net.HttpURLConnection) AccessToken(com.khmelenko.lab.varis.network.response.AccessToken) AppSettings(com.khmelenko.lab.varis.storage.AppSettings) Arrays(java.util.Arrays) HttpException(retrofit2.HttpException) TextUtils(android.text.TextUtils) Response(retrofit2.Response) MvpPresenter(com.khmelenko.lab.varis.mvp.MvpPresenter) GithubApiService(com.khmelenko.lab.varis.network.retrofit.github.GithubApiService) Single(io.reactivex.Single) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) EncryptionUtils(com.khmelenko.lab.varis.util.EncryptionUtils) Inject(javax.inject.Inject) List(java.util.List) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) TravisRestClient(com.khmelenko.lab.varis.network.retrofit.travis.TravisRestClient) StringUtils(com.khmelenko.lab.varis.util.StringUtils) AuthView(com.khmelenko.lab.varis.view.AuthView) AccessTokenRequest(com.khmelenko.lab.varis.network.request.AccessTokenRequest) AuthorizationRequest(com.khmelenko.lab.varis.network.request.AuthorizationRequest) Schedulers(io.reactivex.schedulers.Schedulers) Authorization(com.khmelenko.lab.varis.network.response.Authorization) GitHubRestClient(com.khmelenko.lab.varis.network.retrofit.github.GitHubRestClient) HttpException(retrofit2.HttpException)

Example 23 with HttpException

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;
}
Also used : Response(retrofit2.Response)

Example 24 with HttpException

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();
}
Also used : Response(retrofit2.Response) Authorization(com.khmelenko.lab.varis.network.response.Authorization) AuthorizationRequest(com.khmelenko.lab.varis.network.request.AuthorizationRequest) AccessToken(com.khmelenko.lab.varis.network.response.AccessToken) AuthorizationRequest(com.khmelenko.lab.varis.network.request.AuthorizationRequest) Request(okhttp3.Request) AccessTokenRequest(com.khmelenko.lab.varis.network.request.AccessTokenRequest) HttpException(retrofit2.HttpException) AccessTokenRequest(com.khmelenko.lab.varis.network.request.AccessTokenRequest) Test(org.junit.Test)

Example 25 with HttpException

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;
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) JSONException(org.json.JSONException) HttpException(retrofit2.HttpException) JsonParseException(com.google.gson.JsonParseException) ParseException(java.text.ParseException) JsonParseException(com.google.gson.JsonParseException) MalformedJsonException(com.google.gson.stream.MalformedJsonException) ConnectException(java.net.ConnectException)

Aggregations

HttpException (retrofit2.HttpException)32 HttpException (retrofit2.adapter.rxjava.HttpException)18 Test (org.junit.Test)14 JSONException (org.json.JSONException)12 Intent (android.content.Intent)11 JsonParseException (com.google.gson.JsonParseException)11 ConnectException (java.net.ConnectException)10 Bundle (android.os.Bundle)9 ParseException (android.net.ParseException)8 IOException (java.io.IOException)7 SocketTimeoutException (java.net.SocketTimeoutException)7 UnknownHostException (java.net.UnknownHostException)7 Response (retrofit2.Response)7 View (android.view.View)6 Build (com.github.vase4kin.teamcityapp.buildlist.api.Build)6 Disposable (io.reactivex.disposables.Disposable)6 List (java.util.List)6 TextView (android.widget.TextView)5 TextUtils (android.text.TextUtils)4 BuildCancelRequest (com.github.vase4kin.teamcityapp.build_details.api.BuildCancelRequest)4