Search in sources :

Example 11 with HttpException

use of retrofit2.HttpException in project AndroidUtilLib by SiberiaDante.

the class NetException method throwable.

public static ResponseThrowable throwable(Throwable e) {
    ResponseThrowable ex;
    // }
    if (e instanceof HttpException) {
        HttpException httpException = (HttpException) e;
        ex = new ResponseThrowable(e, ERROR.HTTP_ERROR);
        switch(httpException.code()) {
            case REQUEST_TIMEOUT:
            case GATEWAY_TIMEOUT:
                ex.message = "请求超时,请检查网络";
                break;
            case UNAUTHORIZED:
            case FORBIDDEN:
            case NOT_FOUND:
            // 500
            case INTERNAL_SERVER_ERROR:
            case BAD_GATEWAY:
            case SERVICE_UNAVAILABLE:
            case ACCESS_DENIED:
                ex.message = "网络异常";
                break;
            default:
                ex.message = "网络错误";
                break;
        }
        return ex;
    } else if (e instanceof RuntimeException) {
        ex = new ResponseThrowable(e, ERROR.RUNTIME);
        ex.message = "RuntimeException: " + e.getMessage();
        return ex;
    } else if (e instanceof JSONException || e instanceof ParseException) {
        ex = new ResponseThrowable(e, ERROR.PARSE_ERROR);
        ex.message = "解析错误";
        return ex;
    } else if (e instanceof ConnectException) {
        ex = new ResponseThrowable(e, ERROR.NETWORD_ERROR);
        ex.message = "网络连接失败";
        return ex;
    } else if (e instanceof java.security.cert.CertPathValidatorException) {
        ex = new ResponseThrowable(e, ERROR.SSL_NOT_FOUND);
        ex.message = "证书路径没找到";
        return ex;
    } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
        ex = new ResponseThrowable(e, ERROR.SSL_ERROR);
        ex.message = "证书验证失败";
        return ex;
    } else if (e instanceof java.net.SocketTimeoutException) {
        ex = new ResponseThrowable(e, ERROR.TIMEOUT_ERROR);
        ex.message = "连接超时,请稍后重试";
        return ex;
    } else {
        ex = new ResponseThrowable(e, ERROR.UNKNOWN);
        if (!SDNetWorkUtil.isNetWorkConnected()) {
            ex.message = "网络未连接";
        } else if (!SDNetWorkUtil.isAvailableByPing()) {
            ex.message = "网络不可用";
        } else {
            ex.message = "未知错误";
        }
        return ex;
    }
}
Also used : JSONException(org.json.JSONException) HttpException(com.jakewharton.retrofit2.adapter.rxjava2.HttpException) ParseException(android.net.ParseException) ConnectException(java.net.ConnectException)

Example 12 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 13 with HttpException

use of retrofit2.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 retrofit2.HttpException in project talk-android by nextcloud.

the class ContactsController method fetchData.

