Example usage for com.squareup.okhttp OkHttpClient OkHttpClient

List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient

Introduction

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

Prototype

public OkHttpClient() 

Source Link

Usage

From source file:io.macgyver.plugin.atlassian.confluence.BasicConfluenceClient.java

License:Apache License

public BasicConfluenceClient(String url, String username, String password) {
    OkHttpClient c = new OkHttpClient();
    c.interceptors().add(new BasicAuthInterceptor(username, password));

    OkRestClient client = new OkRestClient(c);

    this.target = client.uri(url);

    //   client.getConverterRegistry().setDefaultResponseErrorHandler(new ConfluenceResponseErrorHandler());

}

From source file:io.macgyver.plugin.atlassian.jira.JiraClientImpl.java

License:Apache License

public JiraClientImpl(String url, String username, String password) {

    OkHttpClient c = new OkHttpClient();
    c.interceptors().add(new BasicAuthInterceptor(username, password));

    OkRestClient client = new OkRestClient(c);
    target = client.url(url);//from  w ww  .ja va  2  s. c o  m

}

From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java

License:Apache License

protected OkHttpClient getClient() {

    // not guaranteed to be singleton, but close enough
    if (clientReference.get() == null) {
        OkHttpClient c = new OkHttpClient();

        c.setConnectTimeout(20, TimeUnit.SECONDS);

        c.setHostnameVerifier(withoutHostnameVerification());
        c.setSslSocketFactory(withoutCertificateValidation().getSocketFactory());

        c.setConnectionSpecs(getA10CompatibleConnectionSpecs());
        c.interceptors().add(LoggingInterceptor.create(A10ClientImpl.class));
        clientReference.set(c);/*from w ww .  j a  va2s .  c  o  m*/
    }
    return clientReference.get();
}

From source file:io.macgyver.plugin.github.GitHubServiceFactory.java

License:Apache License

@Override
protected GitHub doCreateInstance(ServiceDefinition def) {
    try {//from w w w. ja va2s  . co  m
        Properties props = def.getProperties();
        String url = props.getProperty("url");
        String oauthToken = props.getProperty("oauthToken");
        String username = props.getProperty("username");
        String password = props.getProperty("password");

        boolean useToken = Strings.isNullOrEmpty(oauthToken) == false;
        boolean useUsernamePassword = (Strings.isNullOrEmpty(username) == false)
                && (Strings.isNullOrEmpty(password) == false);

        String message = "connecting to {} using {}";

        GitHubBuilder builder = new GitHubBuilder();

        builder = builder.withConnector(new OkHttpConnector(new OkUrlFactory(new OkHttpClient())));

        GitHub gh = null;

        if (url != null) {
            builder = builder.withEndpoint(url);
        } else {
            builder = builder.withEndpoint("https://api.github.com");
        }

        if (useToken) {
            logger.info(message, url, "oauth");
            builder = builder.withOAuthToken(oauthToken);

        } else if (useUsernamePassword) {
            logger.info(message, url, "username/password");
            builder = builder.withPassword(username, password);
        }

        gh = builder.build();

        return gh;
    } catch (IOException e) {
        throw new io.macgyver.core.ConfigurationException("problem creating GitHub client", e);
    }
}

From source file:io.macgyver.plugin.github.GitHubServiceFactory.java

License:Apache License

@Override
protected void doCreateCollaboratorInstances(ServiceRegistry registry, ServiceDefinition primaryDefinition,
        Object primaryBean) {//from  w ww .  j a va  2s .  co m

    OkHttpClient c = new OkHttpClient();
    GitHub h;

    final String oauthToken = primaryDefinition.getProperties().getProperty("oauthToken");
    final String username = primaryDefinition.getProperties().getProperty("username");
    final String password = primaryDefinition.getProperties().getProperty("password");
    String url = primaryDefinition.getProperties().getProperty("url");
    if (!Strings.isNullOrEmpty(oauthToken)) {
        logger.info("using oauth");
        c.interceptors().add(new BasicAuthInterceptor(oauthToken, "x-oauth-token"));

    } else if (!Strings.isNullOrEmpty(username)) {
        logger.info("using username/password auth for OkRest client: " + username + "/" + password);
        c.interceptors().add(new BasicAuthInterceptor(username, password));

    } else {
        logger.info("using anonymous auth");
    }

    if (Strings.isNullOrEmpty(url)) {
        url = "https://api.github.com";
    }
    OkRestTarget rest = new OkRestClient(c).url(url);

    registry.registerCollaborator(primaryDefinition.getName() + "Api", rest);

    GitHubScannerBuilder scannerBuilder = Kernel.getApplicationContext().getBean(Projector.class)
            .createBuilder(GitHubScannerBuilder.class);
    if (!Strings.isNullOrEmpty(url)) {
        scannerBuilder = scannerBuilder.withUrl(url);
    }
    if (!Strings.isNullOrEmpty(username)) {
        scannerBuilder = scannerBuilder.withUsername(username);
    }
    if (!Strings.isNullOrEmpty(password)) {
        scannerBuilder = scannerBuilder.withPassword(password);
    }
    if (!Strings.isNullOrEmpty(oauthToken)) {
        scannerBuilder = scannerBuilder.withToken(oauthToken);
    }
    GitHubScanner scanner = scannerBuilder.build();

    registry.registerCollaborator(primaryDefinition.getName() + "Scanner", scanner);
}

