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.commons.utils.docker.DockerSupport.java

License:Open Source License

private boolean tryRequest(HttpUrl url, OkHttpClient httpClient, ServiceIsUp serviceIsUp) {
    Response response = null;/* w w  w .j  a  va  2s.com*/
    try {
        Request request = new Request.Builder().url(url).get().build();
        Call call = httpClient.newCall(request);
        response = call.execute();
        boolean isSuccesseful = serviceIsUp.accept(response);
        response.body().close();
        return isSuccesseful;
    } catch (IOException e) {
        return false;
    } finally {
        if (response != null) {
            try {
                response.body().close();
            } catch (IOException e) {
                LOGGER.warn("Unable to close response.");
            }
        }
    }
}

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 w w . j a va 2 s  .c  om
    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.  ja va  2 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.promagent.it.SpringIT.java

License:Apache License

/**
 * Run some HTTP queries against a Docker container from image promagent/spring-promagent.
 * <p/>/*www  .j  a va 2s .c om*/
 * The Docker container is started by the maven-docker-plugin when running <tt>mvn verify -Pspring</tt>.
 */
@Test
public void testSpring() throws Exception {
    OkHttpClient client = new OkHttpClient();
    Request metricsRequest = new Request.Builder().url(System.getProperty("promagent.url") + "/metrics")
            .build();

    // Execute two POST requests
    Response restResponse = client.newCall(makePostRequest("Frodo", "Baggins")).execute();
    assertEquals(201, restResponse.code());
    restResponse = client.newCall(makePostRequest("Bilbo", "Baggins")).execute();
    assertEquals(201, restResponse.code());

    // Query Prometheus metrics from promagent
    Response metricsResponse = client.newCall(metricsRequest).execute();
    String[] metricsLines = metricsResponse.body().string().split("\n");

    String httpRequestsTotal = Arrays.stream(metricsLines).filter(m -> m.contains("http_requests_total"))
            .filter(m -> m.contains("method=\"POST\"")).filter(m -> m.contains("path=\"/people\""))
            .filter(m -> m.contains("status=\"201\"")).findFirst()
            .orElseThrow(() -> new Exception("http_requests_total metric not found."));

    assertTrue(httpRequestsTotal.endsWith("2.0"), "Value should be 2.0 for " + httpRequestsTotal);

    String sqlQueriesTotal = Arrays.stream(metricsLines).filter(m -> m.contains("sql_queries_total"))
            // The following regular expression tests for this string, but allows the parameters 'id', 'fist_name', 'last_name' to change order:
            // query="insert into person (first_name, last_name, id)"
            .filter(m -> m.matches(
                    ".*query=\"insert into person \\((?=.*id)(?=.*first_name)(?=.*last_name).*\\) values \\(...\\)\".*"))
            .filter(m -> m.contains("method=\"POST\"")).filter(m -> m.contains("path=\"/people\"")).findFirst()
            .orElseThrow(() -> new Exception("sql_queries_total metric not found."));

    assertTrue(sqlQueriesTotal.endsWith("2.0"), "Value should be 2.0 for " + sqlQueriesTotal);
}

From source file:io.promagent.it.SpringIT.java

License:Apache License

private Request makePostRequest(String firstName, String lastName) {
    return new Request.Builder().url(System.getProperty("deployment.url") + "/people")
            .method("POST",
                    RequestBody.create(MediaType.parse("application/json"),
                            "{  \"firstName\" : \"" + firstName + "\",  \"lastName\" : \"" + lastName + "\" }"))
            .build();/*from  w  w w .j  ava2  s  . co m*/
}

From source file:jonas.tool.saveForOffline.FaviconFetcher.java

License:Open Source License

private BitmapFactory.Options getBitmapDimensFromUrl(String url) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;/*from   w  ww .  j ava 2s . com*/

    Request request = new Request.Builder().url(url).build();

    try {
        Response response = client.newCall(request).execute();
        InputStream is = response.body().byteStream();

        BitmapFactory.decodeStream(is, null, options);

        response.body().close();
        is.close();

        return options;

    } catch (IllegalArgumentException | IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:lumbermill.internal.elasticsearch.ElasticSearchOkHttpClientImpl.java

License:Apache License

protected void doOkHttpPost(RequestContext requestCtx) {
    RequestBody body = RequestBody.create(TEXT, requestCtx.signableRequest.payload().get());
    Request request = new Request.Builder().url(url).post(body)
            .headers(Headers.of(requestCtx.signableRequest.headers())).build();

    // Add some sanity logging to be able to figure out the load
    if (LOGGER.isDebugEnabled()) {
        int requestsInQueue = client.getDispatcher().getQueuedCallCount();
        int requestsInProgress = client.getDispatcher().getRunningCallCount();
        if (requestsInQueue > 0) {
            LOGGER.debug("There are {} requests waiting to be processed", requestsInQueue);
        }/*from w w w .  j  a va  2s  .  c om*/
        if (requestsInProgress > 0) {
            LOGGER.debug("There are {} requests currently executing", requestsInProgress);
        }
    }

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            requestCtx.error(IndexFailedException.ofIOException(e));
        }

        @Override
        public void onResponse(Response response) throws IOException {
            handleResponse(requestCtx, response);
        }
    });
}

