Example usage for com.squareup.okhttp Request.Builder Request.Builder

List of usage examples for com.squareup.okhttp Request.Builder Request.Builder

Introduction

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

Prototype

Request.Builder

Source Link

Usage

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

License:Open Source License

public SELF retrive_a_new_id() {
    OkHttpClient httpClient = new OkHttpClient();
    RequestBody emptyBody = RequestBody.create(null, new byte[0]);
    String baseUrl = getBaseUrl();
    Request request = new Request.Builder().post(emptyBody).url(baseUrl + "/api/v1/user").build();
    Response response = null;//from  w  w  w .  j a  v a 2s  .c o  m
    try {
        response = httpClient.newCall(request).execute();
        if (response.code() != 200) {
            fail("Invalid HTTP code status " + response.code() + " expected 200");
        }
        newUserId = response.body().string();

    } catch (IOException e) {
        fail(e.getMessage(), e);
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    return self();
}

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

License:Open Source License

private SELF create_user(String email, boolean success) {
    if (isBlank(email)) {
        throw new IllegalArgumentException("email must be defined.");
    }/*  w  ww .j  a va 2 s. c om*/
    if (success && StringUtils.isBlank(newUserId)) {
        retrive_a_new_id();
    }

    OkHttpClient httpClient = new OkHttpClient();
    RequestBody body = RequestBody.create(MediaType.parse("application/json"),
            ("{\"email\": \"" + email + "\"}").getBytes());
    String baseUrl = getBaseUrl();

    Request.Builder builder = new Request.Builder().post(body)
            .url(baseUrl + "/api/v1/user" + (newUserId != null ? "/" + newUserId : ""));
    if (isNotBlank(currentUserLogin)) {
        UserInfo currentUser = currentUsers.get(currentUserLogin);
        if (currentUser != null) {
            builder = HttpUserSupport.addBasicAuthentification(currentUser, builder);
        }
    }
    Request request = builder.build();
    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        if (success) {
            assertThat(response.code()).isEqualTo(201);
            JsonParser parser = new JsonParser();
            String bodyResponse = response.body().string();
            JsonObject json = (JsonObject) parser.parse(bodyResponse);
            String currentUsername = json.getAsJsonPrimitive("username").getAsString();
            String currentUserPassword = json.getAsJsonPrimitive("password").getAsString();
            String currentUserEmail = json.getAsJsonPrimitive("email").getAsString();
            String currentUserIdentifier = json.getAsJsonPrimitive("identifier").getAsString();
            String currentUserEntityIdentifier = json.getAsJsonPrimitive("entityIdentifier").getAsString();
            currentUsers.put(currentUsername, new UserInfo(currentUsername, currentUserIdentifier,
                    currentUserEntityIdentifier, currentUserPassword, currentUserEmail));
            if (isBlank(currentUserLogin)) {
                currentUserLogin = currentUsername;
            }
            Attachment privateKey = Attachment.plainText(bodyResponse).withTitle(currentUsername + " response");
            currentStep.addAttachment(privateKey);
        } else {
            assertThat(response.code()).isNotEqualTo(201);
        }
        response.body().close();
    } catch (IOException e) {
        if (success) {
            fail(e.getMessage(), e);
        }
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }
    return self();
}

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

License:Open Source License

private String getProjectConfiguration(String username, String projectConfigurationId) {
    UserInfo userInfo = currentUsers.get(username);
    Request.Builder builder = new Request.Builder().get()
            .url(getApiBaseUrl() + "/projectconfig/" + projectConfigurationId);
    Request request = HttpUserSupport.addBasicAuthentification(userInfo, builder).build();
    Response response = null;/*from w w w.  j  av  a 2  s .  c  om*/
    try {
        OkHttpClient httpClient = new OkHttpClient();
        response = httpClient.newCall(request).execute();
        assertThat(response.code()).isEqualTo(200);
        String body = response.body().string();
        return body;
    } 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 UserInfo createUser(UserInfo currentUser, String email) {

    RequestBody emptyBody = RequestBody.create(null, new byte[0]);
    Request.Builder builder = new Request.Builder().post(emptyBody).url(getApiBaseUrl() + "/user");
    if (currentUser != null) {
        builder = addBasicAuthentification(currentUser, builder);
    }//from  w  w  w.j a  v a2s  . co  m
    Request request = builder.build();
    Response response = null;
    String identifier = null;
    try {
        response = httpClient.newCall(request).execute();
        identifier = response.body().string();
        assertThat(identifier).isNotEmpty();
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response.body());
        }
    }

    RequestBody body = RequestBody.create(MediaType.parse("application/json"),
            ("{\"email\": \"" + email + "\"}").getBytes());
    builder = new Request.Builder().post(body).url(getApiBaseUrl() + "/user/" + identifier);
    if (currentUser != null) {
        builder = addBasicAuthentification(currentUser, builder);
    }
    request = builder.build();
    response = null;
    try {
        response = httpClient.newCall(request).execute();
        JsonParser parser = new JsonParser();
        String bodyResponse = response.body().string();
        JsonObject json = (JsonObject) parser.parse(bodyResponse);
        String currentUsername = json.getAsJsonPrimitive("username").getAsString();
        String currentUserPassword = json.getAsJsonPrimitive("password").getAsString();
        String currentUserEmail = json.getAsJsonPrimitive("email").getAsString();
        String currentUserIdentifier = json.getAsJsonPrimitive("identifier").getAsString();
        String currentUserEntityIdentifier = json.getAsJsonPrimitive("entityIdentifier").getAsString();
        UserInfo res = new UserInfo(currentUsername, currentUserIdentifier, currentUserEntityIdentifier,
                currentUserPassword, currentUserEmail);
        return res;

    } 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 String createProjectConfiguration(String projectName, StackConfigDto stackConfigDto,
        UserInfo currentUser) {//  w ww.  j  ava2  s  .  c  o m
    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;// ww  w  .  j  av  a 2  s. co m
    try {
        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;/*w ww .  j a va  2  s  . c o  m*/
    try {
        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 static Request.Builder createChangeUserOnProjectConfiguration(String apiBaseurl,
        String projectConfigurationId, String json, UserChangeProjectConfig userChangeProjectConfig) {
    RequestBody body = RequestBody.create(MediaType.parse("application/json"), json.getBytes());
    Request.Builder builder = new Request.Builder()
            .url(apiBaseurl + "/projectconfig/" + projectConfigurationId + "/user");
    if (userChangeProjectConfig == UserChangeProjectConfig.ADD) {
        builder = builder.put(body);/*  w  ww  .ja v a 2  s  . c o  m*/
    } else {
        builder = builder.delete(body);
    }
    return builder;

}

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;/*w ww . j av  a  2 s . com*/
    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

private boolean executeRequest(OkHttpClient httpClient, String url, String xmlBody, String login,
        String password) {/*w w  w. j a  v  a2s.co m*/
    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;
}