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.kodokojo.brick.jenkins.JenkinsConfigurer.java

License:Open Source License

private BrickConfigurerData executeGroovyScript(BrickConfigurerData brickConfigurerData,
        VelocityContext context, String templatePath) {
    String url = brickConfigurerData.getEntrypoint() + SCRIPT_URL_SUFFIX;
    OkHttpClient httpClient = new OkHttpClient();
    Response response = null;/*from ww w . j av  a 2 s  .c  o m*/
    try {
        VelocityEngine ve = new VelocityEngine();
        ve.init(VE_PROPERTIES);

        Template template = ve.getTemplate(templatePath);

        StringWriter sw = new StringWriter();
        template.merge(context, sw);
        String script = sw.toString();

        RequestBody body = new FormEncodingBuilder().add(SCRIPT_KEY, script).build();

        Request.Builder builder = new Request.Builder().url(url).post(body);
        User admin = brickConfigurerData.getDefaultAdmin();
        String crendential = String.format("%s:%s", admin.getUsername(), admin.getPassword());
        builder.addHeader("Authorization",
                "Basic " + Base64.getEncoder().encodeToString(crendential.getBytes()));
        Request request = builder.build();
        response = httpClient.newCall(request).execute();
        if (response.code() >= 200 && response.code() < 300) {
            return brickConfigurerData;
        }
        throw new RuntimeException("Unable to configure Jenkins " + brickConfigurerData.getEntrypoint()
                + ". Jenkins return " + response.code());//Create a dedicate Exception instead.
    } catch (IOException e) {
        throw new RuntimeException("Unable to configure Jenkins " + brickConfigurerData.getEntrypoint(), e);
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
}

From source file:io.kodokojo.brick.nexus.NexusConfigurer.java

License:Open Source License

protected OkHttpClient provideHttpClient() {
    return new OkHttpClient();
}

From source file:io.kodokojo.commons.utils.docker.DockerSupport.java

License:Open Source License

public boolean waitUntilHttpRequestRespond(String url, long time, TimeUnit unit, ServiceIsUp serviceIsUp) {
    if (isBlank(url)) {
        throw new IllegalArgumentException("url must be defined.");
    }//from ww w.j  ava  2 s. co m

    long now = System.currentTimeMillis();
    long delta = unit != null ? TimeUnit.MILLISECONDS.convert(time, unit) : time;
    long endTime = now + delta;
    long until = 0;

    OkHttpClient httpClient = new OkHttpClient();
    HttpUrl httpUrl = HttpUrl.parse(url);

    int nbTry = 0;
    boolean available = false;
    do {
        nbTry++;
        available = tryRequest(httpUrl, httpClient, serviceIsUp);
        if (!available) {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                Thread.interrupted();
                break;
            }
            now = System.currentTimeMillis();
            until = endTime - now;
        }
    } while (until > 0 && !available);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(url + " " + (available ? "Success" : "Failed after " + nbTry + " try"));
    }
    return available;
}

From source file:io.kodokojo.service.marathon.MarathonConfigurationStore.java

License:Open Source License

@Override
public boolean storeBootstrapStackData(BootstrapStackData bootstrapStackData) {
    if (bootstrapStackData == null) {
        throw new IllegalArgumentException("bootstrapStackData must be defined.");
    }/*from  ww  w. ja v  a2 s .co  m*/
    String url = marathonUrl + "/v2/artifacts/config/" + bootstrapStackData.getProjectName().toLowerCase()
            + ".json";
    OkHttpClient httpClient = new OkHttpClient();
    Gson gson = new GsonBuilder().create();
    String json = gson.toJson(bootstrapStackData);
    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
            .addFormDataPart("file", bootstrapStackData.getProjectName().toLowerCase() + ".json",
                    RequestBody.create(MediaType.parse("application/json"), json.getBytes()))
            .build();
    Request request = new Request.Builder().url(url).post(requestBody).build();
    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        return response.code() == 200;
    } catch (IOException e) {
        LOGGER.error("Unable to store configuration for project {}", bootstrapStackData.getProjectName(), e);
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    return false;
}

From source file:io.kodokojo.service.marathon.MarathonConfigurationStore.java

License:Open Source License

@Override
public boolean storeSSLKeys(String project, String entityName, SSLKeyPair sslKeyPair) {
    if (isBlank(project)) {
        throw new IllegalArgumentException("project must be defined.");
    }// w ww  .j a v a  2  s.c om
    if (isBlank(entityName)) {
        throw new IllegalArgumentException("entityName must be defined.");
    }
    if (sslKeyPair == null) {
        throw new IllegalArgumentException("sslKeyPair must be defined.");
    }
    Response response = null;
    try {
        Writer writer = new StringWriter();
        SSLUtils.writeSSLKeyPairPem(sslKeyPair, writer);
        byte[] certificat = writer.toString().getBytes();

        String url = marathonUrl + "/v2/artifacts/ssl/" + project.toLowerCase() + "/" + entityName.toLowerCase()
                + "/" + project.toLowerCase() + "-" + entityName.toLowerCase() + "-server.pem";
        OkHttpClient httpClient = new OkHttpClient();
        RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                .addFormDataPart("file", project + "-" + entityName + "-server.pem",
                        RequestBody.create(MediaType.parse("application/text"), certificat))
                .build();
        Request request = new Request.Builder().url(url).post(requestBody).build();
        response = httpClient.newCall(request).execute();
        int code = response.code();
        if (code > 200 && code < 300) {
            LOGGER.info("Push SSL certificate on marathon url '{}' [content-size={}]", url, certificat.length);
        } else {
            LOGGER.error("Fail to push SSL certificate on marathon url '{}' status code {}. Body response:\n{}",
                    url, code, response.body().string());
        }
        return code > 200 && code < 300;
    } catch (IOException e) {
        LOGGER.error("Unable to store ssl key for project {} and brick {}", project, entityName, e);
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    return false;
}

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

License:Apache License

@Test
public void testIt() throws IOException {

    x.enqueue(//from  w w  w .  ja v a2 s  .co  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(/*  www .  j  ava2  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 {//  www  .  j a v  a2 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);//  ww  w.j  a va 2s  . c  om
    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

public NeoRxClient(String url, String username, String password, boolean validateCertificates) {

    while (url.endsWith("/")) {
        url = url.substring(0, url.length() - 1);
    }//from  ww  w .  ja  v a 2  s .c om
    this.url = url;
    this.username = username;
    this.password = password;
    this.validateCertificates = validateCertificates;

    OkHttpClient client = new OkHttpClient();

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

    }

    this.httpClient = client;
}