Example usage for com.squareup.okhttp Credentials basic

List of usage examples for com.squareup.okhttp Credentials basic

Introduction

In this page you can find the example usage for com.squareup.okhttp Credentials basic.

Prototype

public static String basic(String userName, String password) 

Source Link

Document

Returns an auth credential for the Basic scheme.

Usage

From source file:io.morea.handy.android.EventReporterTest.java

License:Apache License

@Test
public void eventsSentToRemoteServer() throws Exception {
    server.enqueue(new MockResponse().setResponseCode(401));
    server.enqueue(new MockResponse().setResponseCode(201));
    server.enqueue(new MockResponse().setResponseCode(401));
    server.enqueue(new MockResponse().setResponseCode(500));
    server.enqueue(new MockResponse().setResponseCode(401));
    server.enqueue(new MockResponse().setResponseCode(201));
    server.start();//  w  ww .  j  a va 2s .com

    EventReporterConfiguration configuration = new EventReporterConfiguration.Builder(server.getUrl("/"))
            .probeId(probeId.toString()).accessKey(accessKey.toString()).syncBatchSize(2).build();

    EventReporter reporter = new EventReporter(application, configuration, new SynchronousExecutorService());

    reporter.log(fiveEvents());
    reporter.send();

    EventDatabaseOpenHelper helper = new EventDatabaseOpenHelper(this.application);
    SQLiteDatabase db = helper.getWritableDatabase();
    Cursor cursor = db.query(Events.TABLE_NAME, Events.orderedColumns(), null, null, null, null,
            Events.IDENTIFIER);

    List<Event> remainingEvents = readCursor(cursor);
    assertThat(remainingEvents).hasSize(2);
    assertThat(remainingEvents.get(0).getIdentifier())
            .isEqualTo(UUID.fromString("4c654f6e-0373-43cf-bd52-31e20067c397"));
    assertThat(remainingEvents.get(1).getIdentifier())
            .isEqualTo(UUID.fromString("74af8761-11ab-47d9-b787-a41c437b7bf1"));

    assertThat(server.getRequestCount()).isEqualTo(6);

    server.takeRequest(1, TimeUnit.SECONDS);
    RecordedRequest request2 = server.takeRequest(1, TimeUnit.SECONDS);
    server.takeRequest(1, TimeUnit.SECONDS);
    RecordedRequest request4 = server.takeRequest(1, TimeUnit.SECONDS);
    server.takeRequest(1, TimeUnit.SECONDS);
    RecordedRequest request6 = server.takeRequest(1, TimeUnit.SECONDS);

    String credentials = Credentials.basic(probeId.toString(), accessKey.toString());

    assertThat(request2.getHeader("Authorization")).isEqualTo(credentials);
    assertThat(fromJson(request2.getBody().readUtf8())).hasSize(2);
    assertThat(request4.getHeader("Authorization")).isEqualTo(credentials);
    assertThat(fromJson(request4.getBody().readUtf8())).hasSize(2);
    assertThat(request6.getHeader("Authorization")).isEqualTo(credentials);
    assertThat(fromJson(request6.getBody().readUtf8())).hasSize(1);

    Util.closeQuietly(cursor);
    server.shutdown();
}

From source file:io.morea.handy.android.SendLogTask.java

License:Apache License

public SendLogTask(final Context context, final EventReporterConfiguration configuration) {
    // Don't make Context a WeakReference, otherwise the reference could get collected before the task is actually
    // run and the task should be executed in any case. There's also no risk to create a memory leak here because
    // the task will be thrown away afterwards anyway.
    this.context = context;
    this.configuration = configuration;

    client = new OkHttpClient();
    client.setConnectTimeout(configuration.getHttpTimeout(), TimeUnit.MILLISECONDS);
    client.setWriteTimeout(configuration.getHttpTimeout(), TimeUnit.MILLISECONDS);
    client.setReadTimeout(configuration.getHttpTimeout(), TimeUnit.MILLISECONDS);
    client.setAuthenticator(new Authenticator() {
        @Override/*from   w w w.  j  a  v  a 2s  . c o m*/
        public Request authenticate(Proxy proxy, Response response) {
            String credential = Credentials.basic(configuration.getProbeId(), configuration.getAccessKey());
            return response.request().newBuilder().header("Authorization", credential).build();
        }

        @Override
        public Request authenticateProxy(Proxy proxy, Response response) {
            return null;
        }
    });

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
    this.gson = gsonBuilder.create();
}

From source file:io.takari.aether.okhttp.OkHttpAetherClient.java

License:Open Source License

private String toHeaderValue(AetherClientAuthentication auth) {
    return Credentials.basic(auth.getUsername(), auth.getPassword());
}

From source file:lumbermill.internal.elasticsearch.ElasticSearchOkHttpClientImpl.java

License:Apache License

public ElasticSearchOkHttpClientImpl withBasicAuth(String user, String passwd) {
    this.basicAuthHeader = Optional.of(Credentials.basic(user, passwd));
    return this;
}

