Search in sources :

Example 26 with Response

use of retrofit.client.Response in project cw-omnibus by commonsguy.

the class SOTests method fetchQuestions.

@Test(timeout = 30000)
public void fetchQuestions() throws InterruptedException {
    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("https://api.stackexchange.com").build();
    StackOverflowInterface so = restAdapter.create(StackOverflowInterface.class);
    so.questions("android", new Callback<SOQuestions>() {

        @Override
        public void success(SOQuestions soQuestions, Response response) {
            questions = soQuestions;
            responseLatch.countDown();
        }

        @Override
        public void failure(RetrofitError error) {
            responseLatch.countDown();
        }
    });
    responseLatch.await();
    Assert.assertNotNull(questions);
    Assert.assertEquals(30, questions.items.size());
    for (Item item : questions.items) {
        Assert.assertNotNull(item.title);
        Assert.assertNotNull(item.link);
    }
}
Also used : Response(retrofit.client.Response) RestAdapter(retrofit.RestAdapter) RetrofitError(retrofit.RetrofitError) Test(org.junit.Test)

Example 27 with Response

use of retrofit.client.Response in project Varis-Android by dkhmelenko.

the class TestBuildDetailsPresenter method testStartLoadingLogFailed.

@Test
public void testStartLoadingLogFailed() {
    final long jobId = 1L;
    final int errorCode = 401;
    final String errorMsg = "error";
    TaskError error = spy(new TaskError(errorCode, errorMsg));
    Response response = new Response("url", 200, "", Collections.<Header>emptyList(), null);
    error.setResponse(response);
    TaskException exception = spy(new TaskException(error));
    when(mRawClient.getApiService().getLog(String.valueOf(jobId))).thenThrow(exception);
    mBuildsDetailsPresenter.startLoadingLog(jobId);
    int loadLogInvocations = BuildsDetailsPresenter.LOAD_LOG_MAX_ATTEMPT + 1;
    verify(mTaskManager, times(loadLogInvocations)).getLogUrl(jobId);
    verify(mBuildDetailsView).showLoadingError(error.getMessage());
    verify(mBuildDetailsView).showLogError();
}
Also used : Response(retrofit.client.Response) TaskException(com.khmelenko.lab.varis.task.TaskException) TaskError(com.khmelenko.lab.varis.task.TaskError) Test(org.junit.Test)

Example 28 with Response

use of retrofit.client.Response in project Varis-Android by dkhmelenko.

the class TestBuildDetailsPresenter method testStartLoadingDataFailed.

@Test
public void testStartLoadingDataFailed() {
    final long buildId = 1L;
    final String slug = "test";
    final int errorCode = 401;
    final String errorMsg = "error";
    TaskError error = spy(new TaskError(errorCode, errorMsg));
    Response response = new Response("url", 200, "", Collections.<Header>emptyList(), null);
    error.setResponse(response);
    TaskException exception = spy(new TaskException(error));
    when(mTravisRestClient.getApiService().getBuild(slug, buildId)).thenThrow(exception);
    mBuildsDetailsPresenter.startLoadingData(null, slug, buildId);
    verify(mTaskManager).getBuildDetails(slug, buildId);
    verify(mBuildDetailsView).showProgress();
    verify(mBuildDetailsView).hideProgress();
    verify(mBuildDetailsView).updateBuildDetails(null);
    verify(mBuildDetailsView).showLoadingError(error.getMessage());
}
Also used : Response(retrofit.client.Response) TaskException(com.khmelenko.lab.varis.task.TaskException) TaskError(com.khmelenko.lab.varis.task.TaskError) Test(org.junit.Test)

Example 29 with Response

use of retrofit.client.Response in project instructure-android by instructure.

the class CanvasCallback method handleHTTPError.

