Search in sources :

Example 16 with HttpException

use of retrofit2.HttpException in project RxReddit by damien5314.

the class RedditAuthService method refreshUserAccessToken.

@Override
public Observable<UserAccessToken> refreshUserAccessToken() {
    return Observable.defer(() -> {
        UserAccessToken token = getUserAccessToken();
        if (token == null) {
            return Observable.error(new IllegalStateException("No user access token available"));
        }
        if (token.secondsUntilExpiration() > EXPIRATION_THRESHOLD) {
            return Observable.just(token);
        }
        String refreshToken = token.getRefreshToken();
        if (refreshToken == null) {
            clearUserAccessToken();
            return Observable.error(new IllegalStateException("No refresh token available"));
        }
        String grantType = "refresh_token";
        return authService.refreshUserAuthToken(grantType, refreshToken).flatMap(RxRedditUtil::responseToBody).doOnNext(this::saveUserAccessToken).doOnError(error -> {
            if (error instanceof HttpException && ((HttpException) error).code() == 403) {
                // 403 means our refresh token is no longer good, just discard it
                clearUserAccessToken();
            }
        });
    });
}
Also used : UserAccessToken(rxreddit.model.UserAccessToken) HttpException(retrofit2.HttpException) RxRedditUtil(rxreddit.util.RxRedditUtil)

Example 17 with HttpException

use of retrofit2.HttpException in project bdcodehelper by boredream.

the class LcErrorConstants method parseHttpErrorInfo.

/**
 * 解析服务器错误信息
 */
