Search in sources :

Example 1 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project crate by crate.

the class BlobSslEnabledITest method uploadSmallBlob.

private String uploadSmallBlob() throws IOException {
    String digest = "c520e6109835c876fd98636efec43dd61634b7d3";
    CloseableHttpResponse response = put(blobUri(digest), StringUtils.repeat("a", 1500));
    assertThat(response.getStatusLine().getStatusCode(), is(201));
    return digest;
}
Also used : CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 2 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project weixin-java-tools by chanjarster.

the class SimpleGetRequestExecutor method execute.

@Override
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, ClientProtocolException, IOException {
    if (queryParam != null) {
        if (uri.indexOf('?') == -1) {
            uri += '?';
        }
        uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
    }
    HttpGet httpGet = new HttpGet(uri);
    if (httpProxy != null) {
        RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
        httpGet.setConfig(config);
    }
    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
        WxError error = WxError.fromJson(responseContent);
        if (error.getErrorCode() != 0) {
            throw new WxErrorException(error);
        }
        return responseContent;
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) WxError(me.chanjar.weixin.common.bean.result.WxError) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) WxErrorException(me.chanjar.weixin.common.exception.WxErrorException)

Example 3 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project cryptomator by cryptomator.

the class WelcomeController method checkForUpdates.

private void checkForUpdates() {
    checkForUpdatesStatus.setText(localization.getString("welcome.checkForUpdates.label.currentlyChecking"));
    checkForUpdatesIndicator.setVisible(true);
    asyncTaskService.asyncTaskOf(() -> {
        RequestConfig requestConfig = //
        RequestConfig.custom().setConnectTimeout(//
        5000).setConnectionRequestTimeout(//
        5000).setSocketTimeout(//
        5000).build();
        HttpClientBuilder httpClientBuilder = //
        HttpClients.custom().disableCookieManagement().setDefaultRequestConfig(//
        requestConfig).setUserAgent("Cryptomator VersionChecker/" + ApplicationVersion.orElse("SNAPSHOT"));
        LOG.debug("Checking for updates...");
        try (CloseableHttpClient client = httpClientBuilder.build()) {
            HttpGet request = new HttpGet("https://cryptomator.org/downloads/latestVersion.json");
            try (CloseableHttpResponse response = client.execute(request)) {
                if (response.getStatusLine().getStatusCode() == 200 && response.getEntity() != null) {
                    try (InputStream in = response.getEntity().getContent()) {
                        Gson gson = new GsonBuilder().setLenient().create();
                        Reader utf8Reader = new InputStreamReader(in, StandardCharsets.UTF_8);
                        Map<String, String> map = gson.fromJson(utf8Reader, new TypeToken<Map<String, String>>() {
                        }.getType());
                        if (map != null) {
                            this.compareVersions(map);
                        }
                    }
                }
            }
        }
    }).andFinally(() -> {
        checkForUpdatesStatus.setText("");
        checkForUpdatesIndicator.setVisible(false);
    }).run();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) InputStreamReader(java.io.InputStreamReader) GsonBuilder(com.google.gson.GsonBuilder) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) Gson(com.google.gson.Gson) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) TypeToken(com.google.gson.reflect.TypeToken) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 4 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project pinot by linkedin.