From source file:io.macgyver.plugin.pagerduty.PagerDutyClientImpl.java

License:Apache License

protected OkHttpClient newEventClient() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, TimeUnit.SECONDS);

    if (!getCertificateValidationEnabled()) {
        client = client.setHostnameVerifier(SslTrust.withoutHostnameVerification());
        client = client.setSslSocketFactory(SslTrust.withoutCertificateValidation().getSocketFactory());

    }/*from   w ww. java2  s .  c  o m*/

    return client;
}

From source file:io.macgyver.test.MockWebServerTest.java

License:Apache License

@Test
public void testIt() throws IOException, InterruptedException {

    // set up mock response
    mockServer.enqueue(/*from  w  w  w  .  ja v a2  s. co  m*/
            new MockResponse().setBody("{\"name\":\"Rob\"}").addHeader("Content-type", "application/json"));

    // set up client and request
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(mockServer.getUrl("/test").toString())
            .post(RequestBody.create(MediaType.parse("application/json"), "{}"))
            .header("Authorization", Credentials.basic("scott", "tiger")).build();

    // make the call
    Response response = client.newCall(request).execute();

    // check the response
    assertThat(response.code()).isEqualTo(200);
    assertThat(response.header("content-type")).isEqualTo("application/json");

    // check the response body
    JsonNode n = new ObjectMapper().readTree(response.body().string());
    assertThat(n.path("name").asText()).isEqualTo("Rob");

    // now make sure that the request was as we exepected it to be
    RecordedRequest recordedRequest = mockServer.takeRequest();
    assertThat(recordedRequest.getPath()).isEqualTo("/test");
    assertThat(recordedRequest.getHeader("Authorization")).isEqualTo("Basic c2NvdHQ6dGlnZXI=");

}

From source file:io.mapsquare.osmcontributor.flickr.oauth.FlickrOAuth.java

License:Open Source License

public FlickrOAuth() {
    // Init Flickr retrofit client
    RestAdapter adapter = new RestAdapter.Builder().setConverter(new StringConverter()).setEndpoint(OAUTH_URL)
            .setClient(new OkClient(new OkHttpClient())).setLogLevel(RestAdapter.LogLevel.FULL).build();
    flickrOauthClient = adapter.create(FlickrOauthClient.class);
}

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//  ww w.j  a  v  a 2s.co  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.promagent.it.SpringIT.java

License:Apache License

/**
 * Run some HTTP queries against a Docker container from image promagent/spring-promagent.
 * <p/>/*w  w  w .  j ava 2  s . com*/
 * The Docker container is started by the maven-docker-plugin when running <tt>mvn verify -Pspring</tt>.
 */
@Test
public void testSpring() throws Exception {
    OkHttpClient client = new OkHttpClient();
    Request metricsRequest = new Request.Builder().url(System.getProperty("promagent.url") + "/metrics")
            .build();

    // Execute two POST requests
    Response restResponse = client.newCall(makePostRequest("Frodo", "Baggins")).execute();
    assertEquals(201, restResponse.code());
    restResponse = client.newCall(makePostRequest("Bilbo", "Baggins")).execute();
    assertEquals(201, restResponse.code());

    // Query Prometheus metrics from promagent
    Response metricsResponse = client.newCall(metricsRequest).execute();
    String[] metricsLines = metricsResponse.body().string().split("\n");

    String httpRequestsTotal = Arrays.stream(metricsLines).filter(m -> m.contains("http_requests_total"))
            .filter(m -> m.contains("method=\"POST\"")).filter(m -> m.contains("path=\"/people\""))
            .filter(m -> m.contains("status=\"201\"")).findFirst()
            .orElseThrow(() -> new Exception("http_requests_total metric not found."));

    assertTrue(httpRequestsTotal.endsWith("2.0"), "Value should be 2.0 for " + httpRequestsTotal);

    String sqlQueriesTotal = Arrays.stream(metricsLines).filter(m -> m.contains("sql_queries_total"))
            // The following regular expression tests for this string, but allows the parameters 'id', 'fist_name', 'last_name' to change order:
            // query="insert into person (first_name, last_name, id)"
            .filter(m -> m.matches(
                    ".*query=\"insert into person \\((?=.*id)(?=.*first_name)(?=.*last_name).*\\) values \\(...\\)\".*"))
            .filter(m -> m.contains("method=\"POST\"")).filter(m -> m.contains("path=\"/people\"")).findFirst()
            .orElseThrow(() -> new Exception("sql_queries_total metric not found."));

    assertTrue(sqlQueriesTotal.endsWith("2.0"), "Value should be 2.0 for " + sqlQueriesTotal);
}