Search in sources :

Example 16 with CloseableHttpAsyncClient

use of org.apache.http.impl.nio.client.CloseableHttpAsyncClient in project elasticsearch by elastic.

the class RemoteScrollableHitSourceTests method sourceWithMockedRemoteCall.

/**
     * Creates a hit source that doesn't make the remote request and instead returns data from some files. Also requests are always returned
     * synchronously rather than asynchronously.
     */
@SuppressWarnings("unchecked")
private RemoteScrollableHitSource sourceWithMockedRemoteCall(boolean mockRemoteVersion, ContentType contentType, String... paths) throws Exception {
    URL[] resources = new URL[paths.length];
    for (int i = 0; i < paths.length; i++) {
        resources[i] = Thread.currentThread().getContextClassLoader().getResource("responses/" + paths[i].replace("fail:", ""));
        if (resources[i] == null) {
            throw new IllegalArgumentException("Couldn't find [" + paths[i] + "]");
        }
    }
    CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer(new Answer<Future<HttpResponse>>() {

        int responseCount = 0;

        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
            // Throw away the current thread context to simulate running async httpclient's thread pool
            threadPool.getThreadContext().stashContext();
            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0];
            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3];
            HttpEntityEnclosingRequest request = (HttpEntityEnclosingRequest) requestProducer.generateRequest();
            URL resource = resources[responseCount];
            String path = paths[responseCount++];
            ProtocolVersion protocolVersion = new ProtocolVersion("http", 1, 1);
            if (path.startsWith("fail:")) {
                String body = Streams.copyToString(new InputStreamReader(request.getEntity().getContent(), StandardCharsets.UTF_8));
                if (path.equals("fail:rejection.json")) {
                    StatusLine statusLine = new BasicStatusLine(protocolVersion, RestStatus.TOO_MANY_REQUESTS.getStatus(), "");
                    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
                    futureCallback.completed(httpResponse);
                } else {
                    futureCallback.failed(new RuntimeException(body));
                }
            } else {
                StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "");
                HttpResponse httpResponse = new BasicHttpResponse(statusLine);
                httpResponse.setEntity(new InputStreamEntity(FileSystemUtils.openFileURLStream(resource), contentType));
                futureCallback.completed(httpResponse);
            }
            return null;
        }
    });
    return sourceWithMockedClient(mockRemoteVersion, httpClient);
}
Also used : InputStreamReader(java.io.InputStreamReader) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) Matchers.containsString(org.hamcrest.Matchers.containsString) ProtocolVersion(org.apache.http.ProtocolVersion) URL(java.net.URL) BasicStatusLine(org.apache.http.message.BasicStatusLine) InputStreamEntity(org.apache.http.entity.InputStreamEntity) StatusLine(org.apache.http.StatusLine) BasicStatusLine(org.apache.http.message.BasicStatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) ScheduledFuture(java.util.concurrent.ScheduledFuture) Future(java.util.concurrent.Future) FutureCallback(org.apache.http.concurrent.FutureCallback)

Example 17 with CloseableHttpAsyncClient

use of org.apache.http.impl.nio.client.CloseableHttpAsyncClient in project spring-framework by spring-projects.

the class HttpComponentsAsyncClientHttpRequestFactoryTests method defaultSettingsOfHttpAsyncClientLostOnExecutorCustomization.

