Example usage for com.squareup.okhttp OkHttpClient newCall

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

Introduction

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

Prototype

public Call newCall(Request request) 

Source Link

Document

Prepares the request to be executed at some point in the future.

Usage

From source file:io.macgyver.core.okhttp.LoggingInterceptorTest.java

License:Apache License

@Test
public void testIt() throws IOException {

    x.enqueue(/*from ww w. j ava2  s . c  o  m*/
            new MockResponse().setBody("{\"hello\":\"world\"}").addHeader("Content-type", "application/json"));
    OkHttpClient c = new OkHttpClient();
    c.interceptors()
            .add(LoggingInterceptor.create(LoggerFactory.getLogger(LoggingInterceptorTest.class), Level.NONE));

    c.newCall(new Request.Builder().url(x.url("/foo")).addHeader("Authorization", "foo").build()).execute();
}

From source file:io.macgyver.core.okhttp.LoggingInterceptorTest.java

License:Apache License

@Test
public void testResponseException() throws IOException {

    x.enqueue(/*from   ww  w  .j  av a 2  s.  c o  m*/
            new MockResponse().setBody("{\"hello\":\"world\"}").addHeader("Content-type", "application/json"));
    OkHttpClient c = new OkHttpClient();

    c.interceptors().add(new BlowingLoggingInterceptor(LoggerFactory.getLogger(BlowingLoggingInterceptor.class),
            Level.BODY));

    c.newCall(new Request.Builder().url(x.url("/foo")).addHeader("Authorization", "foo").build()).execute();
}

From source file:io.macgyver.core.util.CertChecker.java

License:Apache License

private List<ObjectNode> checkCertChain(String url) throws IOException {
    List<ObjectNode> problems = new ArrayList<ObjectNode>();
    try {/*w  w w  . j a  v a  2  s  .c  o m*/
        OkHttpClient c = new OkHttpClient();
        Request.Builder b = new Request.Builder().url(url);
        c.setHostnameVerifier(SslTrust.withoutHostnameVerification());
        Response response = c.newCall(b.build()).execute();
        response.body().close();
    } catch (Exception e) {
        if (e.toString().contains("PKIX path building failed")) {
            ObjectNode n = new ObjectMapper().createObjectNode();
            n.put(DESCRIPTION, "invalid certficate chain");
            problems.add(n);
        }

    }
    return problems;

}

From source file:io.macgyver.core.util.CertChecker.java

License:Apache License

public List<X509Certificate> fetchCertificates(String httpUrl) throws IOException {
    OkHttpClient c = new OkHttpClient();

    CertExtractor extractor = new CertExtractor();
    c.setHostnameVerifier(extractor);//from   w  ww.j  ava  2s.  c o m
    c.setSslSocketFactory(SslTrust.withoutCertificateValidation().getSocketFactory());

    Request r = new Request.Builder().url(httpUrl).build();

    Response response = c.newCall(r).execute();
    response.body().close();

    return extractor.certList;

}

From source file:io.macgyver.neorx.rest.NeoRxClient.java

License:Apache License

protected ObjectNode execRawCypher(String cypher, ObjectNode params) {

    try {//from   w w  w .j av a 2  s  . c  o m

        ObjectNode payload = formatPayload(cypher, params);

        String payloadString = payload.toString();
        OkHttpClient c = getClient();
        checkNotNull(c);
        String requestId = newRequestId();
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("request[%s]: %s", requestId, payloadString));
        }
        Builder builder = injectCredentials(new Request.Builder())
                .addHeader("X-Stream", Boolean.toString(streamResponse)).addHeader("Accept", "application/json")
                .url(getUrl() + "/db/data/transaction/commit")
                .post(RequestBody.create(MediaType.parse("application/json"), payloadString));

        if (!GuavaStrings.isNullOrEmpty(username) && !GuavaStrings.isNullOrEmpty(password)) {
            builder = builder.addHeader("Authorization", Credentials.basic(username, password));
        }

        com.squareup.okhttp.Response r = c.newCall(builder.build()).execute();

        ObjectNode jsonResponse = (ObjectNode) mapper.readTree(r.body().charStream());
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("response[%s]: %s", requestId, jsonResponse.toString()));
        }
        ObjectNode n = jsonResponse;
        JsonNode error = n.path("errors").path(0);

        if (error instanceof ObjectNode) {

            throw new NeoRxException(((ObjectNode) error));
        }

        return n;

    } catch (IOException e) {
        throw new NeoRxException(e);
    }
}

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

