Search in sources :

Example 16 with HttpStatusException

use of org.edx.mobile.http.HttpStatusException in project edx-app-android by openedx.

the class ErrorHandlingCallback method onResponse.

/**
 * The original callback method invoked by Retrofit upon receiving an HTTP response. This method
 * definition provides extra information that's not needed by most individual callback
 * implementations, and is also invoked when HTTP error status codes are encountered (forcing
 * the implementation to manually check for success in each case). Therefore this implementation
 * delegates to {@link #onResponse(Object)} in the case where it receives a successful HTTP
 * status code, and to {@link #onFailure(Call, Throwable)} otherwise, passing an instance of
 * {@link HttpStatusException} with the relevant error status code. This method is
 * declared as final, as subclasses are meant to be implementing the abstract
 * {@link #onResponse(Object)} method instead of this one.
 * <p>
 * This implementation takes care of invoking the callback for request process completion.
 *
 * @param call The Call object that was used to enqueue the request.
 * @param response The HTTP response data.
 */
@Override
public final void onResponse(@NonNull final Call<T> call, @NonNull final Response<T> response) {
    if (!response.isSuccessful()) {
        onFailure(call, new HttpStatusException(response));
    } else {
        if (progressCallback != null) {
            progressCallback.finishProcess();
        }
        onResponse(response.body());
        // Show SnackBar if user is seeing cached content while being offline.
        if (response.raw().networkResponse() == null && !NetworkUtil.isConnected(context)) {
            if (snackbarErrorNotification != null && refreshListener != null) {
                snackbarErrorNotification.showError(R.string.offline_text, R.drawable.ic_wifi, R.string.lbl_reload, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (NetworkUtil.isConnected(context)) {
                            refreshListener.onRefresh();
                            snackbarErrorNotification.hideError();
                        }
                    }
                });
            }
        }
        onFinish();
    }
}
Also used : HttpStatusException(org.edx.mobile.http.HttpStatusException) View(android.view.View)

Example 17 with HttpStatusException

use of org.edx.mobile.http.HttpStatusException in project edx-app-android by openedx.

the class WebViewUtil method loadUrlBasedOnOsVersion.

/**
 * Simply loads a url within a WebView for Marshmallow & above and differently in case of
 * Lollipop & below.<br/>
 * WebViews prior to Marshmallow (API Level 23) don't provide a way to get the HTTP status
 * codes if the url being loaded fails.<br/>
 * This utility function solves this by making a server call using the url provided to query if
 * an error is being return and show error or move on to load the url in WebView, if the server
 * is responding correctly.
 * <p>
 * Inspiration for this solution has been taken from this link:
 * https://stackoverflow.com/questions/11889020/get-http-status-code-in-android-webview/21609608#21609608
 *
 * @param context              Current context.
 * @param webView              The WebView to load the URL into.
 * @param url                  The URL to load.
 * @param viewInterface        WebView's callbacks interface.
 * @param errorNotification    The notification setup for showing/hiding errors.
 * @param okHttpClientProvider The utility to make server calls.
 * @param actionTextResId      The resource ID of the action button text.
 * @param actionListener       The callback to be invoked when the action button is clicked.
 */
public static void loadUrlBasedOnOsVersion(@NonNull final Context context, @NonNull final WebView webView, @NonNull final String url, @NonNull final WebViewStatusListener viewInterface, @NonNull final FullScreenErrorNotification errorNotification, @NonNull OkHttpClientProvider okHttpClientProvider, @StringRes final int actionTextResId, @Nullable final View.OnClickListener actionListener) {
    if (!NetworkUtil.isConnected(context)) {
        errorNotification.showError(context, new IOException(), actionTextResId, actionListener);
    } else {
        errorNotification.hideError();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            viewInterface.showLoadingProgress();
            okHttpClientProvider.get().newCall(new Request.Builder().url(url).get().build()).enqueue(new Callback() {

                @Override
                public void onFailure(Call call, final IOException e) {
                    webView.post((new Runnable() {

                        @Override
                        public void run() {
                            errorNotification.showError(context, e, actionTextResId, actionListener);
                            viewInterface.hideLoadingProgress();
                            viewInterface.clearWebView();
                        }
                    }));
                }

                @Override
                public void onResponse(Call call, final okhttp3.Response response) throws IOException {
                    webView.post(new Runnable() {

                        @Override
                        public void run() {
                            final int responseCode = response.code();
                            if (responseCode >= HttpStatus.BAD_REQUEST) {
                                errorNotification.showError(context, new HttpStatusException(Response.error(responseCode, ResponseBody.create(MediaType.parse("text/plain"), response.message()))), actionTextResId, actionListener);
                                viewInterface.hideLoadingProgress();
                                viewInterface.clearWebView();
                            } else {
                                webView.loadUrl(url);
                            }
                        }
                    });
                }
            });
        } else {
            webView.loadUrl(url);
        }
    }
}
Also used : Call(okhttp3.Call) Callback(okhttp3.Callback) Request(okhttp3.Request) HttpStatusException(org.edx.mobile.http.HttpStatusException) IOException(java.io.IOException)

