Search in sources :

Example 26 with Header

use of retrofit2.http.Header 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 27 with Header

use of retrofit2.http.Header 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 28 with Header

use of retrofit2.http.Header in project run-wallet-android by runplay.

the class RunIotaAPICore method postConstruct.

/**
 * added header for IRI
 */
private void postConstruct() {
    boolean USE_AUTH = false;
    // if(host.contains(".runplay.com") || host.contains(".runpg.com"))
    // USE_AUTH=true;
    final String nodeUrl = protocol + "://" + host + ":" + port;
    if (USE_AUTH) {
        // Log.e("IRI-CONNECT","Using Auth OK");
        String creds = Base64.encodeToString((uname + ":" + upassword).getBytes(), false);
        final OkHttpClient.Builder builder = new OkHttpClient.Builder();
        OkHttpClient client = builder.readTimeout(5000, TimeUnit.SECONDS).addInterceptor(new Interceptor() {

            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Request newRequest;
                newRequest = request.newBuilder().addHeader(X_IOTA_API_VERSION_HEADER_NAME, X_IOTA_API_VERSION_HEADER_VALUE).addHeader("Authorization", "Basic " + creds).build();
                return chain.proceed(newRequest);
            }
        }).connectTimeout(5000, TimeUnit.SECONDS).build();
        // use client to create Retrofit service
        final Retrofit retrofit = new Retrofit.Builder().baseUrl(nodeUrl).addConverterFactory(GsonConverterFactory.create()).client(client).build();
        service = retrofit.create(IotaAPIService.class);
    } else {
        // Log.e("IRI-CONNECT","NOOTTTTT Using Auth");
        final OkHttpClient client = new OkHttpClient.Builder().readTimeout(5000, TimeUnit.SECONDS).addNetworkInterceptor(new Interceptor() {

            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                final Buffer buffer = new Buffer();
                chain.request().body().writeTo(buffer);
                return chain.proceed(chain.request());
            }
        }).addInterceptor(new Interceptor() {

            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Request newRequest;
                newRequest = request.newBuilder().addHeader(X_IOTA_API_VERSION_HEADER_NAME, X_IOTA_API_VERSION_HEADER_VALUE).build();
                return chain.proceed(newRequest);
            }
        }).connectTimeout(5000, TimeUnit.SECONDS).build();
        // use client to create Retrofit service
        final Retrofit retrofit = new Retrofit.Builder().baseUrl(nodeUrl).addConverterFactory(GsonConverterFactory.create()).client(client).build();
        service = retrofit.create(IotaAPIService.class);
    }
    // Create OkHttpBuilder
    log.debug("Jota-API Java proxy pointing to node url: '{}'", nodeUrl);
}
Also used : Buffer(okio.Buffer) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Response(retrofit2.Response) Retrofit(retrofit2.Retrofit) Interceptor(okhttp3.Interceptor)

Example 29 with Header

use of retrofit2.http.Header in project Retrofit-Android-Basic by basil2style.

the class ServiceGenerator method createService.

public static <S> S createService(Class<S> serviceClass, final String authToken) {
    if (authToken != null) {
        httpClient.interceptors().add(new Interceptor() {

            @Override
            public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();
                // Request customization: add request headers
                Request.Builder requestBuilder = original.newBuilder().header("Authorization", authToken).method(original.method(), original.body());
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });
    }
    OkHttpClient client = httpClient.build();
    Retrofit retrofit = builder.client(client).build();
    return retrofit.create(serviceClass);
}
Also used : Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor)

Example 30 with Header

use of retrofit2.http.Header in project xDrip-plus by jamorham.

the class NightscoutUploader method doRESTtreatmentDownload.