License:Apache License

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

    // set up mock response
    mockServer.enqueue(//w w w  .ja  va 2s. c om
            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.promagent.it.SpringIT.java

License:Apache License

/**
 * Run some HTTP queries against a Docker container from image promagent/spring-promagent.
 * <p/>/*from   w  w  w.j a v  a2 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);
}

From source file:io.promagent.it.WildflyIT.java

License:Apache License

/**
 * Run some HTTP queries against a Docker container from image promagent/wildfly-kitchensink-promagent.
 * <p/>// ww  w  . j  a  v a 2  s. c  o m
 * The Docker container is started by the maven-docker-plugin when running <tt>mvn verify -Pwildfly</tt>.
 */
@Test
public void testWildfly() throws Exception {
    OkHttpClient client = new OkHttpClient();
    Request restRequest = new Request.Builder().url(System.getProperty("deployment.url") + "/rest/members")
            .build();

    // Execute REST call
    Response restResponse = client.newCall(restRequest).execute();
    Assertions.assertEquals(restResponse.code(), 200);
    Assertions.assertTrue(restResponse.body().string().contains("John Smith"));

    Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric
    assertMetrics(client, "1.0");

    // Execute REST call again
    restResponse = client.newCall(restRequest).execute();
    Assertions.assertEquals(restResponse.code(), 200);
    Assertions.assertTrue(restResponse.body().string().contains("John Smith"));

    Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric
    assertMetrics(client, "2.0");
}

From source file:io.promagent.it.WildflyIT.java

License:Apache License

private void assertMetrics(OkHttpClient client, String nCalls) throws Exception {

    Request metricsRequest = new Request.Builder().url(System.getProperty("promagent.url") + "/metrics")
            .build();//from  ww w . ja  v  a 2 s. c om
    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=\"GET\""))
            .filter(m -> m.contains("path=\"/wildfly-kitchensink/rest/members\""))
            .filter(m -> m.contains("status=\"200\"")).findFirst()
            .orElseThrow(() -> new Exception("http_requests_total metric not found."));

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

    String sqlQueriesTotal = Arrays.stream(metricsLines).filter(m -> m.contains("sql_queries_total")).filter(
            m -> m.matches(".*?query=\"select .*?id .*?email .*?name .*?phone_number .*? from Member .*?\".*?"))
            .filter(m -> m.contains("method=\"GET\""))
            .filter(m -> m.contains("path=\"/wildfly-kitchensink/rest/members\"")).findFirst()
            .orElseThrow(() -> new Exception("sql_queries_total metric not found."));

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

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

License:Open Source License

private Response execute(OkHttpClient httpClient, Request request) throws IOException {
    com.squareup.okhttp.Response response = httpClient.newCall(request).execute();
    switch (response.code()) {
    case HttpURLConnection.HTTP_PROXY_AUTH:
        if (config.getProxy() == null) {
            throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
        }//from  w w  w  .  j  a  v  a  2 s  .c  o  m
        if (config.getProxy().getAuthentication() != null && !headers.containsKey("Proxy-Authorization")) {
            headers.put("Proxy-Authorization", toHeaderValue(config.getProxy().getAuthentication()));
            return null; // retry
        }
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        if (config.getAuthentication() != null && !headers.containsKey("Authorization")) {
            headers.put("Authorization", toHeaderValue(config.getAuthentication()));
            return null; // retry
        }
        break;
    }
    return new ResponseAdapter(response); // do not retry
}