Example 18 with HttpStatusException

use of org.edx.mobile.http.HttpStatusException in project edx-app-android by edx.

the class WebViewUtil method loadUrlBasedOnOsVersion.

/**
 * Simply loads a url within a WebView for Marshmallow & above and differently in case of
 * Lollipop & below.<br/>
 * WebViews prior to Marshmallow (API Level 23) don't provide a way to get the HTTP status
 * codes if the url being loaded fails.<br/>
 * This utility function solves this by making a server call using the url provided to query if
 * an error is being return and show error or move on to load the url in WebView, if the server
 * is responding correctly.
 * <p>
 * Inspiration for this solution has been taken from this link:
 * https://stackoverflow.com/questions/11889020/get-http-status-code-in-android-webview/21609608#21609608
 *
 * @param context              Current context.
 * @param webView              The WebView to load the URL into.
 * @param url                  The URL to load.
 * @param viewInterface        WebView's callbacks interface.
 * @param errorNotification    The notification setup for showing/hiding errors.
 * @param okHttpClientProvider The utility to make server calls.
 * @param actionTextResId      The resource ID of the action button text.
 * @param actionListener       The callback to be invoked when the action button is clicked.
 */
public static void loadUrlBasedOnOsVersion(@NonNull final Context context, @NonNull final WebView webView, @NonNull final String url, @NonNull final WebViewStatusListener viewInterface, @NonNull final FullScreenErrorNotification errorNotification, @NonNull OkHttpClientProvider okHttpClientProvider, @StringRes final int actionTextResId, @Nullable final View.OnClickListener actionListener) {
    if (!NetworkUtil.isConnected(context)) {
        errorNotification.showError(context, new IOException(), actionTextResId, actionListener);
    } else {
        errorNotification.hideError();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            viewInterface.showLoadingProgress();
            okHttpClientProvider.get().newCall(new Request.Builder().url(url).get().build()).enqueue(new Callback() {

                @Override
                public void onFailure(Call call, final IOException e) {
                    webView.post((new Runnable() {

                        @Override
                        public void run() {
                            errorNotification.showError(context, e, actionTextResId, actionListener);
                            viewInterface.hideLoadingProgress();
                            viewInterface.clearWebView();
                        }
                    }));
                }

                @Override
                public void onResponse(Call call, final okhttp3.Response response) throws IOException {
                    webView.post(new Runnable() {

                        @Override
                        public void run() {
                            final int responseCode = response.code();
                            if (responseCode >= HttpStatus.BAD_REQUEST) {
                                errorNotification.showError(context, new HttpStatusException(Response.error(responseCode, ResponseBody.create(MediaType.parse("text/plain"), response.message()))), actionTextResId, actionListener);
                                viewInterface.hideLoadingProgress();
                                viewInterface.clearWebView();
                            } else {
                                webView.loadUrl(url);
                            }
                        }
                    });
                }
            });
        } else {
            webView.loadUrl(url);
        }
    }
}
Also used : Call(okhttp3.Call) Callback(okhttp3.Callback) Request(okhttp3.Request) HttpStatusException(org.edx.mobile.http.HttpStatusException) IOException(java.io.IOException)

Example 19 with HttpStatusException

use of org.edx.mobile.http.HttpStatusException in project edx-app-android by edx.

the class OauthRefreshTokenAuthenticator method authenticate.