private synchronized boolean doRESTtreatmentDownload(SharedPreferences prefs) {
    final String baseURLSettings = prefs.getString("cloud_storage_api_base", "");
    final ArrayList<String> baseURIs = new ArrayList<>();
    boolean new_data = false;
    Log.d(TAG, "doRESTtreatmentDownload() starting run");
    try {
        for (String baseURLSetting : baseURLSettings.split(" ")) {
            String baseURL = baseURLSetting.trim();
            if (baseURL.isEmpty())
                continue;
            baseURIs.add(baseURL + (baseURL.endsWith("/") ? "" : "/"));
        }
    } catch (Exception e) {
        Log.e(TAG, "Unable to process API Base URL: " + e);
        return false;
    }
    // process a list of base uris
    for (String baseURI : baseURIs) {
        try {
            baseURI = TryResolveName(baseURI);
            int apiVersion = 0;
            URI uri = new URI(baseURI);
            if ((uri.getHost().startsWith("192.168.")) && prefs.getBoolean("skip_lan_uploads_when_no_lan", true) && (!JoH.isLANConnected())) {
                Log.d(TAG, "Skipping Nighscout download from: " + uri.getHost() + " due to no LAN connection");
                continue;
            }
            if (uri.getPath().endsWith("/v1/"))
                apiVersion = 1;
            String baseURL;
            String secret = uri.getUserInfo();
            if ((secret == null || secret.isEmpty()) && apiVersion == 0) {
                baseURL = baseURI;
            } else if ((secret == null || secret.isEmpty())) {
                throw new Exception("Starting with API v1, a pass phase is required");
            } else if (apiVersion > 0) {
                baseURL = baseURI.replaceFirst("//[^@]+@", "//");
            } else {
                throw new Exception("Unexpected baseURI: " + baseURI);
            }
            final Retrofit retrofit = new Retrofit.Builder().baseUrl(baseURL).client(client).build();
            final NightscoutService nightscoutService = retrofit.create(NightscoutService.class);
            final String checkurl = retrofit.baseUrl().url().toString();
            if (!isNightscoutCompatible(checkurl)) {
                Log.e(TAG, "Nightscout version: " + getNightscoutVersion(checkurl) + " on " + checkurl + " is not compatible with the Rest-API download feature!");
                continue;
            }
            if (apiVersion == 1) {
                final String hashedSecret = Hashing.sha1().hashBytes(secret.getBytes(Charsets.UTF_8)).toString();
                final Response<ResponseBody> r;
                if (hashedSecret != null) {
                    // update status if needed
                    doStatusUpdate(nightscoutService, retrofit.baseUrl().url().toString(), hashedSecret);
                    // per uri marker
                    final String LAST_MODIFIED_KEY = LAST_SUCCESS_TREATMENT_DOWNLOAD + CipherUtils.getMD5(uri.toString());
                    String last_modified_string = PersistentStore.getString(LAST_MODIFIED_KEY);
                    if (last_modified_string.equals(""))
                        last_modified_string = JoH.getRFC822String(0);
                    final long request_start = JoH.tsl();
                    r = nightscoutService.downloadTreatments(hashedSecret, last_modified_string).execute();
                    if ((r != null) && (r.raw().networkResponse().code() == HttpURLConnection.HTTP_NOT_MODIFIED)) {
                        Log.d(TAG, "Treatments on " + uri.getHost() + ":" + uri.getPort() + " not modified since: " + last_modified_string);
                        // skip further processing of this url
                        continue;
                    }
                    if ((r != null) && (r.isSuccessful())) {
                        last_modified_string = r.raw().header("Last-Modified", JoH.getRFC822String(request_start));
                        final String this_etag = r.raw().header("Etag", "");
                        if (this_etag.length() > 0) {
                            // older versions of nightscout don't support if-modified-since so check the etag for duplication
                            if (this_etag.equals(PersistentStore.getString(ETAG + LAST_MODIFIED_KEY))) {
                                Log.d(TAG, "Skipping Treatments on " + uri.getHost() + ":" + uri.getPort() + " due to etag duplicate: " + this_etag);
                                continue;
                            }
                            PersistentStore.setString(ETAG + LAST_MODIFIED_KEY, this_etag);
                        }
                        final String response = r.body().string();
                        if (d)
                            Log.d(TAG, "Response: " + response);
                        new_data = NightscoutTreatments.processTreatmentResponse(response);
                        PersistentStore.setString(LAST_MODIFIED_KEY, last_modified_string);
                        checkGzipSupport(r);
                    } else {
                        Log.d(TAG, "Failed to get treatments from the base URL");
                    }
                } else {
                    Log.d(TAG, "Old api version not supported");
                }
            }
        } catch (Exception e) {
            String msg = "Unable to do REST API Download " + e + e.getMessage();
            handleRestFailure(msg);
        }
    }
    Log.d(TAG, "doRESTtreatmentDownload() finishing run");
    return new_data;
}
Also used : ArrayList(java.util.ArrayList) URI(java.net.URI) MongoClientURI(com.mongodb.MongoClientURI) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ResponseBody(okhttp3.ResponseBody) Retrofit(retrofit2.Retrofit)

Aggregations

Response (retrofit2.Response)39 ServiceResponse (com.microsoft.rest.ServiceResponse)30 TypeToken (com.google.common.reflect.TypeToken)29 Product (fixtures.lro.models.Product)29 Request (okhttp3.Request)23 Retrofit (retrofit2.Retrofit)21 OkHttpClient (okhttp3.OkHttpClient)19 IOException (java.io.IOException)15 Test (org.junit.Test)14 SubProduct (fixtures.lro.models.SubProduct)12 Interceptor (okhttp3.Interceptor)12 Response (okhttp3.Response)10 ResponseBody (okhttp3.ResponseBody)9 Header (retrofit2.http.Header)6 ArrayList (java.util.ArrayList)4 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)4 GsonBuilder (com.google.gson.GsonBuilder)3 HttpException (retrofit2.HttpException)3 Context (android.content.Context)2 Nullable (android.support.annotation.Nullable)2