private void handleHTTPError(RetrofitError retrofitError) {
    Response response = retrofitError.getResponse();
    if (response == null) {
        return;
    }
    Log.e(APIHelpers.LOG_TAG, "Response code: " + response.getStatus());
    Log.e(APIHelpers.LOG_TAG, "Response body: " + response.getBody());
    CanvasError canvasError = null;
    try {
        canvasError = (CanvasError) retrofitError.getBodyAs(CanvasError.class);
    } catch (Exception exception) {
    }
    if (response.getStatus() == 200) {
        errorDelegate.generalError(retrofitError, canvasError, getContext());
    } else if (response.getStatus() == 401) {
        errorDelegate.notAuthorizedError(retrofitError, canvasError, getContext());
    } else if (response.getStatus() >= 400 && response.getStatus() < 500) {
        errorDelegate.invalidUrlError(retrofitError, getContext());
    } else if (response.getStatus() >= 500 && response.getStatus() < 600) {
        // anything there
        if (response.getStatus() == 504 && APIHelpers.isCachedResponse(response)) {
            if (!CanvasRestAdapter.isNetworkAvaliable(getContext())) {
                // Purposely not part of the above if statement. First if statement is prevent the error delegate from a 504 cache response
                // Only call when no items were cached and there isn't a network
                statusDelegate.onNoNetwork();
            }
        // do nothing
        } else {
            errorDelegate.serverError(retrofitError, getContext());
        }
    }
}
Also used : Response(retrofit.client.Response) CanvasError(com.instructure.canvasapi.model.CanvasError)

Example 30 with Response

use of retrofit.client.Response in project instructure-android by instructure.

the class OAuthWebLogin method setupCallback.

