org.asynchttpclient.ListenableFuture Java Examples

The following examples show how to use org.asynchttpclient.ListenableFuture. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FlummiTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetAdminClientIndices() throws ExecutionException, InterruptedException, IOException {
    //Given
    final BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
    when(asyncHttpClient.preparePut(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setCharset(Charset.forName("UTF-8"))).thenReturn(boundRequestBuilder);
    final ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    final Response response = mock(Response.class);
    when(listenableFuture.get()).thenReturn(response);
    when(response.getStatusCode()).thenReturn(200);
    when(response.getResponseBody()).thenReturn("{\"acknowledged\":\"true\"}");
    final IndicesAdminClient indicesAdminClient = client.admin().indices();
    final CreateIndexRequestBuilder createIndexRequestBuilder = indicesAdminClient.prepareCreate("someIndexName");

    //When
    createIndexRequestBuilder.execute();

    //Then
    verify(asyncHttpClient).preparePut("http://someHost:9200/someIndexName");
    assertThat(indicesAdminClient, notNullValue());
}
 
Example #2
Source File: FlummiTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPrepareBulk() throws ExecutionException, InterruptedException, IOException {
    //Given
    final BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
    when(asyncHttpClient.preparePost(anyString())).thenReturn(boundRequestBuilder);
    final ListenableFuture listenableFuture = mock(ListenableFuture.class);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setCharset(Charset.forName("UTF-8"))).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    final Response response = mock(Response.class);
    when(listenableFuture.get()).thenReturn(response);
    when(response.getStatusCode()).thenReturn(200);
    when(response.getResponseBody()).thenReturn("{\"errors\":false}");
    final BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
    bulkRequestBuilder.add(new DeleteActionBuilder("someIndexName", "someId", "someType"));

    //When
    bulkRequestBuilder.execute();

    //Then
    verify(asyncHttpClient).preparePost("http://someHost:9200/_bulk");
}
 
Example #3
Source File: FlummiTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPrepareCount() throws ExecutionException, InterruptedException, IOException {
    //Given
    final BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
    when(asyncHttpClient.prepareGet(anyString())).thenReturn(boundRequestBuilder);
    final ListenableFuture listenableFuture = mock(ListenableFuture.class);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    final Response response = mock(Response.class);
    when(listenableFuture.get()).thenReturn(response);
    when(response.getStatusCode()).thenReturn(200);
    when(response.getResponseBody()).thenReturn("{\"count\":201}");
    final CountRequestBuilder countRequestBuilder = client.prepareCount("someIndexName");

    //When
    countRequestBuilder.execute();

    //Then
    verify(asyncHttpClient).prepareGet("http://someHost:9200/someIndexName/_count");
}
 
Example #4
Source File: SearchRequestBuilderTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddQueryToException() throws Exception {
    //given
    BoundRequestBuilder boundRequestBuilderMock = mock(BoundRequestBuilder.class);
    when(httpClient.preparePost("/some-index/_search")).thenReturn(boundRequestBuilderMock);
    when(boundRequestBuilderMock.setBody(any(String.class))).thenReturn(boundRequestBuilderMock);
    when(boundRequestBuilderMock.setCharset(Charset.forName("UTF-8"))).thenReturn(boundRequestBuilderMock);
    when(boundRequestBuilderMock.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilderMock);
    TimeoutException timeoutException = new TimeoutException();
    when(boundRequestBuilderMock.execute()).thenReturn(new ListenableFuture.CompletedFailure<>(timeoutException));

    //when
    JsonObject query = createSampleQuery();
    try {
        searchRequestBuilder.setQuery(query).execute();
    } catch (RuntimeException e) {
        //then
        assertThat(e.getCause().getCause(), is(timeoutException));
        assertThat(e.getMessage(), is("{\"query\":" + query.toString() + "}"));
    }

}
 
