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.bitfactory.mobileclimatemonitor.SlackReporter.java

License:Apache License

@Background
protected void sendValuesToSlack() {

    if (temperatureValue == 0) {
        return;/*from w w w  .j  a va 2s .com*/
    }

    if (humidityValue == 0) {
        return;
    }

    try {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("text",
                Helper.formatTemperature(temperatureValue) + "\n" + Helper.formatHumidity(humidityValue));
        jsonObject.put("channel", slackChannel);
        jsonObject.put("username", slackSenderName);
        jsonObject.put("icon_emoji", ":cubimal_chick:");

        MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

        Request request = new Request.Builder().url(new URL(slackWebhookUrl))
                .post(RequestBody.create(MEDIA_TYPE_JSON, jsonObject.toString())).build();

        new OkHttpClient().newCall(request).execute();

    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }

    temperatureValue = 0;
    humidityValue = 0;
}

From source file:io.fabric8.devops.connector.DevOpsConnector.java

License:Apache License

protected void createGerritRepo(String repoName, String gerritUser, String gerritPwd,
        String gerritGitInitialCommit, String gerritGitRepoDescription) throws Exception {

    // lets add defaults if not env vars
    final String username = Strings.isNullOrBlank(gerritUser) ? "admin" : gerritUser;
    final String password = Strings.isNullOrBlank(gerritPwd) ? "secret" : gerritPwd;

    log.info("A Gerrit git repo will be created for this name : " + repoName);

    String gerritAddress = KubernetesHelper.getServiceURL(kubernetes, ServiceNames.GERRIT, namespace, "http",
            true);//from   www.j av a  2 s .  co m
    log.info("Found gerrit address: " + gerritAddress + " for namespace: " + namespace
            + " on Kubernetes address: " + kubernetes.getMasterUrl());

    if (Strings.isNullOrBlank(gerritAddress)) {
        throw new Exception("No address for service " + ServiceNames.GERRIT + " in namespace: " + namespace
                + " on Kubernetes address: " + kubernetes.getMasterUrl());
    }

    String GERRIT_URL = gerritAddress + "/a/projects/" + repoName;

    OkHttpClient client = new OkHttpClient();
    if (isNotNullOrEmpty(gerritUser) && isNotNullOrEmpty(gerritPwd)) {
        client.setAuthenticator(new Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                List<Challenge> challenges = response.challenges();
                Request request = response.request();
                for (int i = 0, size = challenges.size(); i < size; i++) {
                    Challenge challenge = challenges.get(i);
                    if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                        continue;

                    String credential = Credentials.basic(username, password);
                    return request.newBuilder().header("Authorization", credential).build();
                }
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
    }

    System.out.println("Requesting : " + GERRIT_URL);

    try {
        CreateRepositoryDTO createRepoDTO = new CreateRepositoryDTO();
        createRepoDTO.setDescription(gerritGitRepoDescription);
        createRepoDTO.setName(repoName);
        createRepoDTO.setCreate_empty_commit(Boolean.valueOf(gerritGitInitialCommit));

        RequestBody body = RequestBody.create(JSON, MAPPER.writeValueAsString(createRepoDTO));
        Request request = new Request.Builder().post(body).url(GERRIT_URL).build();
        Response response = client.newCall(request).execute();
        System.out.println("responseBody : " + response.body().string());

    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (client != null && client.getConnectionPool() != null) {
            client.getConnectionPool().evictAll();
        }
    }
}

From source file:io.fabric8.docker.client.impl.BuildImage.java

License:Apache License

@Override
public OutputHandle fromTar(String path) {
    try {//  w  w w.j ava  2 s  . c o  m
        StringBuilder sb = new StringBuilder();
        sb.append(getOperationUrl());
        sb.append(Q).append(DOCKER_FILE).append(EQUALS).append(dockerFile);

        if (alwaysRemoveIntermediate) {
            sb.append(A).append(ALWAYS_REMOVE_INTERMEDIATE).append(EQUALS).append(alwaysRemoveIntermediate);
        } else {
            sb.append(A).append(REMOVE_INTERMEDIATE_ON_SUCCESS).append(EQUALS)
                    .append(removeIntermediateOnSuccess);
        }

        sb.append(A).append(PULL).append(EQUALS).append(pulling);
        sb.append(A).append(SUPRESS_VERBOSE_OUT).append(EQUALS).append(supressingVerboseOutput);
        sb.append(A).append(NOCACHE).append(EQUALS).append(noCache);

        if (cpuPeriodMicros >= 0) {
            sb.append(A).append(CPU_PERIOD).append(EQUALS).append(cpuPeriodMicros);
        }

        if (cpuQuotaMicros >= 0) {
            sb.append(A).append(CPU_QUOTA).append(EQUALS).append(cpuQuotaMicros);
        }

        if (cpuShares >= 0) {
            sb.append(A).append(CPU_SHARES).append(EQUALS).append(cpuShares);
        }

        if (cpus > 0) {
            sb.append(A).append(CPUS).append(EQUALS).append(cpus);
        }

        if (Utils.isNotNullOrEmpty(memorySize)) {
            sb.append(A).append(MEMORY).append(EQUALS).append(memorySize);
        }

        if (Utils.isNotNullOrEmpty(swapSize)) {
            sb.append(A).append(MEMSWAP).append(EQUALS).append(swapSize);
        }

        if (Utils.isNotNullOrEmpty(buildArgs)) {
            sb.append(A).append(BUILD_ARGS).append(EQUALS).append(buildArgs);
        }

        if (Utils.isNotNullOrEmpty(repositoryName)) {
            sb.append(A).append(REPOSITORY_NAME).append(EQUALS).append(repositoryName);
        }

        RequestBody body = RequestBody.create(MEDIA_TYPE_TAR, new File(path));
        Request request = new Request.Builder()
                .header("X-Registry-Config",
                        new String(Base64.encodeBase64(
                                JSON_MAPPER.writeValueAsString(config.getAuthConfigs()).getBytes("UTF-8")),
                                "UTF-8"))
                .post(body).url(sb.toString()).build();

        OkHttpClient clone = client.clone();
        clone.setReadTimeout(config.getImageBuildTimeout(), TimeUnit.MILLISECONDS);
        BuildImageHandle handle = new BuildImageHandle(out, config.getImageBuildTimeout(),
                TimeUnit.MILLISECONDS, listener);
        clone.newCall(request).enqueue(handle);
        return handle;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.docker.client.impl.ContainerInputOutputErrorHandle.java

License:Apache License

private void send(byte[] bytes) throws IOException {
    if (bytes.length > 0) {
        WebSocket ws = webSocketRef.get();
        if (ws != null) {
            byte[] toSend = new byte[bytes.length + 1];
            toSend[0] = 0;/*ww w.j  a  v a  2  s  .  c  o  m*/
            System.arraycopy(bytes, 0, toSend, 1, bytes.length);
            ws.sendMessage(RequestBody.create(WebSocket.BINARY, toSend));
        }
    }
}

From source file:io.fabric8.docker.client.impl.ContainerNamedOperationImpl.java

License:Apache License

@Override
public InputStream export() {
    try {/*from www .j av  a  2 s  .  c o  m*/
        StringBuilder sb = new StringBuilder();
        sb.append(getResourceUrl());
        RequestBody body = RequestBody.create(MEDIA_TYPE_TEXT, EMPTY);
        Request.Builder requestBuilder = new Request.Builder().post(body)
                .url(URLUtils.join(getResourceUrl().toString(), EXPORT_OPERATION));
        return handleResponseStream(requestBuilder, 200);
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.docker.client.impl.ContainerNamedOperationImpl.java

License:Apache License

@Override
public Boolean resize(int h, int w) {
    try {/*from   ww  w .  ja v  a 2 s . c o  m*/
        StringBuilder sb = new StringBuilder();
        sb.append(getResourceUrl());
        sb.append(Q).append("h").append(EQUALS).append(h);
        sb.append(A).append("w").append(EQUALS).append(w);
        RequestBody body = RequestBody.create(MEDIA_TYPE_TEXT, EMPTY);
        Request.Builder requestBuilder = new Request.Builder().post(body)
                .url(URLUtils.join(getResourceUrl().toString(), RESIZE_OPERATION));
        handleResponse(requestBuilder, 200);
        return true;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.docker.client.impl.ContainerNamedOperationImpl.java

License:Apache License

@Override
public Boolean start() {
    try {/*  w  w w.j  a v a2  s.c  o m*/
        StringBuilder sb = new StringBuilder();
        sb.append(getResourceUrl());
        RequestBody body = RequestBody.create(MEDIA_TYPE_TEXT, EMPTY);
        Request.Builder requestBuilder = new Request.Builder().post(body)
                .url(URLUtils.join(getResourceUrl().toString(), START_OPERATION));
        handleResponse(requestBuilder, 204);
        return true;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.docker.client.impl.ContainerNamedOperationImpl.java

License:Apache License

@Override
public Boolean stop(int time) {
    try {/*from   w w w. ja v a2  s  .  c  o  m*/
        StringBuilder sb = new StringBuilder();
        sb.append(getResourceUrl());
        sb.append(Q).append(TIMEOUT).append(EQUALS).append(time);
        RequestBody body = RequestBody.create(MEDIA_TYPE_TEXT, EMPTY);
        Request.Builder requestBuilder = new Request.Builder().post(body)
                .url(URLUtils.join(getResourceUrl().toString(), STOP_OPERATION));
        handleResponse(requestBuilder, 204);
        return true;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.docker.client.impl.ContainerNamedOperationImpl.java

License:Apache License

@Override
public Boolean restart(int time) {
    try {//from   w  w w  .ja va  2  s  . c  o m
        StringBuilder sb = new StringBuilder();
        sb.append(getResourceUrl());
        sb.append(Q).append(TIMEOUT).append(EQUALS).append(time);
        RequestBody body = RequestBody.create(MEDIA_TYPE_TEXT, EMPTY);
        Request.Builder requestBuilder = new Request.Builder().post(body)
                .url(URLUtils.join(getResourceUrl().toString(), RESTART_OPERATION));
        handleResponse(requestBuilder, 204);
        return true;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.docker.client.impl.ContainerNamedOperationImpl.java

License:Apache License

@Override
public Boolean kill(String signal) {
    try {//from w w w.  j a  v  a  2 s .co m
        StringBuilder sb = new StringBuilder();
        sb.append(getResourceUrl());
        sb.append(Q).append(SIGNAL).append(EQUALS).append(signal);
        RequestBody body = RequestBody.create(MEDIA_TYPE_TEXT, EMPTY);
        Request.Builder requestBuilder = new Request.Builder().post(body)
                .url(URLUtils.join(getResourceUrl().toString(), KILL_OPERATION));
        handleResponse(requestBuilder, 204);
        return true;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}