@Override
public synchronized Request authenticate(Route route, final Response response) throws IOException {
    logger.warn(response.toString());
    final AuthResponse currentAuth = loginPrefs.get().getCurrentAuth();
    if (null == currentAuth || null == currentAuth.refresh_token) {
        return null;
    }
    String errorCode = getErrorCode(response.peekBody(200).string());
    if (errorCode != null) {
        switch(errorCode) {
            case TOKEN_EXPIRED_ERROR_MESSAGE:
                final AuthResponse refreshedAuth;
                try {
                    refreshedAuth = refreshAccessToken(currentAuth);
                } catch (HttpStatusException e) {
                    return null;
                }
                return response.request().newBuilder().header("Authorization", refreshedAuth.token_type + " " + refreshedAuth.access_token).build();
            case TOKEN_NONEXISTENT_ERROR_MESSAGE:
            case TOKEN_INVALID_GRANT_ERROR_MESSAGE:
                // one call succeeds but the other fails. https://github.com/edx/edx-app-android/pull/834
                if (!response.request().headers().get("Authorization").split(" ")[1].equals(currentAuth.access_token)) {
                    return response.request().newBuilder().header("Authorization", currentAuth.token_type + " " + currentAuth.access_token).build();
                }
            case DISABLED_USER_ERROR_MESSAGE:
                // If the user is logged-in & marked as disabled then on the next server response
                // app will force the user to logout and navigate it to the launcher screen.
                EventBus.getDefault().post(new LogoutEvent());
                break;
        }
    }
    return null;
}
Also used : LogoutEvent(org.edx.mobile.event.LogoutEvent) HttpStatusException(org.edx.mobile.http.HttpStatusException) AuthResponse(org.edx.mobile.authentication.AuthResponse)

Example 20 with HttpStatusException

use of org.edx.mobile.http.HttpStatusException in project edx-app-android by edx.

the class ErrorHandlingCallback method onResponse.

/**
 * The original callback method invoked by Retrofit upon receiving an HTTP response. This method
 * definition provides extra information that's not needed by most individual callback
 * implementations, and is also invoked when HTTP error status codes are encountered (forcing
 * the implementation to manually check for success in each case). Therefore this implementation
 * delegates to {@link #onResponse(Object)} in the case where it receives a successful HTTP
 * status code, and to {@link #onFailure(Call, Throwable)} otherwise, passing an instance of
 * {@link HttpStatusException} with the relevant error status code. This method is
 * declared as final, as subclasses are meant to be implementing the abstract
 * {@link #onResponse(Object)} method instead of this one.
 * <p>
 * This implementation takes care of invoking the callback for request process completion.
 *
 * @param call The Call object that was used to enqueue the request.
 * @param response The HTTP response data.
 */
@Override
public final void onResponse(@NonNull final Call<T> call, @NonNull final Response<T> response) {
    if (!response.isSuccessful()) {
        onFailure(call, new HttpStatusException(response));
    } else {
        if (progressCallback != null) {
            progressCallback.finishProcess();
        }
        onResponse(response.body());
        // Show SnackBar if user is seeing cached content while being offline.
        if (response.raw().networkResponse() == null && !NetworkUtil.isConnected(context)) {
            if (snackbarErrorNotification != null && refreshListener != null) {
                snackbarErrorNotification.showError(R.string.offline_text, R.drawable.ic_wifi, R.string.lbl_reload, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (NetworkUtil.isConnected(context)) {
                            refreshListener.onRefresh();
                            snackbarErrorNotification.hideError();
                        }
                    }
                });
            }
        }
        onFinish();
    }
}
Also used : HttpStatusException(org.edx.mobile.http.HttpStatusException) View(android.view.View)

Aggregations

HttpStatusException (org.edx.mobile.http.HttpStatusException)21 AuthResponse (org.edx.mobile.authentication.AuthResponse)9 View (android.view.View)8 IOException (java.io.IOException)5 FormFieldMessageBody (org.edx.mobile.model.api.FormFieldMessageBody)5 SocialFactory (org.edx.mobile.social.SocialFactory)5 SuppressLint (android.annotation.SuppressLint)4 NonNull (androidx.annotation.NonNull)4 AndroidEntryPoint (dagger.hilt.android.AndroidEntryPoint)4 LoginTask (org.edx.mobile.authentication.LoginTask)4 LoginErrorMessage (org.edx.mobile.exception.LoginErrorMessage)4 LoginException (org.edx.mobile.exception.LoginException)4 DialogInterface (android.content.DialogInterface)3 Bundle (android.os.Bundle)3 Request (okhttp3.Request)3 Activity (android.app.Activity)2 Intent (android.content.Intent)2 Editable (android.text.Editable)2 TextWatcher (android.text.TextWatcher)2 LinkMovementMethod (android.text.method.LinkMovementMethod)2