private void fetchData() {
    dispose(null);
    Set<Sharee> shareeHashSet = new HashSet<>();
    contactItems = new ArrayList<>();
    userHeaderItems = new HashMap<>();
    RetrofitBucket retrofitBucket = ApiUtils.getRetrofitBucketForContactsSearch(userEntity.getBaseUrl(), "");
    contactsQueryDisposable = ncApi.getContactsWithSearchParam(ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken()), retrofitBucket.getUrl(), retrofitBucket.getQueryMap()).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe((ShareesOverall shareesOverall) -> {
        if (shareesOverall != null) {
            if (shareesOverall.getOcs().getData().getUsers() != null) {
                shareeHashSet.addAll(shareesOverall.getOcs().getData().getUsers());
            }
            if (shareesOverall.getOcs().getData().getExactUsers() != null && shareesOverall.getOcs().getData().getExactUsers().getExactSharees() != null) {
                shareeHashSet.addAll(shareesOverall.getOcs().getData().getExactUsers().getExactSharees());
            }
            Participant participant;
            for (Sharee sharee : shareeHashSet) {
                if (!sharee.getValue().getShareWith().equals(userEntity.getUsername())) {
                    participant = new Participant();
                    participant.setName(sharee.getLabel());
                    String headerTitle;
                    headerTitle = sharee.getLabel().substring(0, 1).toUpperCase();
                    UserHeaderItem userHeaderItem;
                    if (!userHeaderItems.containsKey(headerTitle)) {
                        userHeaderItem = new UserHeaderItem(headerTitle);
                        userHeaderItems.put(headerTitle, userHeaderItem);
                    }
                    participant.setUserId(sharee.getValue().getShareWith());
                    contactItems.add(new UserItem(participant, userEntity, userHeaderItems.get(headerTitle)));
                }
            }
            userHeaderItems = new HashMap<>();
            Collections.sort(contactItems, (o1, o2) -> {
                String firstName;
                String secondName;
                if (o1 instanceof UserItem) {
                    firstName = ((UserItem) o1).getModel().getName();
                } else {
                    firstName = ((UserHeaderItem) o1).getModel();
                }
                if (o2 instanceof UserItem) {
                    secondName = ((UserItem) o2).getModel().getName();
                } else {
                    secondName = ((UserHeaderItem) o2).getModel();
                }
                return firstName.compareToIgnoreCase(secondName);
            });
            if (isNewConversationView) {
                contactItems.add(0, new NewCallHeaderItem());
            }
            adapter.updateDataSet(contactItems, true);
            searchItem.setVisible(contactItems.size() > 0);
            swipeRefreshLayout.setRefreshing(false);
            if (isNewConversationView) {
                checkAndHandleBottomButtons();
            }
        }
    }, throwable -> {
        if (searchItem != null) {
            searchItem.setVisible(false);
        }
        if (throwable instanceof HttpException) {
            HttpException exception = (HttpException) throwable;
            switch(exception.code()) {
                case 401:
                    if (getParentController() != null && getParentController().getRouter() != null) {
                        getParentController().getRouter().pushController((RouterTransaction.with(new WebViewLoginController(userEntity.getBaseUrl(), true)).pushChangeHandler(new VerticalChangeHandler()).popChangeHandler(new VerticalChangeHandler())));
                    }
                    break;
                default:
                    break;
            }
        }
        swipeRefreshLayout.setRefreshing(false);
        dispose(contactsQueryDisposable);
    }, () -> {
        swipeRefreshLayout.setRefreshing(false);
        dispose(contactsQueryDisposable);
    });
}
Also used : AutoInjector(autodagger.AutoInjector) Bundle(android.os.Bundle) UserUtils(com.nextcloud.talk.utils.database.user.UserUtils) EntryMenuController(com.nextcloud.talk.controllers.bottomsheet.EntryMenuController) IFlexible(eu.davidea.flexibleadapter.items.IFlexible) SearchView(android.support.v7.widget.SearchView) RetrofitBucket(com.nextcloud.talk.models.RetrofitBucket) UserItem(com.nextcloud.talk.adapters.items.UserItem) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) OnClick(butterknife.OnClick) DividerItemDecoration(android.support.v7.widget.DividerItemDecoration) BindView(butterknife.BindView) ApiUtils(com.nextcloud.talk.utils.ApiUtils) ViewHidingBehaviourAnimation(com.nextcloud.talk.utils.animations.ViewHidingBehaviourAnimation) BottomSheet(com.kennyc.bottomsheet.BottomSheet) Handler(android.os.Handler) View(android.view.View) Button(android.widget.Button) UserHeaderItem(com.nextcloud.talk.adapters.items.UserHeaderItem) Schedulers(io.reactivex.schedulers.Schedulers) Sharee(com.nextcloud.talk.models.json.sharees.Sharee) SelectableAdapter(eu.davidea.flexibleadapter.SelectableAdapter) VerticalChangeHandler(com.bluelinelabs.conductor.changehandler.VerticalChangeHandler) Participant(com.nextcloud.talk.models.json.participants.Participant) MenuItemCompat(android.support.v4.view.MenuItemCompat) Optional(butterknife.Optional) HttpException(retrofit2.HttpException) InputType(android.text.InputType) Set(java.util.Set) FlexibleAdapter(eu.davidea.flexibleadapter.FlexibleAdapter) ThreadMode(org.greenrobot.eventbus.ThreadMode) ViewGroup(android.view.ViewGroup) BundleKeys(com.nextcloud.talk.utils.bundle.BundleKeys) List(java.util.List) Disposable(io.reactivex.disposables.Disposable) Parcels(org.parceler.Parcels) FastScroller(eu.davidea.fastscroller.FastScroller) AbstractFlexibleItem(eu.davidea.flexibleadapter.items.AbstractFlexibleItem) Nullable(android.support.annotation.Nullable) SearchManager(android.app.SearchManager) EditorInfo(android.view.inputmethod.EditorInfo) Context(android.content.Context) CoordinatorLayout(android.support.design.widget.CoordinatorLayout) UserEntity(com.nextcloud.talk.models.database.UserEntity) SmoothScrollLinearLayoutManager(eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager) Intent(android.content.Intent) HashMap(java.util.HashMap) NonNull(android.support.annotation.NonNull) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) BottomSheetLockEvent(com.nextcloud.talk.events.BottomSheetLockEvent) HashSet(java.util.HashSet) Inject(javax.inject.Inject) BaseController(com.nextcloud.talk.controllers.base.BaseController) MenuInflater(android.view.MenuInflater) EventBus(org.greenrobot.eventbus.EventBus) Menu(android.view.Menu) SwipeRefreshLayout(android.support.v4.widget.SwipeRefreshLayout) NcApi(com.nextcloud.talk.api.NcApi) BottomNavigationView(android.support.design.widget.BottomNavigationView) R(com.nextcloud.talk.R) Room(com.nextcloud.talk.models.json.rooms.Room) LayoutInflater(android.view.LayoutInflater) NewCallHeaderItem(com.nextcloud.talk.adapters.items.NewCallHeaderItem) TextUtils(android.text.TextUtils) FlipView(eu.davidea.flipview.FlipView) ShareesOverall(com.nextcloud.talk.models.json.sharees.ShareesOverall) HorizontalChangeHandler(com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler) RecyclerView(android.support.v7.widget.RecyclerView) Subscribe(org.greenrobot.eventbus.Subscribe) KeyboardUtils(com.nextcloud.talk.utils.KeyboardUtils) CallActivity(com.nextcloud.talk.activities.CallActivity) Observer(io.reactivex.Observer) ViewTreeObserver(android.view.ViewTreeObserver) RoomOverall(com.nextcloud.talk.models.json.rooms.RoomOverall) Collections(java.util.Collections) NextcloudTalkApplication(com.nextcloud.talk.application.NextcloudTalkApplication) RouterTransaction(com.bluelinelabs.conductor.RouterTransaction) RetrofitBucket(com.nextcloud.talk.models.RetrofitBucket) HashMap(java.util.HashMap) NewCallHeaderItem(com.nextcloud.talk.adapters.items.NewCallHeaderItem) VerticalChangeHandler(com.bluelinelabs.conductor.changehandler.VerticalChangeHandler) UserItem(com.nextcloud.talk.adapters.items.UserItem) Sharee(com.nextcloud.talk.models.json.sharees.Sharee) UserHeaderItem(com.nextcloud.talk.adapters.items.UserHeaderItem) Participant(com.nextcloud.talk.models.json.participants.Participant) ShareesOverall(com.nextcloud.talk.models.json.sharees.ShareesOverall) HttpException(retrofit2.HttpException) HashSet(java.util.HashSet)