From source file:net.yatomiya.e4.util.HttpUtils.java

License:Open Source License

public static Request.Builder createRequestBuilder(HttpUrl url, Date lastModifiedSince) {
    Request.Builder builder = new Request.Builder();
    builder.url(url);//from   w  w w  . j  av  a  2  s  .  c  o m
    addLastModifiedHeader(builder, lastModifiedSince);
    return builder;
}

From source file:net.yatomiya.nicherry.services.bbs.PostMessageHandler.java

License:Open Source License

public Call execute(ThreadProcessor processor, boolean isSynchronous, String name, String mail, String body,
        Map<String, String> additionalParams) {
    this.processor = processor;
    this.isSynchronous = isSynchronous;
    this.name = name;
    this.mail = mail;
    this.body = body;

    executeTime = JUtils.getCurrentTime();

    EUtils.get(EventService.class).send(BBSService.Event.Post.START, getModel());

    BBSService bbsSrv = processor.getManager().getBBSService();
    BBSHttpClient client = bbsSrv.getHttpClient();

    ThreadId threadId = getModel().getId();
    MBoard board = bbsSrv.getBoard(threadId.getBoardId());
    String hostUrl = HttpUtils.getHostUrl(board.getUrl());
    String postUrl = hostUrl + "/test/bbs.cgi";

    Request.Builder builder = new Request.Builder();
    builder.url(postUrl);//w  w  w . j av  a2s  .  c  o  m

    Map<String, String> valueMap = new HashMap<>();
    valueMap.put("bbs", threadId.getBoardId().getIdValue());
    valueMap.put("key", threadId.getIdValue());
    valueMap.put("time", String.valueOf((JUtils.getCurrentTime() / 1000) - 60));
    valueMap.put("submit", "??");
    valueMap.put("FROM", name);
    valueMap.put("mail", mail);
    valueMap.put("MESSAGE", body);
    if (additionalParams != null)
        valueMap.putAll(additionalParams);
    String valueStr = HttpUtils.buildFormPostData(valueMap, NConstants.CHARSET_SHIFT_JIS);

    builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=Shift_JIS"),
            StringUtils.getBytes(valueStr, NConstants.CHARSET_SHIFT_JIS)));

    builder.header("Referer", board.getUrl());

    Request request = builder.build();

    Callback callback = new Callback() {
        @Override
        public void onResponse(Response response) throws IOException {
            EUtils.asyncExec(() -> doOnResponse(response));
        }

        @Override
        public void onFailure(Request request, IOException e) {
            EUtils.asyncExec(() -> doOnFailure(request, e));
        }
    };
    httpCall = client.execute(request, callback, isSynchronous);

    postEvent = new PostMessageEvent(name, mail, body);

    return httpCall;
}

From source file:org.bitcoinj_extra.net.discovery.HttpDiscovery.java

License:Apache License

@Override
public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit)
        throws PeerDiscoveryException {
    try {//from  ww w . j  a  v a  2  s.c  o  m
        HttpUrl.Builder url = HttpUrl.get(details.uri).newBuilder();
        if (services != 0)
            url.addQueryParameter("srvmask", Long.toString(services));
        Request.Builder request = new Request.Builder();
        request.url(url.build());
        request.addHeader("User-Agent", VersionMessage.LIBRARY_SUBVER); // TODO Add main version.
        log.info("Requesting seeds from {}", url);
        Response response = client.newCall(request.build()).execute();
        if (!response.isSuccessful())
            throw new PeerDiscoveryException(
                    "HTTP request failed: " + response.code() + " " + response.message());
        InputStream stream = response.body().byteStream();
        GZIPInputStream zip = new GZIPInputStream(stream);
        PeerSeedProtos.SignedPeerSeeds proto = PeerSeedProtos.SignedPeerSeeds.parseDelimitedFrom(zip);
        stream.close();
        return protoToAddrs(proto);
    } catch (PeerDiscoveryException e1) {
        throw e1;
    } catch (Exception e) {
        throw new PeerDiscoveryException(e);
    }
}