From source file:net.codestory.rest.RestAssert.java

License:Apache License

private static UnaryOperator<Request.Builder> addBasicAuthHeader(String login, String password) {
    return addHeader("Authorization", Credentials.basic(login, password));
}

From source file:net.simno.klingar.ui.LoginController.java

License:Apache License

private void login() {
    disableInput();/*from  ww w .j  av a 2 s .c o  m*/

    String username = usernameEdit.getText().toString();
    String password = passwordEdit.getText().toString();

    if (Strings.isBlank(username)) {
        usernameEdit.setError(invalidUsername);
        enableInput();
        return;
    }
    if (Strings.isBlank(password) || password.length() < 8) {
        passwordEdit.setError(invalidPassword);
        enableInput();
        return;
    }

    hideInputMethod();
    invisible(loginForm);
    contentLoading.show();
    disposables.add(plex.signIn(Credentials.basic(username, password)).compose(bindUntilEvent(DETACH))
            .compose(rx.singleSchedulers()).subscribe(user -> {
                loginManager.login(user.authenticationToken);
                if (getActivity() != null) {
                    getActivity().invalidateOptionsMenu();
                }
                getRouter().setRoot(RouterTransaction.with(new BrowserController(null)));
            }, e -> {
                Rx.onError(e);
                loginManager.logout();
                contentLoading.hide();
                visible(loginForm);
                showToast(R.string.sign_in_failed);
                enableInput();
            }));
}

From source file:net.yatomiya.nicherry.services.bbs.BBSHttpClient.java

License:Open Source License

void applyProxyPreference() {
    PreferenceService prefs = context.get(PreferenceService.class);
    boolean enable = Boolean.valueOf(prefs.getString(NPreferences.NODE, NPreferences.NETWORK_PROXY_ENABLE));
    String host = prefs.getString(NPreferences.NODE, NPreferences.NETWORK_PROXY_HOST);
    int port = Integer.valueOf(prefs.getString(NPreferences.NODE, NPreferences.NETWORK_PROXY_PORT));
    String username = prefs.getString(NPreferences.NODE, NPreferences.NETWORK_PROXY_BASIC_USERNAME);
    String password = prefs.getString(NPreferences.NODE, NPreferences.NETWORK_PROXY_BASIC_PASSWORD);

    if (enable && !JUtils.isEmpty(host)) {
        setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)));
    } else {/*from ww w  .j a v a2  s . c o m*/
        setProxy(Proxy.NO_PROXY);
    }

    if (enable && !JUtils.isEmpty(username) && !JUtils.isEmpty(password)) {
        proxyCredentials = Credentials.basic(username, password);
    } else {
        proxyCredentials = null;
    }
}

From source file:objective.taskboard.jira.endpoint.JiraEndpoint.java

License:Open Source License

public byte[] readBytesFromURL(URL url, String username, String password) throws IOException {
    URLConnection connection = url.openConnection();
    connection.setRequestProperty("Authorization", Credentials.basic(username, password));
    try (InputStream inputStream = connection.getInputStream()) {
        byte[] bytes = new byte[connection.getContentLength()];
        inputStream.read(bytes);//from w w w  .  j  a  v a2  s .c o m
        return bytes;
    } catch (Exception e) {
        log.error("Error reading bytes from url: " + e.getMessage());
        throw new IllegalStateException(e);
    }
}

From source file:org.addhen.birudo.data.net.JenkinsClient.java

License:Apache License

public GcmRegistrationStatus sendGcmTokenToServer() throws Exception {
    if (mJenkinsUserEntity == null) {
        return null;
    }//w ww  . j a va 2  s .  c om

    // Retrieve crumbInfo
    CrumbInfoEntity crumbInfoEntity = retrieveCrumbInfo();
    if (crumbInfoEntity != null && crumbInfoEntity.isCsrfEnabled()) {
        setHeader(crumbInfoEntity.getCrumbRequestField(), crumbInfoEntity.getCrumb());
    }

    FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();

    formEncodingBuilder.add("token", mJenkinsUserEntity.getSenderId());

    String credential = Credentials.basic(mJenkinsUserEntity.getUsername(), mJenkinsUserEntity.getToken());

    setHeader("Authorization", credential);

    setRequestBody(formEncodingBuilder.build());

    // Send to gcm/regsiter
    super.url = String.format("%sgcm/register", mJenkinsUserEntity.getUrl());
    setMethod(HttpMethod.POST);
    execute();

    final int statusCode = getResponse().code();
    GcmRegistrationStatus status = new GcmRegistrationStatus();
    status.setStatusCode(statusCode);
    if (statusCode != 200) {
        log("Sending registering token failed with satus code %s", statusCode);
        status.setStatus(false);
    } else {
        status.setStatus(true);
    }

    return status;
}

From source file:org.apache.nifi.processors.standard.util.MultiAuthenticator.java

License:Apache License

@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
    String credential = Credentials.basic(proxyUsername, proxyPassword);
    return response.request().newBuilder().header("Proxy-Authorization", credential).build();
}