Example usage for com.squareup.okhttp RequestBody create

List of usage examples for com.squareup.okhttp RequestBody create

Introduction

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

Prototype

public static RequestBody create(final MediaType contentType, final File file) 

Source Link

Document

Returns a new request body that transmits the content of file .

Usage

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;/*from  ww w  . ja v a  2 s.  c  o m*/

    try {
        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 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. ja v  a2 s.  c  om*/
    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  w  w.jav  a2 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

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;//from   w  w w.  ja v a2  s  . c om
    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);//from w w  w  . j  av a  2  s  .  c om
    } else {
        builder = builder.delete(body);
    }
    return builder;

}

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  a 2s  .c  o  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;
}

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   w ww. j  a  v a2  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;
}

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.");
    }/*from  w  w  w . ja va2 s  .  c o m*/
    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.neorx.rest.NeoRxClient.java

License:Apache License

protected ObjectNode execRawCypher(String cypher, ObjectNode params) {

    try {//from   ww  w .j  a v  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.plugin.elb.a10.A10ClientImpl.java

License:Apache License

public Response execute(RequestBuilder b) {
    try {//w  w  w .ja  v a  2s. co m

        String method = b.getMethod();
        Preconditions.checkArgument(!Strings.isNullOrEmpty(method), "method argument must be passed");

        String url = null;

        Response resp;
        String format = b.getParams().getOrDefault("format", "xml");
        b = b.param("format", format);
        if (!b.hasBody()) {

            url = formatUrl(b.getParams(), format);
            FormEncodingBuilder fb = new FormEncodingBuilder().add("session_id", getAuthToken());
            for (Map.Entry<String, String> entry : b.getParams().entrySet()) {
                if (!entry.getValue().equals("format")) {
                    fb = fb.add(entry.getKey(), entry.getValue());
                }
            }
            resp = getClient().newCall(new Request.Builder().url(getUrl()).post(fb.build()).build()).execute();
        } else if (b.getXmlBody().isPresent()) {
            b = b.param("format", "xml");
            url = formatUrl(b.getParams(), "xml");
            String bodyAsString = new XMLOutputter(Format.getRawFormat()).outputString(b.getXmlBody().get());
            final MediaType XML = MediaType.parse("text/xml");

            resp = getClient().newCall(new Request.Builder().url(url)
                    .post(RequestBody.create(XML, bodyAsString)).header("Content-Type", "text/xml").build())
                    .execute();
        } else if (b.getJsonBody().isPresent()) {
            b = b.param("format", "json");
            url = formatUrl(b.getParams(), "json");
            String bodyAsString = mapper.writeValueAsString(b.getJsonBody().get());

            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            resp = getClient().newCall(new Request.Builder().url(url).post(

                    RequestBody.create(JSON, bodyAsString)).header("Content-Type", "application/json").build())
                    .execute();
        } else {
            throw new UnsupportedOperationException("body type not supported");
        }
        // the A10 API rather stupidly uses 200 responses even when there is
        // an error
        if (!resp.isSuccessful()) {
            logger.warn("response code={}", resp.code());
        }

        return resp;

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