public static String parseHttpErrorInfo(Throwable throwable) {
    String errorInfo = throwable.getMessage();
    if (throwable instanceof HttpException) {
        // 如果是Retrofit的Http错误,则转换类型,获取信息
        HttpException exception = (HttpException) throwable;
        ResponseBody responseBody = exception.response().errorBody();
        MediaType type = responseBody.contentType();
        // 如果是application/json类型数据,则解析返回内容
        if (type != null && type.type().equals("application") && type.subtype().equals("json")) {
            try {
                // 这里的返回内容是Bmob/AVOS/Parse等RestFul API文档中的错误代码和错误信息对象
                BaseResponse errorResponse = new Gson().fromJson(responseBody.string(), BaseResponse.class);
                errorInfo = getLocalErrorInfo(errorResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else if (throwable instanceof LcErrorResponse) {
        LcErrorResponse lce = (LcErrorResponse) throwable;
        errorInfo = getLocalErrorInfo(lce.getError());
    } else {
        if (throwable instanceof UnknownHostException) {
            errorInfo = "无法连接到服务器";
        }
    }
    return errorInfo;
}
Also used : BaseResponse(com.boredream.bdcodehelper.lean.entity.BaseResponse) UnknownHostException(java.net.UnknownHostException) MediaType(okhttp3.MediaType) Gson(com.google.gson.Gson) HttpException(retrofit2.HttpException) LcErrorResponse(com.boredream.bdcodehelper.lean.entity.LcErrorResponse) HttpException(retrofit2.HttpException) UnknownHostException(java.net.UnknownHostException) ResponseBody(okhttp3.ResponseBody)

Example 18 with HttpException

use of retrofit2.HttpException in project archi by ivacf.

the class MainViewModelTest method shouldSearchInvalidUsername.

@Test
public void shouldSearchInvalidUsername() {
    String username = "invalidUsername";
    TextView textView = new TextView(application);
    textView.setText(username);
    HttpException mockHttpException = new HttpException(Response.error(404, mock(ResponseBody.class)));
    when(githubService.publicRepositories(username)).thenReturn(Observable.<List<Repository>>error(mockHttpException));
    mainViewModel.onSearchAction(textView, EditorInfo.IME_ACTION_SEARCH, null);
    verify(dataListener, never()).onRepositoriesChanged(anyListOf(Repository.class));
    assertEquals(mainViewModel.infoMessage.get(), application.getString(R.string.error_username_not_found));
    assertEquals(mainViewModel.infoMessageVisibility.get(), View.VISIBLE);
    assertEquals(mainViewModel.progressVisibility.get(), View.INVISIBLE);
    assertEquals(mainViewModel.recyclerViewVisibility.get(), View.INVISIBLE);
}
Also used : Repository(uk.ivanc.archimvvm.model.Repository) TextView(android.widget.TextView) HttpException(retrofit2.adapter.rxjava.HttpException) Test(org.junit.Test)

Example 19 with HttpException

use of retrofit2.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 20 with HttpException

use of retrofit2.HttpException in project android-diplicity by zond.

the class UserView method getAvatarClickListener.

public static OnClickListener getAvatarClickListener(final RetrofitActivity retrofitActivity, final Game game, final Member member, final User user) {
    if (game == null) {
        return getAvatarClickListener(retrofitActivity, user);
    }
    Member me = retrofitActivity.getLoggedInMember(game);
    if (me == null || me.Nation.equals(member.Nation)) {
        return getAvatarClickListener(retrofitActivity, user);
    }
    final Member finalMe = me;
    return new OnClickListener() {

        @Override
        public void onClick(View v) {
            retrofitActivity.handleReq(JoinObservable.when(JoinObservable.from(retrofitActivity.userStatsService.UserStatsLoad(user.Id)).and(retrofitActivity.gameStateService.GameStateLoad(game.ID, finalMe.Nation)).and(retrofitActivity.banService.BanLoad(retrofitActivity.getLoggedInUser().Id, user.Id).onErrorReturn(new Func1<Throwable, SingleContainer<Ban>>() {

                @Override
                public SingleContainer<Ban> call(Throwable throwable) {
                    if (throwable instanceof HttpException) {
                        HttpException he = (HttpException) throwable;
                        if (he.code() == 404) {
                            return null;
                        }
                    }
                    throw new RuntimeException(throwable);
                }
            })).then(new Func3<SingleContainer<UserStats>, SingleContainer<GameState>, SingleContainer<Ban>, Object>() {

                @Override
                public Object call(final SingleContainer<UserStats> userStatsSingleContainer, final SingleContainer<GameState> gameStateSingleContainer, final SingleContainer<Ban> banSingleContainer) {
                    AlertDialog dialog = new AlertDialog.Builder(retrofitActivity).setView(R.layout.user_dialog).show();
                    setupUserDialog(retrofitActivity, dialog, userStatsSingleContainer, banSingleContainer);
                    final CheckBox mutedCheckBox = (CheckBox) dialog.findViewById(R.id.muted);
                    mutedCheckBox.setVisibility(VISIBLE);
                    mutedCheckBox.setChecked(gameStateSingleContainer.Properties.Muted != null && gameStateSingleContainer.Properties.Muted.contains(member.Nation));
                    mutedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            if (isChecked && (gameStateSingleContainer.Properties.Muted == null || !gameStateSingleContainer.Properties.Muted.contains(member.Nation))) {
                                if (gameStateSingleContainer.Properties.Muted == null) {
                                    gameStateSingleContainer.Properties.Muted = new ArrayList<String>();
                                }
                                gameStateSingleContainer.Properties.Muted.add(member.Nation);
                            } else if (!isChecked && gameStateSingleContainer.Properties.Muted != null && gameStateSingleContainer.Properties.Muted.contains(member.Nation)) {
                                gameStateSingleContainer.Properties.Muted.remove(member.Nation);
                            }
                            retrofitActivity.handleReq(retrofitActivity.gameStateService.GameStateUpdate(gameStateSingleContainer.Properties, game.ID, finalMe.Nation), new Sendable<SingleContainer<GameState>>() {

                                @Override
                                public void send(SingleContainer<GameState> gameStateSingleContainer) {
                                }
                            }, retrofitActivity.getResources().getString(R.string.updating));
                        }
                    });
                    return null;
                }
            })).toObservable(), new Sendable<Object>() {

                @Override
                public void send(Object o) {
                }
            }, retrofitActivity.getResources().getString(R.string.loading_user_stats));
        }
    };
}
Also used : AlertDialog(android.support.v7.app.AlertDialog) ArrayList(java.util.ArrayList) GameState(se.oort.diplicity.apigen.GameState) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) Ban(se.oort.diplicity.apigen.Ban) SingleContainer(se.oort.diplicity.apigen.SingleContainer) UserStats(se.oort.diplicity.apigen.UserStats) CheckBox(android.widget.CheckBox) HttpException(retrofit2.adapter.rxjava.HttpException) Func1(rx.functions.Func1) Member(se.oort.diplicity.apigen.Member) Func3(rx.functions.Func3) CompoundButton(android.widget.CompoundButton)

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