@Test
public void defaultSettingsOfHttpAsyncClientLostOnExecutorCustomization() throws Exception {
    CloseableHttpAsyncClient client = HttpAsyncClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(1234).build()).build();
    HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory(client);
    URI uri = new URI(baseUrl + "/status/ok");
    HttpComponentsAsyncClientHttpRequest request = (HttpComponentsAsyncClientHttpRequest) factory.createAsyncRequest(uri, HttpMethod.GET);
    assertNull("No custom config should be set with a custom HttpClient", request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG));
    factory.setConnectionRequestTimeout(4567);
    HttpComponentsAsyncClientHttpRequest request2 = (HttpComponentsAsyncClientHttpRequest) factory.createAsyncRequest(uri, HttpMethod.GET);
    Object requestConfigAttribute = request2.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG);
    assertNotNull(requestConfigAttribute);
    RequestConfig requestConfig = (RequestConfig) requestConfigAttribute;
    assertEquals(4567, requestConfig.getConnectionRequestTimeout());
    // No way to access the request config of the HTTP client so no way to "merge" our customizations
    assertEquals(-1, requestConfig.getConnectTimeout());
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) URI(java.net.URI) Test(org.junit.Test)

Example 18 with CloseableHttpAsyncClient

use of org.apache.http.impl.nio.client.CloseableHttpAsyncClient in project uavstack by uavorg.

the class HttpService method httpclientAsyncDoubleTest.

@GET
@Path("httpclientAsync_double_test")
public String httpclientAsyncDoubleTest() {
    httpclientAsynctest();
    final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
    HttpUriRequest httpMethod = new HttpGet("http://weibo.com/");
    client.start();
    client.execute(httpMethod, new FutureCallback<HttpResponse>() {

        @Override
        public void completed(HttpResponse result) {
            System.out.println(client.getClass().getName() + "---OK");
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void failed(Exception ex) {
            System.out.println(client.getClass().getName() + "---FAIL");
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void cancelled() {
            System.out.println(client.getClass().getName() + "---CANCEL");
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    return "httpclientAsync_double_test";
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 19 with CloseableHttpAsyncClient

use of org.apache.http.impl.nio.client.CloseableHttpAsyncClient in project uavstack by uavorg.

the class HttpService method httpclientAsynctest.

/**
 * 异步测试用例
 *
 * @return
 */
@GET
@Path("httpclientAsynctest")
public String httpclientAsynctest() {
    final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
    HttpUriRequest httpMethod = new HttpGet("https://www.baidu.com/");
    client.start();
    client.execute(httpMethod, new FutureCallback<HttpResponse>() {

        @Override
        public void completed(HttpResponse result) {
            System.out.println(client.getClass().getName() + "---OK");
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void failed(Exception ex) {
            System.out.println(client.getClass().getName() + "---FAIL");
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void cancelled() {
            System.out.println(client.getClass().getName() + "---CANCEL");
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    // }
    return "httpclientAsynctest success";
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 20 with CloseableHttpAsyncClient

use of org.apache.http.impl.nio.client.CloseableHttpAsyncClient in project tutorials by eugenp.

the class HttpAsyncClientLiveTest method whenUseHttpAsyncClient_thenCorrect.

// tests
@Test
public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
    final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();
    final HttpGet request = new HttpGet(HOST);
    final Future<HttpResponse> future = client.execute(request, null);
    final HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) HttpResponse(org.apache.http.HttpResponse) Test(org.junit.Test)

Aggregations

CloseableHttpAsyncClient (org.apache.http.impl.nio.client.CloseableHttpAsyncClient)34 HttpResponse (org.apache.http.HttpResponse)18 IOException (java.io.IOException)13 HttpGet (org.apache.http.client.methods.HttpGet)12 Test (org.junit.Test)8 HttpHost (org.apache.http.HttpHost)7 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)6 Future (java.util.concurrent.Future)5 InputStreamReader (java.io.InputStreamReader)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 GET (javax.ws.rs.GET)4 Path (javax.ws.rs.Path)4 ClientProtocolException (org.apache.http.client.ClientProtocolException)4 RequestConfig (org.apache.http.client.config.RequestConfig)4 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)4 FutureCallback (org.apache.http.concurrent.FutureCallback)4 HttpAsyncRequestProducer (org.apache.http.nio.protocol.HttpAsyncRequestProducer)4 Before (org.junit.Before)4 URL (java.net.URL)3 HttpEntity (org.apache.http.HttpEntity)3