Example 15 with HttpException

use of retrofit2.HttpException in project BaseProject by wareine.

the class ExceptionHandle method handleException.

public static ResponseException handleException(Throwable e) {
    ResponseException ex;
    if (e instanceof HttpException) {
        HttpException httpException = (HttpException) e;
        ex = new ResponseException(e, ERROR.HTTP_ERROR);
        switch(httpException.code()) {
            case UNAUTHORIZED:
            case FORBIDDEN:
            case NOT_FOUND:
            case REQUEST_TIMEOUT:
            case GATEWAY_TIMEOUT:
            case INTERNAL_SERVER_ERROR:
            case BAD_GATEWAY:
            case SERVICE_UNAVAILABLE:
            default:
                ex.message = "网络错误";
                break;
        }
        return ex;
    } else if (e instanceof ServerException) {
        ServerException resultException = (ServerException) e;
        ex = new ResponseException(resultException, resultException.code);
        ex.message = resultException.message;
        return ex;
    } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {
        ex = new ResponseException(e, ERROR.PARSE_ERROR);
        ex.message = "解析错误";
        return ex;
    } else if (e instanceof ConnectException) {
        ex = new ResponseException(e, ERROR.NETWORD_ERROR);
        ex.message = "连接失败";
        return ex;
    } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
        ex = new ResponseException(e, ERROR.SSL_ERROR);
        ex.message = "证书验证失败";
        return ex;
    } else if (e instanceof ConnectTimeoutException) {
        ex = new ResponseException(e, ERROR.TIMEOUT_ERROR);
        ex.message = "连接超时";
        return ex;
    } else if (e instanceof java.net.SocketTimeoutException) {
        ex = new ResponseException(e, ERROR.TIMEOUT_ERROR);
        ex.message = "连接超时";
        return ex;
    } else {
        ex = new ResponseException(e, ERROR.UNKNOWN);
        ex.message = "未知错误";
        return ex;
    }
}
Also used : JSONException(org.json.JSONException) HttpException(retrofit2.HttpException) JsonParseException(com.google.gson.JsonParseException) ParseException(android.net.ParseException) JsonParseException(com.google.gson.JsonParseException) ConnectException(java.net.ConnectException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

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