Search in sources :

Example 11 with HttpException

use of com.jakewharton.retrofit2.adapter.rxjava2.HttpException in project dagger-test-example by aschattney.

the class SimpleEspressoTest method viewIsClearedWhenARequestFailed.

@Test
public void viewIsClearedWhenARequestFailed() {
    NavigationController controller = mock(NavigationController.class);
    app().mainActivitySubcomponent().withNavigationController(() -> controller);
    doNothing().when(controller).showErrorIfNotAlreadyShowing(anyString(), anyString());
    final String message = "some exception message";
    when(weatherApi.getCurrentWeather(FAKE_LONGITUDE, FAKE_LATITUDE)).thenReturn(Observable.error(new HttpException(Response.error(500, ResponseBody.create(MediaType.parse("text/plain"), message)))));
    when(weatherApi.getTomorrowWeather(FAKE_LONGITUDE, FAKE_LATITUDE)).thenReturn(Observable.empty());
    rule.launchActivity(null);
    this.allowPermissionsIfNeeded();
    onView(withIndex(withId(R.id.imageView), 0)).check(matches(hasNoDrawable()));
    final int[] ids = new int[] { R.id.cityTextView, R.id.temperatureTextView, R.id.humidityTextView, R.id.descriptionTextView };
    for (int id : ids) {
        onView(withIndex(withId(id), 0)).check(matches(emptyText()));
    }
}
Also used : NavigationController(dagger.extension.example.service.NavigationController) HttpException(retrofit2.HttpException) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.Test)

Example 12 with HttpException

use of com.jakewharton.retrofit2.adapter.rxjava2.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 13 with HttpException

use of com.jakewharton.retrofit2.adapter.rxjava2.HttpException in project Varis-Android by dkhmelenko.

the class BuildsDetailsPresenter method startLoadingLog.

/**
 * Starts loading log file
 *
 * @param jobId Job ID
 */
public void startLoadingLog(long jobId) {
    mJobId = jobId;
    String accessToken = mAppSettings.getAccessToken();
    Single<String> responseSingle;
    if (StringUtils.isEmpty(accessToken)) {
        responseSingle = mRawClient.getApiService().getLog(String.valueOf(mJobId));
    } else {
        String auth = String.format("token %1$s", mAppSettings.getAccessToken());
        responseSingle = mRawClient.getApiService().getLog(auth, String.valueOf(mJobId));
    }
    Disposable subscription = responseSingle.subscribeOn(Schedulers.io()).map(s -> mRawClient.getLogUrl(mJobId)).onErrorResumeNext(new Function<Throwable, SingleSource<String>>() {

        @Override
        public SingleSource<String> apply(@NonNull Throwable throwable) throws Exception {
            String redirectUrl = "";
            if (throwable instanceof HttpException) {
                HttpException httpException = (HttpException) throwable;
                Headers headers = httpException.response().headers();
                for (String header : headers.names()) {
                    if (header.equals("Location")) {
                        redirectUrl = headers.get(header);
                        break;
                    }
                }
                return Single.just(redirectUrl);
            } else {
                return Single.error(throwable);
            }
        }
    }).retry(LOAD_LOG_MAX_ATTEMPT).map(mRawClient::singleStringRequest).map(response -> mLogsParser.parseLog(response.blockingGet())).observeOn(AndroidSchedulers.mainThread()).subscribe((log, throwable) -> {
        if (throwable == null) {
            getView().setLog(log);
        } else {
            getView().showLogError();
            getView().showLoadingError(throwable.getMessage());
        }
    });
    mSubscriptions.add(subscription);
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) Function(io.reactivex.functions.Function) Headers(okhttp3.Headers) NonNull(io.reactivex.annotations.NonNull) HttpException(retrofit2.HttpException)

Example 14 with HttpException

use of com.jakewharton.retrofit2.adapter.rxjava2.HttpException in project DevRing by LJYcoder.

the class ThrowableHandler method fromJson.

/**
 * 从HttpException类型的throwalbe中得到其响应实体并转换为指定格式
 *
 * @param throwable HttpException类型的throwalbe
 * @param clazz     响应实体对应的格式
 */
public static <T> T fromJson(Throwable throwable, Class<T> clazz) {
    HttpException httpException = (HttpException) throwable;
    Gson gson = new Gson();
    T t = null;
    try {
        t = gson.fromJson(httpException.response().errorBody().string(), clazz);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return t;
}
Also used : Gson(com.google.gson.Gson) HttpException(retrofit2.HttpException) IOException(java.io.IOException)

Example 15 with HttpException

use of com.jakewharton.retrofit2.adapter.rxjava2.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)

Aggregations

HttpException (retrofit2.HttpException)29 JSONException (org.json.JSONException)12 JsonParseException (com.google.gson.JsonParseException)11 ConnectException (java.net.ConnectException)10 ParseException (android.net.ParseException)8 SocketTimeoutException (java.net.SocketTimeoutException)7 UnknownHostException (java.net.UnknownHostException)7 Disposable (io.reactivex.disposables.Disposable)6 IOException (java.io.IOException)6 Response (retrofit2.Response)5 TextUtils (android.text.TextUtils)4 CompositeDisposable (io.reactivex.disposables.CompositeDisposable)4 Test (org.junit.Test)4 NonNull (android.support.annotation.NonNull)3 Gson (com.google.gson.Gson)3 AccessTokenRequest (com.khmelenko.lab.varis.network.request.AccessTokenRequest)3 AuthorizationRequest (com.khmelenko.lab.varis.network.request.AuthorizationRequest)3 AccessToken (com.khmelenko.lab.varis.network.response.AccessToken)3 Authorization (com.khmelenko.lab.varis.network.response.Authorization)3 AndroidSchedulers (io.reactivex.android.schedulers.AndroidSchedulers)3