Example usage for com.squareup.okhttp Response code

List of usage examples for com.squareup.okhttp Response code

Introduction

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

Prototype

int code

To view the source code for com.squareup.okhttp Response code.

Click Source Link

Usage

From source file:io.kodokojo.bdd.stage.BrickConfigurerGiven.java

License:Open Source License

private boolean waitBrickStarted(String brickUrl, int timeout) {
    boolean started = false;
    long now = System.currentTimeMillis();
    long end = now + (timeout * 1000);

    OkHttpClient httpClient = new OkHttpClient();
    Request request = new Request.Builder().get().url(brickUrl).build();
    while (!started && (end - System.currentTimeMillis()) > 0) {
        Response response = null;
        try {/*from   w w w .j a  va  2 s  .  c  o m*/
            response = httpClient.newCall(request).execute();
            int httpStatusCode = response.code();
            started = httpStatusCode >= 200 && httpStatusCode < 300;
        } catch (IOException e) {
            // Silently ignore, service maybe not available
            started = false;
        } finally {
            if (response != null) {
                IOUtils.closeQuietly(response.body());
            }
        }
        if (!started) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    return started;
}

From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationGiven.java

License:Open Source License

private void killApp(String appId) {
    OkHttpClient httpClient = new OkHttpClient();
    Request request = new Request.Builder().delete().url(marathonUrl + "/v2/apps/" + appId).build();
    try {/* w  ww  . j av  a2s  .  c  om*/
        Response response = httpClient.newCall(request).execute();
        assertThat(response.code()).isEqualTo(200);
    } catch (IOException e) {
        LOGGER.error("Unable to kill app {}.", appId, e);
    }
}

From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationWhen.java

License:Open Source License

public SELF i_start_the_project() {

    OkHttpClient httpClient = new OkHttpClient();

    String url = "http://" + restEntryPointHost + ":" + restEntryPointPort + "/api/v1/project/"
            + projectConfiguration.getIdentifier();
    RequestBody body = RequestBody.create(null, new byte[0]);
    Request.Builder builder = new Request.Builder().url(url).post(body);
    builder = HttpUserSupport.addBasicAuthentification(currentUser, builder);
    Response response = null;

    try {// www  . j  a  v  a  2s. c  o m
        response = httpClient.newCall(builder.build()).execute();
        assertThat(response.code()).isEqualTo(201);
        LOGGER.trace("Starting project");

        Map<String, Boolean> brickRunning = new HashMap<>();
        projectConfiguration.getDefaultBrickConfigurations().forEachRemaining(b -> {
            brickRunning.put(b.getName(), Boolean.FALSE);
        });

        JsonParser parser = new JsonParser();
        boolean allBrickStarted = true;

        long now = System.currentTimeMillis();
        long end = now + 180000;

        do {
            Iterator<String> messageReceive = webSocketEventsListener.getMessages().iterator();
            while (messageReceive.hasNext()) {
                String message = messageReceive.next();
                JsonObject root = (JsonObject) parser.parse(message);
                if ("updateState".equals(root.getAsJsonPrimitive("action").getAsString())) {
                    JsonObject data = root.getAsJsonObject("data");
                    String brickName = data.getAsJsonPrimitive("brickName").getAsString();
                    String brickState = data.getAsJsonPrimitive("state").getAsString();
                    if ("RUNNING".equals(brickState)) {
                        brickRunning.put(brickName, Boolean.TRUE);
                    }
                }
            }
            Iterator<Boolean> iterator = brickRunning.values().iterator();
            allBrickStarted = true;
            while (allBrickStarted && iterator.hasNext()) {
                allBrickStarted = iterator.next();
            }
            if (!allBrickStarted) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            now = System.currentTimeMillis();
        } while (!allBrickStarted && now < end);
        assertThat(allBrickStarted).isTrue();
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }

    return self();
}

From source file:io.kodokojo.bdd.stage.HttpUserSupport.java

License:Open Source License

public String createProjectConfiguration(String projectName, StackConfigDto stackConfigDto,
        UserInfo currentUser) {//from  w  w  w  . ja  v  a2 s . c om
    if (isBlank(projectName)) {
        throw new IllegalArgumentException("projectName must be defined.");
    }
    String json = generateProjectConfigurationDto(projectName, currentUser, stackConfigDto);
    RequestBody body = RequestBody.create(MediaType.parse("application/json"), json.getBytes());
    Request.Builder builder = new Request.Builder().url(getApiBaseUrl() + "/projectconfig").post(body);
    Request request = addBasicAuthentification(currentUser, builder).build();
    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        assertThat(response.code()).isEqualTo(201);
        String payload = response.body().string();
        return payload;
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    return null;
}

From source file:io.kodokojo.bdd.stage.HttpUserSupport.java

License:Open Source License

private <T extends Serializable> T getRessources(String path, UserInfo currentUser, Class<T> expectedType) {

    Request.Builder builder = new Request.Builder().url(getApiBaseUrl() + path).get();
    builder = addBasicAuthentification(currentUser, builder);
    Response response = null;
    try {/* w ww. j a  v  a 2s .co  m*/
        response = httpClient.newCall(builder.build()).execute();
        assertThat(response.code()).isEqualTo(200);
        Gson gson = new GsonBuilder().create();
        return gson.fromJson(response.body().string(), expectedType);
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    return null;
}

From source file:io.kodokojo.bdd.stage.HttpUserSupport.java

License:Open Source License

public void startProject(String projectConfigurationIdentifier, UserInfo currentUser) {
    RequestBody body = RequestBody.create(null, new byte[0]);
    Request.Builder builder = new Request.Builder()
            .url("http://" + endpoint + "/api/v1/project/" + projectConfigurationIdentifier).post(body);
    builder = HttpUserSupport.addBasicAuthentification(currentUser, builder);
    Request request = builder.build();
    Response response = null;
    try {/*  w ww  .  ja v  a2s. com*/
        response = httpClient.newCall(request).execute();
        assertThat(response.code()).isEqualTo(201);
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
}

From source file:io.kodokojo.bdd.stage.HttpUserSupport.java

License:Open Source License

private void executeRequestWithExpectedStatus(Request request, int expectedStatus) {

    Response response = null;
    try {/*w ww .jav a 2s .  co m*/
        response = httpClient.newCall(request).execute();
        assertThat(response.code()).isEqualTo(expectedStatus);
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
}

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;
    try {/*w  w w .  j ava 2s .  co m*/
        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

private boolean executeRequest(OkHttpClient httpClient, String url, String xmlBody, String login,
        String password) {//from  w ww  .  java  2 s  . c  om
    RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml"), xmlBody);
    Request request = new Request.Builder().url(url)
            .addHeader("Authorization", encodeBasicAuth(login, password)).post(requestBody).build();
    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        return response.code() >= 200 && response.code() < 300;
    } catch (IOException e) {
        LOGGER.error("Unable to complete request on Nexus url {}", url, 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 storeBootstrapStackData(BootstrapStackData bootstrapStackData) {
    if (bootstrapStackData == null) {
        throw new IllegalArgumentException("bootstrapStackData must be defined.");
    }/*ww w .  ja  v a 2  s  . com*/
    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;
}