public void setupCallback() {
    mobileVerifyCallback = new CanvasCallback<DomainVerificationResult>(APIHelpers.statusDelegateWithContext(OAuthWebLogin.this)) {

        @Override
        public void cache(DomainVerificationResult domainVerificationResult) {
        }

        @Override
        public void firstPage(DomainVerificationResult domainVerificationResult, LinkHeaders linkHeaders, Response response) {
            if (domainVerificationResult.getResult() == DomainVerificationResult.DomainVerificationCode.Success) {
                // Domain is now verified.
                // save domain to the preferences.
                String domain = "";
                // mobile verify can change the hostname we need to use
                if (domainVerificationResult.getBase_url() != null && !domainVerificationResult.getBase_url().equals("")) {
                    domain = domainVerificationResult.getBase_url();
                } else {
                    domain = url;
                }
                // The domain gets set afterwards in SetUpInstance, but domain is required a bit before that works.
                APIHelpers.setDomain(OAuthWebLogin.this, domain);
                client_id = domainVerificationResult.getClient_id();
                client_secret = domainVerificationResult.getClient_secret();
                // Get the protocol
                api_protocol = domainVerificationResult.getProtocol();
                // Set the protocol
                APIHelpers.setProtocol(domainVerificationResult.getProtocol(), OAuthWebLogin.this);
                // Get device name for the login request.
                String deviceName = Build.MODEL;
                if (deviceName == null || deviceName.equals("")) {
                    deviceName = getString(R.string.unknownDevice);
                }
                // Remove spaces
                deviceName = deviceName.replace(" ", "_");
                // changed for the online update to have an actual formatted login page
                authenticationURL = api_protocol + "://" + domain + "/login/oauth2/auth?client_id=" + client_id + "&response_type=code&redirect_uri=urn:ietf:wg:oauth:2.0:oob&mobile=1";
                authenticationURL += "&purpose=" + deviceName;
                if (canvas_login == 1) {
                    authenticationURL += "&canvas_login=1";
                } else if (canvas_login == 2) {
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setCookie(api_protocol + "://" + domain, "canvas_sa_delegated=1");
                }
                web.loadUrl(authenticationURL);
            } else {
                // Error message
                int errorId;
                if (domainVerificationResult.getResult() == DomainVerificationResult.DomainVerificationCode.GeneralError) {
                    errorId = R.string.mobileVerifyGeneral;
                } else if (domainVerificationResult.getResult() == DomainVerificationResult.DomainVerificationCode.DomainNotAuthorized) {
                    errorId = R.string.mobileVerifyDomainUnauthorized;
                } else if (domainVerificationResult.getResult() == DomainVerificationResult.DomainVerificationCode.UnknownUserAgent) {
                    errorId = R.string.mobileVerifyUserAgentUnauthorized;
                } else {
                    errorId = R.string.mobileVerifyUnknownError;
                }
                MaterialDialog.Builder builder = new MaterialDialog.Builder(OAuthWebLogin.this);
                builder.title(R.string.errorOccurred);
                builder.content(errorId);
                builder.cancelable(true);
                builder.positiveColor(Color.BLACK);
                MaterialDialog dialog = builder.build();
                dialog.show();
            }
        }
    };
    getToken = new CanvasCallback<OAuthToken>(APIHelpers.statusDelegateWithContext(OAuthWebLogin.this)) {

        @Override
        public void cache(OAuthToken oAuthToken, LinkHeaders linkHeaders, Response response) {
        }

        @Override
        public void firstPage(OAuthToken oAuthToken, LinkHeaders linkHeaders, Response response) {
            // Set up the rest adapter and such.
            APIHelpers.setToken(getContext(), oAuthToken.getAccess_token());
            CanvasRestAdapter.setupInstance(getContext(), oAuthToken.getAccess_token(), APIHelpers.loadProtocol(getContext()) + "://" + APIHelpers.getDomain(getContext()));
            // save the successful domain to be remembered for later
            JSONArray domains = SavedDomains.getSavedDomains(OAuthWebLogin.this, prefNamePreviousDomain);
            String domain = APIHelpers.getDomain(OAuthWebLogin.this);
            domains.put(domain);
            // save the new domain
            SavedDomains.setSavedDomains(OAuthWebLogin.this, domains, prefNamePreviousDomain);
            // Set the last used domain.
            setLastSignedInDomain(domain, OAuthWebLogin.this);
            // We now need to get the cache user
            UserAPI.getSelf(new UserCallback(APIHelpers.statusDelegateWithContext(OAuthWebLogin.this)) {

                @Override
                public void cachedUser(User user) {
                }

                @Override
                public void user(User user, Response response) {
                    Intent intent = OAuthWebLogin.this.getIntent();
                    intent.putExtra(URLSignIn.loggedInIntent, true);
                    if (passedURI != null) {
                        intent.putExtra(Const.PASSED_URI, passedURI);
                    }
                    OAuthWebLogin.this.setResult(RESULT_OK, intent);
                    OAuthWebLogin.this.finish();
                }
            });
        }

        @Override
        public boolean onFailure(RetrofitError retrofitError) {
            if (!specialCase) {
                Toast.makeText(OAuthWebLogin.this, R.string.errorOccurred, Toast.LENGTH_SHORT).show();
            } else {
                specialCase = false;
            }
            web.loadUrl(authenticationURL);
            return true;
        }
    };
}
Also used : MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) SignedInUser(com.instructure.loginapi.login.model.SignedInUser) User(com.instructure.canvasapi.model.User) LinkHeaders(com.instructure.canvasapi.utilities.LinkHeaders) JSONArray(org.json.JSONArray) Intent(android.content.Intent) DomainVerificationResult(com.instructure.loginapi.login.model.DomainVerificationResult) WebResourceResponse(android.webkit.WebResourceResponse) Response(retrofit.client.Response) OAuthToken(com.instructure.canvasapi.model.OAuthToken) UserCallback(com.instructure.canvasapi.utilities.UserCallback) CookieManager(android.webkit.CookieManager) RetrofitError(retrofit.RetrofitError)

Aggregations

Response (retrofit.client.Response)46 RetrofitError (retrofit.RetrofitError)27 LinkHeaders (com.instructure.canvasapi.utilities.LinkHeaders)8 View (android.view.View)7 TextView (android.widget.TextView)7 ImageView (android.widget.ImageView)6 ArrayList (java.util.ArrayList)5 Callback (retrofit.Callback)5 RestAdapter (retrofit.RestAdapter)5 SharedPreferences (android.content.SharedPreferences)4 User (com.instructure.canvasapi.model.User)4 ClientAuthInterceptor (io.plaidapp.data.api.ClientAuthInterceptor)4 HashMap (java.util.HashMap)4 Intent (android.content.Intent)3 HashSet (java.util.HashSet)3 Test (org.junit.Test)3 ForgetPasswordResponse (org.matrix.androidsdk.rest.model.ForgetPasswordResponse)3 RequestEmailValidationResponse (org.matrix.androidsdk.rest.model.RequestEmailValidationResponse)3 RequestPhoneNumberValidationResponse (org.matrix.androidsdk.rest.model.RequestPhoneNumberValidationResponse)3 TokenRefreshResponse (org.matrix.androidsdk.rest.model.login.TokenRefreshResponse)3