Example #5
Source File: AdminClientTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateIndicesAdminClient() throws ExecutionException, InterruptedException, IOException {
    //Given
    final BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
    when(httpClient.preparePut(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setCharset(Charset.forName("UTF-8"))).thenReturn(boundRequestBuilder);
    final ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    final Response response = mock(Response.class);
    when(listenableFuture.get()).thenReturn(response);
    when(response.getStatusCode()).thenReturn(200);
    when(response.getResponseBody()).thenReturn("{\"acknowledged\":\"true\"}");
    final IndicesAdminClient indicesAdminClient = adminClient.indices();
    final CreateIndexRequestBuilder createIndexRequestBuilder = indicesAdminClient.prepareCreate("someIndexName");

    //When
    createIndexRequestBuilder.execute();

    //Then
    verify(httpClient).preparePut("/someIndexName");
    assertThat(indicesAdminClient, notNullValue());
}
 
Example #6
Source File: AdminClientTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateClusterAdminClient() throws ExecutionException, InterruptedException, IOException {
    // Given
    final BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
    final ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
    final Response response = mock(Response.class);
    when(response.getStatusCode()).thenReturn(200);
    when(response.getResponseBody()).thenReturn("{\"status\":\"GREEN\", \"cluster_name\":\"someClusterName\", \"timed_out\":\"someTimedOut\"}");
    when(listenableFuture.get()).thenReturn(response);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    when(httpClient.prepareGet(anyString())).thenReturn(boundRequestBuilder);
    final ClusterAdminClient cluster = adminClient.cluster();
    final ClusterHealthRequestBuilder clusterHealthRequestBuilder = cluster.prepareHealth("someIndexName");

    //When
    clusterHealthRequestBuilder.execute();

    //Then
    Mockito.verify(httpClient).prepareGet("/_cluster/health/someIndexName");
    assertThat(cluster, notNullValue());
}
 
Example #7
Source File: FlummiTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPrepareGet() throws ExecutionException, InterruptedException, IOException {
    //Given
    final BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
    when(asyncHttpClient.prepareGet(anyString())).thenReturn(boundRequestBuilder);
    final ListenableFuture listenableFuture = mock(ListenableFuture.class);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    final Response response = mock(Response.class);
    when(listenableFuture.get()).thenReturn(response);
    when(response.getStatusCode()).thenReturn(200);
    when(response.getResponseBody()).thenReturn("{\"_id\":\"46711\"}");
    final GetRequestBuilder getRequestBuilder = client.prepareGet("someIndexName", "someDocumentType", "someProductId");

    //When
    getRequestBuilder.execute();

    //Then
    verify(asyncHttpClient).prepareGet("http://someHost:9200/someIndexName/someDocumentType/someProductId");
}
 
Example #8
Source File: FlummiTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPrepareDelete() throws ExecutionException, InterruptedException, IOException {
    //Given
    final BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
    when(asyncHttpClient.prepareDelete(anyString())).thenReturn(boundRequestBuilder);
    final ListenableFuture listenableFuture = mock(ListenableFuture.class);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    final Response response = mock(Response.class);
    when(listenableFuture.get()).thenReturn(response);
    when(response.getStatusCode()).thenReturn(200);
    final DeleteRequestBuilder deleteRequestBuilder = client.prepareDelete();
    deleteRequestBuilder.setIndexName("someIndexName");
    deleteRequestBuilder.setDocumentType("someDocumentType");
    deleteRequestBuilder.setId("someId");

    //When
    deleteRequestBuilder.execute();

    //Then
    verify(asyncHttpClient).prepareDelete("http://someHost:9200/someIndexName/someDocumentType/someId");
}
 
Example #9
Source File: FlummiTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPrepareAnalyze() throws ExecutionException, InterruptedException, IOException {
    final BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
    when(asyncHttpClient.prepareGet(anyString())).thenReturn(boundRequestBuilder);
    final ListenableFuture listenableFuture = mock(ListenableFuture.class);
    when(boundRequestBuilder.setCharset(Charset.forName("UTF-8"))).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    final Response response = mock(Response.class);
    when(response.getStatusCode()).thenReturn(200);
    when(response.getResponseBody()).thenReturn("{ \"tokens\": [] }");
    when(listenableFuture.get()).thenReturn(response);
    final AnalyzeRequestBuilder analyzeRequestBuilder = client.prepareAnalyze("hello world");

    //When
    analyzeRequestBuilder.execute();

    //Then
    verify(asyncHttpClient).prepareGet("http://someHost:9200/_analyze");
}
 
Example #10
Source File: TestAzureAsyncContainerProvider.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoesContainerExists() throws ExecutionException, InterruptedException {
  AzureStorageFileSystem parentClass = mock(AzureStorageFileSystem.class);
  AzureAuthTokenProvider authTokenProvider = getMockAuthTokenProvider();
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  Response response = mock(Response.class);
  when(response.getHeader(any(String.class))).thenReturn("");
  when(response.getStatusCode()).thenReturn(200);
  ListenableFuture<Response> future = mock(ListenableFuture.class);
  when(future.get()).thenReturn(response);
  when(client.executeRequest(any(Request.class))).thenReturn(future);

  AzureAsyncContainerProvider containerProvider = new AzureAsyncContainerProvider(
    client, "azurestoragev2hier", authTokenProvider, parentClass, true);
  assertTrue(containerProvider.doesContainerExists("container"));
}
 
Example #11
Source File: FlummiTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPrepareIndex() throws ExecutionException, InterruptedException, IOException {
    //Given
    final BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
    when(asyncHttpClient.preparePost(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setCharset(Charset.forName("UTF-8"))).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    final ListenableFuture listenableFuture = mock(ListenableFuture.class);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    final Response response = mock(Response.class);
    when(listenableFuture.get()).thenReturn(response);
    when(response.getStatusCode()).thenReturn(200);
    final IndexRequestBuilder indexRequestBuilder = client.prepareIndex();
    indexRequestBuilder.setSource(new JsonObject());

    //When
    indexRequestBuilder.execute();

    //Then
    verify(asyncHttpClient).preparePost("http://someHost:9200");
}
 
Example #12
Source File: FlummiTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetAdminClientCluster() throws ExecutionException, InterruptedException, IOException {
    // Given
    final BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
    final ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
    final Response response = mock(Response.class);
    when(response.getStatusCode()).thenReturn(200);
    when(response.getResponseBody()).thenReturn("{\"status\":\"GREEN\", \"cluster_name\":\"someClusterName\", \"timed_out\":\"someTimedOut\"}");
    when(listenableFuture.get()).thenReturn(response);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    when(asyncHttpClient.prepareGet(anyString())).thenReturn(boundRequestBuilder);
    final ClusterAdminClient cluster = client.admin().cluster();
    final ClusterHealthRequestBuilder clusterHealthRequestBuilder = cluster.prepareHealth("someIndexName");

    //When
    clusterHealthRequestBuilder.execute();

    //Then
    Mockito.verify(asyncHttpClient).prepareGet("http://someHost:9200/_cluster/health/someIndexName");
    assertThat(cluster, notNullValue());
}
 
Example #13
Source File: IndicesAdminClientTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPrepareCreate() throws ExecutionException, InterruptedException, IOException {
    //Given
    when(httpClient.preparePut(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setCharset(Charset.forName("UTF-8"))).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    final ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    final Response response = mock(Response.class);
    when(listenableFuture.get()).thenReturn(response);
    when(response.getStatusCode()).thenReturn(200);
    when(response.getResponseBody()).thenReturn("{\"acknowledged\":\"true\"}");
    final CreateIndexRequestBuilder createIndexRequestBuilder = indicesAdminClient.prepareCreate("someIndexName");

    //When
    createIndexRequestBuilder.execute();

    //Then
    verify(httpClient).preparePut("/someIndexName");
}
 
Example #14
Source File: IndicesAdminClientTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPrepareExists() throws ExecutionException, InterruptedException, IOException {
    //Given
    when(httpClient.prepareHead(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    final ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    final Response response = mock(Response.class);
    when(listenableFuture.get()).thenReturn(response);
    when(response.getStatusCode()).thenReturn(200);
    final IndicesExistsRequestBuilder indicesExistsRequestBuilder = indicesAdminClient.prepareExists("someIndexName");

    //When
    indicesExistsRequestBuilder.execute();

    //Then
    verify(httpClient).prepareHead("/someIndexName");
}
 
Example #15
Source File: AsyncHttpClientServiceShould.java    From mutual-tls-ssl with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void executeRequest() throws Exception {
    Response response = mock(Response.class);
    ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);

    when(httpClient.executeRequest(any(RequestBuilder.class))).thenReturn(listenableFuture);
    when(listenableFuture.toCompletableFuture()).thenReturn(CompletableFuture.completedFuture(response));

    when(response.getStatusCode()).thenReturn(200);
    when(response.getResponseBody()).thenReturn("Hello");

    ArgumentCaptor<RequestBuilder> requestBuilderArgumentCaptor = ArgumentCaptor.forClass(RequestBuilder.class);

    ClientResponse clientResponse = victim.executeRequest(HTTP_URL);

    assertThat(clientResponse.getStatusCode()).isEqualTo(200);
    assertThat(clientResponse.getResponseBody()).isEqualTo("Hello");

    verify(httpClient, times(1)).executeRequest(requestBuilderArgumentCaptor.capture());
    Request request = requestBuilderArgumentCaptor.getValue().build();
    assertThat(request.getUrl()).isEqualTo(HTTP_URL);
    assertThat(request.getMethod()).isEqualTo(GET_METHOD);
    assertThat(request.getHeaders().get(HEADER_KEY_CLIENT_TYPE)).isEqualTo(ASYNC_HTTP_CLIENT.getValue());
}
 
Example #16
Source File: HttpClientTest.java    From tac with MIT License 6 votes vote down vote up
@Test
public void test() throws InterruptedException, ExecutionException, TimeoutException {

    JSONObject data = new JSONObject();
    data.put("name", "ljinshuan");

    AsyncHttpClient asyncHttpClient = asyncHttpClient();

    ListenableFuture<Response> execute = asyncHttpClient.preparePost("http://localhost:8001/api/tac/execute/shuan")
        .addHeader("Content-Type", "application/json;charset=UTF-8").setBody(data.toJSONString()).execute();
    Response response = execute.get(10, TimeUnit.SECONDS);

    if (response.getStatusCode() == HttpConstants.ResponseStatusCodes.OK_200) {
        TacResult tacResult = JSONObject.parseObject(response.getResponseBody(), TacResult.class);

        System.out.println(tacResult);
    }
    System.out.println(response);
}
 
Example #17
Source File: TacPublishTestService.java    From tac with MIT License 6 votes vote down vote up
/**
 * test with http .
 *
 * @param instId
 * @param msCode
 * @param params
 * @return
 */
private TacResult<?> onlinePublishTestHttp(Long instId, String msCode, Map<String, Object> params) {

    AsyncHttpClient asyncHttpClient = asyncHttpClient();

    ListenableFuture<Response> execute = asyncHttpClient.preparePost(containerWebApi + "/" + msCode)
        .addHeader("Content-Type", "application/json;charset=UTF-8").setBody(JSONObject.toJSONString(params))
        .execute();
    Response response;
    try {
        response = execute.get(10, TimeUnit.SECONDS);
        if (response.getStatusCode() == HttpConstants.ResponseStatusCodes.OK_200) {
            TacResult tacResult = JSONObject.parseObject(response.getResponseBody(), TacResult.class);
            return tacResult;
        }
        log.error("onlinePublishTestHttp msCode:{} params:{} {}", msCode, params, response);
        throw new IllegalStateException("request engine error " + msCode);
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }

}
 
Example #18
Source File: IndicesAdminClientTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPrepareDelete() throws ExecutionException, InterruptedException {
    //Given
    when(httpClient.prepareDelete(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    final ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    final Response response = mock(Response.class);
    when(listenableFuture.get()).thenReturn(response);
    when(response.getStatusCode()).thenReturn(200);
    final DeleteIndexRequestBuilder deleteIndexRequestBuilder = indicesAdminClient.prepareDelete("someIndexName");

    //When
    deleteIndexRequestBuilder.execute();

    //Then
    verify(httpClient).prepareDelete("/someIndexName");
}
 
Example #19
Source File: AsyncHttpClientAspect2x.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@OnReturn
public static <T extends ListenableFutureMixin & ListenableFuture<?>> void onReturn(
        @BindReturn @Nullable T future,
        @BindTraveler @Nullable AsyncTraceEntry asyncTraceEntry) {
    if (asyncTraceEntry == null) {
        return;
    }
    asyncTraceEntry.stopSyncTimer();
    if (future == null) {
        asyncTraceEntry.end();
        return;
    }
    future.glowroot$setAsyncTraceEntry(asyncTraceEntry);
    future.addListener(new ExecuteRequestListener<T>(asyncTraceEntry, future),
            DirectExecutor.INSTANCE);
}
 
Example #20
Source File: WebhookTest.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Override
public <T> ListenableFuture<T> executeRequest(org.asynchttpclient.Request request,
                                              AsyncHandler<T> handler) {

  WebhookOnThrowableHandler<T> wrapped = new WebhookOnThrowableHandler<>(
      handler,
      new CountDownLatch(1));
  ListenableFuture<T> future = super.executeRequest(request, wrapped);
  try {
    future.get();
    future.done();
  } catch (InterruptedException | ExecutionException e) {
    // The future threw an exception, wait for onThrowable to complete.
    wrapped.waitForOnThrowableToFinish();
  }
  return future;
}
 
Example #21
Source File: Zendesk.java    From zendesk-java-client with Apache License 2.0 5 votes vote down vote up
private <T> ListenableFuture<T> submit(Request request, ZendeskAsyncCompletionHandler<T> handler) {
    if (logger.isDebugEnabled()) {
        if (request.getStringData() != null) {
            logger.debug("Request {} {}\n{}", request.getMethod(), request.getUrl(), request.getStringData());
        } else if (request.getByteData() != null) {
            logger.debug("Request {} {} {} {} bytes", request.getMethod(), request.getUrl(),
                    request.getHeaders().get("Content-type"), request.getByteData().length);
        } else {
            logger.debug("Request {} {}", request.getMethod(), request.getUrl());
        }
    }
    return client.executeRequest(request, handler);
}
 
Example #22
Source File: AsyncHttpRequest.java    From junit-servers with MIT License 5 votes vote down vote up
@Override
protected HttpResponse doExecute() throws Exception {
	final HttpUrl endpoint = getEndpoint();
	final String scheme = endpoint.getScheme();
	final String userInfo = null;
	final String host = endpoint.getHost();
	final int port = endpoint.getPort();
	final String path = Utf8UrlEncoder.encodePath(endpoint.getPath());
	final String query = null;
	final String fragment = null;
	final Uri uri = new Uri(scheme, userInfo, host, port, path, query, fragment);

	final String method = getMethod().getVerb();
	final RequestBuilder builder = new RequestBuilder(method, true).setUri(uri);

	handleQueryParameters(builder);
	handleBody(builder);
	handleHeaders(builder);
	handleCookies(builder);

	final Request request = builder.build();
	final ListenableFuture<Response> future = client.executeRequest(request);

	final long start = nanoTime();
	final Response response = future.get();
	final long duration = nanoTime() - start;

	return AsyncHttpResponseFactory.of(response, duration);
}
 
Example #23
Source File: Zendesk.java    From zendesk-java-client with Apache License 2.0 5 votes vote down vote up
public ListenableFuture<List<JobStatus<HashMap<String, Object>>>> getJobStatusesAsync(List<JobStatus> statuses) {
    List<String> ids = new ArrayList<>(statuses.size());
    for (JobStatus status : statuses) {
        ids.add(status.getId());
    }
    Class<JobStatus<HashMap<String, Object>>> clazz = (Class<JobStatus<HashMap<String, Object>>>)(Object)JobStatus.class;
    return submit(req("GET", tmpl("/job_statuses/show_many.json{?ids}").set("ids", ids)), handleList(clazz, "job_statuses"));
}
 
Example #24
Source File: TestAzureAsyncReader.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private AzureAsyncReader prepareAsyncReader(final String responseBody, final int responseCode) {
  // Prepare response
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  Response response = mock(Response.class);
  HttpResponseStatus status = mock(HttpResponseStatus.class);
  when(status.getStatusCode()).thenReturn(responseCode);
  when(response.getResponseBody()).thenReturn(responseBody);

  CompletableFuture<Response> future = new CompletableFuture<>(); //CompletableFuture.completedFuture(response);
  ListenableFuture<Response> resFuture = mock(ListenableFuture.class);
  when(resFuture.toCompletableFuture()).thenReturn(future);
  LocalDateTime versionDate = LocalDateTime.now(ZoneId.of("GMT")).minusDays(2);

  when(client.executeRequest(any(Request.class), any(AsyncCompletionHandler.class))).then(invocationOnMock -> {
    AsyncCompletionHandler<Response> responseHandler = invocationOnMock.getArgument(1, AsyncCompletionHandler.class);
    assertEquals(responseHandler.getClass(), BufferBasedCompletionHandler.class);
    responseHandler.onStatusReceived(status);
    try {
      responseHandler.onCompleted(response);
    } catch (Exception e) {
      future.completeExceptionally(e);
    }
    return resFuture;
  });

  AzureAsyncReader azureAsyncReader = spy(new AzureAsyncReader(
    "account", new Path("container/directory/file_00.parquet"),
    getMockAuthTokenProvider(), String.valueOf(versionDate.atZone(ZoneId.of("GMT")).toInstant().toEpochMilli()),
    true, client
  ));
  return azureAsyncReader;

}
 
Example #25
Source File: GracefulShutdownIT.java    From spring-boot-graceful-shutdown with Apache License 2.0 5 votes vote down vote up
@Test
public void inFlightRequestFailsAfterTimeout() throws InterruptedException {
    ListenableFuture<Response> response = sendRequestAndWaitForServerToStartProcessing();

    stopSpringBootApp();

    assertThatCode(response::get).hasCauseInstanceOf(IOException.class);
}
 
Example #26
Source File: NonGracefulShutdownIT.java    From spring-boot-graceful-shutdown with Apache License 2.0 5 votes vote down vote up
@Test
public void inFlightRequestFails() throws InterruptedException {
    ListenableFuture<Response> response = sendRequestAndWaitForServerToStartProcessing();

    stopSpringBootApp();

    assertThatCode(response::get).hasCauseInstanceOf(IOException.class);
}
 
Example #27
Source File: DRPCQueryResultPubscriberTest.java    From bullet-storm with Apache License 2.0 5 votes vote down vote up
private AsyncHttpClient mockClientWith(CompletableFuture<Response> future) {
    ListenableFuture<Response> mockListenable = (ListenableFuture<Response>) mock(ListenableFuture.class);
    doReturn(future).when(mockListenable).toCompletableFuture();

    BoundRequestBuilder mockBuilder = mock(BoundRequestBuilder.class);
    doReturn(mockListenable).when(mockBuilder).execute();
    // Return itself
    doReturn(mockBuilder).when(mockBuilder).setBody(anyString());

    AsyncHttpClient mockClient = mock(AsyncHttpClient.class);
    doReturn(mockBuilder).when(mockClient).preparePost(anyString());
    return mockClient;
}
 
Example #28
Source File: AsyncHttpCaller.java    From pampas with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Response> asyncCall(AsyncHttpRequest req, ServerInstance serverInstance) {
    final FullHttpRequest httpRequest = req.getFullHttpRequest();
    try {
        final AsyncHttpClient httpClient = this.client;
        BoundRequestBuilder requestBuilder = new BoundRequestBuilder(httpClient,
                httpRequest.method().name(), true);

        requestBuilder.setUri(Uri.create(serverInstance.toUri() + req.getRequestPath()));
        for (Map.Entry<String, String> headerEntry : httpRequest.headers()) {
            if (StringUtils.isNotEmpty(headerEntry.getKey())
                    && !"Host".equals(headerEntry.getKey())) {
                requestBuilder.addHeader(headerEntry.getKey(), headerEntry.getValue());
            }

        }
        requestBuilder.addHeader(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

        if (httpRequest.content() != null && httpRequest.content().isReadable()) {
            //请求body转换为ByteBuffer,并且设置为只读,ByteBuf复用 堆内存中的数据 zero copy
            ByteBuffer readOnlyBuffer = httpRequest.content().nioBuffer().asReadOnlyBuffer();
            requestBuilder.setBody(readOnlyBuffer);
        }
        ListenableFuture<Response> listenableFuture = requestBuilder.execute();
        return listenableFuture.toCompletableFuture();

    } catch (Exception ex) {
        log.warn("执行调用报错:{}", ex);
        CompletableFuture<Response> exceptionFuture = CompletableFuture.completedFuture(null);
        exceptionFuture.completeExceptionally(ex);
        return exceptionFuture;
    }
}
 
Example #29
Source File: ClickhouseWriterTest.java    From flink-clickhouse-sink with MIT License 5 votes vote down vote up
private void send(String data, String url, String basicCredentials, AtomicInteger counter) {
    String query = String.format("INSERT INTO %s VALUES %s ", "groot3.events", data);
    BoundRequestBuilder requestBuilder = asyncHttpClient.preparePost(url).setHeader("Authorization", basicCredentials);
    requestBuilder.setBody(query);
    ListenableFuture<Response> whenResponse = asyncHttpClient.executeRequest(requestBuilder.build());
    Runnable callback = () -> {
        try {
            Response response = whenResponse.get();
            System.out.println(Thread.currentThread().getName() + " " + response);

            if (response.getStatusCode() != 200) {
                System.out.println(Thread.currentThread().getName() + " try to retry...");
                int attempt = counter.incrementAndGet();
                if (attempt > MAX_ATTEMPT) {
                    System.out.println("Failed ");
                } else {
                    send(data, url, basicCredentials, counter);
                }
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    };

    Executor executor = ForkJoinPool.commonPool();
    whenResponse.addListener(callback, executor);
}
 
Example #30
Source File: CompletedFuture.java    From flummi with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableFuture<T> addListener(Runnable listener, Executor exec) {
    return null;
}