the class DruidThroughput method main.

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);
    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {

            @Override
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
                    post.addHeader("content-type", "application/json");
                    CloseableHttpResponse res;
                    while (true) {
                        try (BufferedReader reader = new BufferedReader(new FileReader(QUERY_FILE_DIR + File.separator + random.nextInt(numQueries) + ".json"))) {
                            int length = reader.read(BUFFER);
                            post.setEntity(new StringEntity(new String(BUFFER, 0, length)));
                        }
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: " + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) IOException(java.io.IOException) StringEntity(org.apache.http.entity.StringEntity) AtomicLong(java.util.concurrent.atomic.AtomicLong) Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader)

Example 5 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project pinot by linkedin.

the class PinotResponseTime method main.

public static void main(String[] args) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost("http://localhost:8099/query");
        CloseableHttpResponse res;
        if (STORE_RESULT) {
            File dir = new File(RESULT_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
        int length;
        // Make sure all segments online
        System.out.println("Test if number of records is " + RECORD_NUMBER);
        post.setEntity(new StringEntity("{\"pql\":\"select count(*) from tpch_lineitem\"}"));
        while (true) {
            System.out.print('*');
            res = client.execute(post);
            boolean valid;
            try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) {
                length = in.read(BUFFER);
                valid = new String(BUFFER, 0, length, "UTF-8").contains("\"value\":\"" + RECORD_NUMBER + "\"");
            }
            res.close();
            if (valid) {
                break;
            } else {
                Thread.sleep(5000);
            }
        }
        System.out.println("Number of Records Test Passed");
        // Start Benchmark
        for (int i = 0; i < QUERIES.length; i++) {
            System.out.println("--------------------------------------------------------------------------------");
            System.out.println("Start running query: " + QUERIES[i]);
            post.setEntity(new StringEntity("{\"pql\":\"" + QUERIES[i] + "\"}"));
            // Warm-up Rounds
            System.out.println("Run " + WARMUP_ROUND + " times to warm up cache...");
            for (int j = 0; j < WARMUP_ROUND; j++) {
                res = client.execute(post);
                if (!isValid(res, null)) {
                    System.out.println("\nInvalid Response, Sleep 20 Seconds...");
                    Thread.sleep(20000);
                }
                res.close();
                System.out.print('*');
            }
            System.out.println();
            // Test Rounds
            int[] time = new int[TEST_ROUND];
            int totalTime = 0;
            int validIdx = 0;
            System.out.println("Run " + TEST_ROUND + " times to get average time...");
            while (validIdx < TEST_ROUND) {
                long startTime = System.currentTimeMillis();
                res = client.execute(post);
                long endTime = System.currentTimeMillis();
                boolean valid;
                if (STORE_RESULT && validIdx == 0) {
                    valid = isValid(res, RESULT_DIR + File.separator + i + ".json");
                } else {
                    valid = isValid(res, null);
                }
                if (!valid) {
                    System.out.println("\nInvalid Response, Sleep 20 Seconds...");
                    Thread.sleep(20000);
                    res.close();
                    continue;
                }
                res.close();
                time[validIdx] = (int) (endTime - startTime);
                totalTime += time[validIdx];
                System.out.print(time[validIdx] + "ms ");
                validIdx++;
            }
            System.out.println();
            // Process Results
            double avgTime = (double) totalTime / TEST_ROUND;
            double stdDev = 0;
            for (int temp : time) {
                stdDev += (temp - avgTime) * (temp - avgTime) / TEST_ROUND;
            }
            stdDev = Math.sqrt(stdDev);
            System.out.println("The average response time for the query is: " + avgTime + "ms");
            System.out.println("The standard deviation is: " + stdDev);
        }
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) BufferedInputStream(java.io.BufferedInputStream) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) File(java.io.File)

Aggregations

CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)1314 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)502 HttpGet (org.apache.http.client.methods.HttpGet)485 Test (org.junit.Test)370 IOException (java.io.IOException)362 HttpPost (org.apache.http.client.methods.HttpPost)286 HttpEntity (org.apache.http.HttpEntity)248 StringEntity (org.apache.http.entity.StringEntity)229 JsonNode (com.fasterxml.jackson.databind.JsonNode)126 StatusLine (org.apache.http.StatusLine)121 URI (java.net.URI)118 InputStream (java.io.InputStream)112 ArrayList (java.util.ArrayList)87 Deployment (org.activiti.engine.test.Deployment)87 RequestConfig (org.apache.http.client.config.RequestConfig)87 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)87 HttpPut (org.apache.http.client.methods.HttpPut)79 Map (java.util.Map)75 Header (org.apache.http.Header)75 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)73