com.ning.http.client.ListenableFuture Java Examples

The following examples show how to use com.ning.http.client.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: TestServerFixture.java    From fixd with Apache License 2.0 6 votes vote down vote up
@Test
public void testUponWithTimeout() throws Exception {
    
    server.handle(Method.GET, "/subscribe")
          .with(200, "text/plain", "message: :message")
          .upon(Method.GET, "/broadcast/:message")
          .withTimeout(100, TimeUnit.MILLISECONDS);
    
    ListenableFuture<Response> f = client.prepareGet("http://localhost:8080/subscribe").execute();
    
    /*
     * If the process didn't timeout, the subscribe request
     * would wait indefinitely, as no broadcast requests
     * are being made.
     */
    assertEquals(408, f.get().getStatusCode());
}
 
Example #2
Source File: AsyncHttpClientAspect1x.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@OnReturn
public static <T extends ListenableFutureMixin & ListenableFuture<?>> void onReturn(
        final @BindReturn @Nullable T future,
        final @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 #3
Source File: LoadBalancerClientImpl.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public SingularityCheckingUpstreamsUpdate getLoadBalancerServiceStateForRequest(
  String singularityRequestId
)
  throws IOException, InterruptedException, ExecutionException, TimeoutException {
  final String loadBalancerStateUri = getLoadBalancerStateUri(singularityRequestId);
  final BoundRequestBuilder requestBuilder = httpClient.prepareGet(
    loadBalancerStateUri
  );
  final Request request = requestBuilder.build();
  LOG.debug(
    "Sending load balancer {} request for {} to {}",
    request.getMethod(),
    singularityRequestId,
    request.getUrl()
  );
  ListenableFuture<Response> future = httpClient.executeRequest(request);
  Response response = future.get(loadBalancerTimeoutMillis, TimeUnit.MILLISECONDS);
  LOG.debug(
    "Load balancer {} request {} returned with code {}",
    request.getMethod(),
    singularityRequestId,
    response.getStatusCode()
  );
  Optional<BaragonServiceState> maybeBaragonServiceState = Optional.ofNullable(
    objectMapper.readValue(response.getResponseBodyAsBytes(), BaragonServiceState.class)
  );
  return new SingularityCheckingUpstreamsUpdate(
    maybeBaragonServiceState,
    singularityRequestId
  );
}
 
Example #4
Source File: RpcCall.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private void postRequest(Map<String, Object> request, Runnable completeHandler) {
    try {
        // we fire this request off asynchronously and let the completeHandler
        // process any response as necessary (can be null)
        String resultWrite = writeJson(request);
        logger.debug("Write JSON: {}", resultWrite);
        ListenableFuture<Response> future = client.preparePost(uri).setBody(resultWrite)
                .setHeader("content-type", "application/json").setHeader("accept", "application/json")
                .execute(new AsyncCompletionHandler<Response>() {
                    @Override
                    public Response onCompleted(Response response) throws Exception {
                        logger.debug("Read JSON: {}", response.getResponseBody());
                        Map<String, Object> json = readJson(response.getResponseBody());

                        // if we get an error then throw an exception to stop the
                        // completion handler getting executed
                        if (json.containsKey("error")) {
                            throw new RpcException(json.get("error").toString());
                        }

                        processResponse(json);
                        return response;
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        logger.error("Error handling POST response from XBMC", t);
                    }
                });

        // add the future listener to handle the response once this request completes
        if (completeHandler != null) {
            future.addListener(completeHandler, client.getConfig().executorService());
        }
    } catch (Exception e) {
        logger.error("Failed sending POST request to XBMC", e);
    }
}
 
Example #5
Source File: TestServerFixture.java    From fixd with Apache License 2.0 5 votes vote down vote up
@Test
public void testUponAndMarshallingWithoutHandler() throws Exception {
    
    server.marshal("application/json")
          .with(new JSONMarshaller());
    
    server.handle(Method.GET, "/subscribe")
          .with(200, "application/json", new SimplePojo("marshalledJSON"))
          .upon(Method.PUT, "/broadcast");
  
    final List<String> broadcasts = new ArrayList<String>();
    ListenableFuture<Integer> f = client.prepareGet("http://localhost:8080/subscribe")
          .execute(new AddToListOnBodyPartReceivedHandler(broadcasts));
    
    /* need some time for the above request to complete
     * before the broadcast requests can start */
    Thread.sleep(100);
    
    for (int i = 0; i < 2; i++) {

        AsyncHttpClient otherClient = new AsyncHttpClient();
        try {
            otherClient.preparePut("http://localhost:8080/broadcast").execute().get();
        
            /* sometimes the last broadcast request is not
             * finished before f.done() is called */
            Thread.sleep(200);
        } finally {
            otherClient.close();
        }
    }
    
    f.done(null);
    assertEquals("[{\"val\":\"marshalledJSON\"}, {\"val\":\"marshalledJSON\"}]", 
            broadcasts.toString());
}
 
Example #6
Source File: TestServerFixture.java    From fixd with Apache License 2.0 5 votes vote down vote up
@Test
public void testUponWithRequestHandler() throws Exception {
    
    server.handle(Method.GET, "/subscribe")
          .with(new HttpRequestHandler() {
               public void handle(HttpRequest request, HttpResponse response) {
                   response.setStatusCode(200);
                   response.setContentType("text/plain");
                   response.setBody("message: " + request.getBody());
               }
          })
          .upon(Method.PUT, "/broadcast");
    
    final List<String> broadcasts = new ArrayList<String>();
    ListenableFuture<Integer> f = client.prepareGet("http://localhost:8080/subscribe")
          .execute(new AddToListOnBodyPartReceivedHandler(broadcasts));
    
    /* need some time for the above request to complete
     * before the broadcast requests can start */
    Thread.sleep(100);
    
    for (int i = 0; i < 2; i++) {

        AsyncHttpClient otherClient = new AsyncHttpClient();
        try {
            otherClient.preparePut("http://localhost:8080/broadcast")
                    .setBody("hello" + i)
                    .execute().get();
        
            /* sometimes the last broadcast request is not
             * finished before f.done() is called */
            Thread.sleep(200);
        } finally {
            otherClient.close();
        }
    }
    
    f.done(null);
    assertEquals("[message: hello0, message: hello1]", broadcasts.toString());
}
 
Example #7
Source File: TestServerFixture.java    From fixd with Apache License 2.0 5 votes vote down vote up
@Test
public void testUponUsingRequestBody() throws Exception {
    
    server.handle(Method.GET, "/subscribe")
          .with(200, "text/plain", "message: [request.body]")
          .upon(Method.PUT, "/broadcast");
    
    final List<String> broadcasts = new ArrayList<String>();
    ListenableFuture<Integer> f = client.prepareGet("http://localhost:8080/subscribe")
          .execute(new AddToListOnBodyPartReceivedHandler(broadcasts));
    
    /* need some time for the above request to complete
     * before the broadcast requests can start */
    Thread.sleep(200);
    
    for (int i = 0; i < 2; i++) {

        AsyncHttpClient otherClient = new AsyncHttpClient();
        try {
            otherClient.preparePut("http://localhost:8080/broadcast")
                    .setBody("hello" + i)
                    .execute().get();
        
        /* sometimes the last broadcast request is not
         * finished before f.done() is called */
            Thread.sleep(200);
        } finally {
            otherClient.close();
        }
    }
    
    f.done(null);
    assertEquals("[message: hello0, message: hello1]", broadcasts.toString());
}
 
Example #8
Source File: TestServerFixture.java    From fixd with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpon() throws Exception {
    
    server.handle(Method.GET, "/subscribe")
          .with(200, "text/plain", "message: :message")
          .upon(Method.GET, "/broadcast/:message");
    
    final List<String> broadcasts = new ArrayList<String>();
    ListenableFuture<Integer> f = client.prepareGet("http://localhost:8080/subscribe")
          .execute(new AddToListOnBodyPartReceivedHandler(broadcasts));
    
    /* need some time for the above request to complete
     * before the broadcast requests can start */
    Thread.sleep(200);
    
    for (int i = 0; i < 2; i++) {

        AsyncHttpClient otherClient = new AsyncHttpClient();
        try {
            otherClient.prepareGet("http://localhost:8080/broadcast/hello" + i).execute().get();

            /* sometimes the last broadcast request is not
             * finished before f.done() is called */
            Thread.sleep(200);
        } finally {
            otherClient.close();
        }
    }
    
    f.done(null);
    assertEquals("[message: hello0, message: hello1]", broadcasts.toString());
}
 
Example #9
Source File: TestServerFixture.java    From fixd with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvery() throws Exception {
    
    server.handle(Method.GET, "/echo/:message")
          .with(200, "text/plain", "message: :message")
          .every(200, TimeUnit.MILLISECONDS, 2);
    
    final List<String> chunks = new ArrayList<String>();
    ListenableFuture<Integer> f = client.prepareGet("http://localhost:8080/echo/hello")
          .execute(new AddToListOnBodyPartReceivedHandler(chunks));
    
    assertEquals(200, (int)f.get());
    assertEquals("[message: hello, message: hello]", chunks.toString());
}
 
Example #10
Source File: HttpLocalDownloadServiceFetcher.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public FutureHolder(
  ListenableFuture<Response> future,
  long start,
  S3Artifact s3Artifact
) {
  this.future = future;
  this.start = start;
  this.s3Artifact = s3Artifact;
}
 
Example #11
Source File: GithubTest.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void githubTest() throws IOException, ExecutionException, InterruptedException {
    Request request = client.prepareGet("https://api.github.com/repos/xleiy/algorithm/git/trees/master")
            .addHeader("Accept", "application/json")
            .addHeader("'content-type", "application/json")
            .addHeader("Authorization", token)
            .build();
    ListenableFuture<Response> future = client.executeRequest(request);
    Response response = future.get();
    System.out.println(response.getStatusCode());
    System.out.println(response.getResponseBody(Charsets.UTF_8.name()));
}
 
Example #12
Source File: AsyncHttpClientLambdaAware.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 5 votes vote down vote up
public ListenableFuture<Response> execute(String url, final Completed c) throws IOException {
    return asyncHttpClient.prepareGet(url).execute(new AsyncCompletionHandler<Response>() {

        @Override
        public Response onCompleted(Response response) throws Exception {
            return c.onCompleted(response);
        }
    });
}
 
Example #13
Source File: AsyncHttpClientLambdaAware.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 5 votes vote down vote up
public ListenableFuture<Response> execute(String url, final Completed c, final Error e) throws IOException {
    return asyncHttpClient.prepareGet(url).execute(new AsyncCompletionHandler<Response>() {

        @Override
        public Response onCompleted(Response response) throws Exception {
            return c.onCompleted(response);
        }

        @Override
        public void onThrowable(Throwable t) {
            e.onThrowable(t);
        }

    });
}
 
Example #14
Source File: AggregatorEventHandler.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 5 votes vote down vote up
public void onTimeout() {

        // complete missing answers and return ...
        log.logMessage("Timeout in aggregating service, only received answers from " + noOfResults.get() + " out of total " + noOfCalls + " expected responses.");
        int i = 0;
        for (ListenableFuture<Response> executor : executors) {
            if (!executor.isDone()) {
                log.logMessage("Cancel asych request #" + i);
                executor.cancel(true);
            }
            i++;
        }
        onAllCompleted();
    }
 
Example #15
Source File: Executor.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 5 votes vote down vote up
private void onTimeout() {

        // complete missing answers and return ...
        log.logMessage("Timeout in aggregating service, only received answers from " + noOfResults.get() + " out of total " + noOfCalls + " expected responses.");
        int i = 0;
        for (ListenableFuture<Response> executor : concurrentExecutors) {
            if (!executor.isDone()) {
                log.logMessage("Cancel asych request #" + i);
                executor.cancel(true);
            }
            i++;
        }
        onAllCompleted();
    }
 
Example #16
Source File: ParsecHttpRequestRetryCallableTest.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    mockResponse = mock(com.ning.http.client.Response.class);
    mockFuture = mock(ListenableFuture.class);
    mockClient = mock(AsyncHttpClient.class);
}
 
Example #17
Source File: ParsecHttpRequestRetryCallableTest.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
private void setMockClientReturnStatusCode(int [] returnStatusCodes) throws Exception {
    List<ListenableFuture> futures = new ArrayList<>();

    for (int returnStatusCode: returnStatusCodes) {
        com.ning.http.client.Response response = mock(com.ning.http.client.Response.class);
        when(response.getStatusCode()).thenReturn(returnStatusCode);
        ListenableFuture future = mock(ListenableFuture.class);
        when(future.get()).thenReturn(response);
        futures.add(future);
    }

    when(mockClient.executeRequest(request.getNingRequest()))
        .thenAnswer(AdditionalAnswers.returnsElementsOf(futures));
}
 
Example #18
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private <T> ListenableFuture<T> submit(Request request, AsyncCompletionHandler<T> handler) {
    try {
        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().getFirstValue("Content-type"), request.getByteData().length);
        } else {
            logger.debug("Request {} {}", request.getMethod(), request.getUrl());
        }
        return client.executeRequest(request, handler);
    } catch (IOException e) {
        throw new ZendeskException(e.getMessage(), e);
    }
}
 
Example #19
Source File: GithubTest.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void githubFileTest() throws ExecutionException, InterruptedException, IOException {
    Request request = client.prepareGet("https://api.github.com/repos/xleiy/algorithm/contents/src/main/java/com/xx/leetcode/AddTwoNumbers.java")
            .addQueryParam("ref", "master")
            .addHeader("Accept", "application/json")
            .addHeader("'content-type", "application/json")
            .addHeader("Authorization", token)
            .build();
    ListenableFuture<Response> future = client.executeRequest(request);
    Response response = future.get();
    System.out.println(response.getStatusCode());
    System.out.println(response.getResponseBody(Charsets.UTF_8.name()));
}
 
Example #20
Source File: NingRequestBuilder.java    From ob1k with Apache License 2.0 4 votes vote down vote up
private ComposableFuture<com.ning.http.client.Response> executeAndTransformRequest() {

    try {
      prepareRequestBody();
    } catch (final IOException e) {
      return fromError(e);
    }

    final Request ningRequest = ningRequestBuilder.build();

    if (log.isTraceEnabled()) {
      final String body = ningRequest.getByteData() == null
        ? ningRequest.getStringData() :
        new String(ningRequest.getByteData(), Charset.forName(charset));

      log.trace("Sending HTTP call to {}: headers=[{}], body=[{}]", ningRequest.getUrl(), ningRequest.getHeaders(), body);
    }

    final Provider<com.ning.http.client.Response> provider = new Provider<com.ning.http.client.Response>() {
      private boolean aborted = false;
      private long size;

      @Override
      public ListenableFuture<com.ning.http.client.Response> provide() {
        return asyncHttpClient.executeRequest(ningRequest, new AsyncCompletionHandler<com.ning.http.client.Response>() {
          @Override
          public com.ning.http.client.Response onCompleted(final com.ning.http.client.Response response) throws Exception {
            if (aborted) {
              throw new RuntimeException("Response size is bigger than the limit: " + responseMaxSize);
            }
            return response;
          }

          @Override
          public STATE onBodyPartReceived(final HttpResponseBodyPart content) throws Exception {
            if (responseMaxSize > 0) {
              size += content.length();
              if (size > responseMaxSize) {
                aborted = true;
                return STATE.ABORT;
              }
            }
            return super.onBodyPartReceived(content);
          }
        });
      }
    };

    return fromListenableFuture(provider);
  }
 
Example #21
Source File: LoadBalancerClientImpl.java    From Singularity with Apache License 2.0 4 votes vote down vote up
private LoadBalancerUpdateHolder sendRequest(
  LoadBalancerRequestId loadBalancerRequestId,
  Request request,
  BaragonRequestState onFailure
) {
  try {
    LOG.trace(
      "Sending LB {} request for {} to {}",
      request.getMethod(),
      loadBalancerRequestId,
      request.getUrl()
    );

    ListenableFuture<Response> future = httpClient.executeRequest(request);

    Response response = future.get(loadBalancerTimeoutMillis, TimeUnit.MILLISECONDS);

    LOG.trace(
      "LB {} request {} returned with code {}",
      request.getMethod(),
      loadBalancerRequestId,
      response.getStatusCode()
    );

    if (response.getStatusCode() == 504) {
      return new LoadBalancerUpdateHolder(
        BaragonRequestState.UNKNOWN,
        Optional.of(
          String.format(
            "LB %s request %s timed out",
            request.getMethod(),
            loadBalancerRequestId
          )
        )
      );
    } else if (!JavaUtils.isHttpSuccess(response.getStatusCode())) {
      return new LoadBalancerUpdateHolder(
        onFailure,
        Optional.of(String.format("Response status code %s", response.getStatusCode()))
      );
    }

    BaragonResponse lbResponse = readResponse(response);

    return new LoadBalancerUpdateHolder(
      lbResponse.getLoadBalancerState(),
      lbResponse.getMessage().toJavaUtil()
    );
  } catch (TimeoutException te) {
    LOG.trace(
      "LB {} request {} timed out after waiting {}",
      request.getMethod(),
      loadBalancerRequestId,
      JavaUtils.durationFromMillis(loadBalancerTimeoutMillis)
    );
    return new LoadBalancerUpdateHolder(
      BaragonRequestState.UNKNOWN,
      Optional.of(
        String.format(
          "Timed out after %s",
          JavaUtils.durationFromMillis(loadBalancerTimeoutMillis)
        )
      )
    );
  } catch (Throwable t) {
    LOG.error(
      "LB {} request {} to {} threw error",
      request.getMethod(),
      loadBalancerRequestId,
      request.getUrl(),
      t
    );
    return new LoadBalancerUpdateHolder(
      BaragonRequestState.UNKNOWN,
      Optional.of(
        String.format("Exception %s - %s", t.getClass().getSimpleName(), t.getMessage())
      )
    );
  }
}
 
Example #22
Source File: RoutingSlipNonBlockingLambdaController.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 4 votes vote down vote up
/**
 * Sample usage: curl "http://localhost:9181/routing-slip-non-blocking-lambds"
 *
 * @return
 */
@RequestMapping("/routing-slip-non-blocking-lambda")
public DeferredResult<String> nonBlockingRoutingSlip() throws IOException {

    LOG.logStartNonBlocking();

    DeferredResult<String> deferredResult = new DeferredResult<>();
    Result r = new Result();

    // Kick off the asynch processing of five sequentially executed asynch processing steps

    // Send request #1
    LOG.logStartProcessingStepNonBlocking(1);
    ListenableFuture<Response> execute = asyncHttpClient.execute(getUrl(1),
            (Response r1) -> {
                LOG.logEndProcessingStepNonBlocking(1, r1.getStatusCode());

                // Process response #1
                r.processResult(r1.getResponseBody());

                // Send request #2
                LOG.logStartProcessingStepNonBlocking(2);
                asyncHttpClient.execute(getUrl(2),
                        (Response r2) -> {
                            LOG.logEndProcessingStepNonBlocking(2, r2.getStatusCode());

                            // Process response #2
                            r.processResult(r2.getResponseBody());

                            // Send request #3
                            LOG.logStartProcessingStepNonBlocking(3);
                            asyncHttpClient.execute(getUrl(3),
                                    (Response r3) -> {
                                        LOG.logEndProcessingStepNonBlocking(3, r3.getStatusCode());

                                        // Process response #3
                                        r.processResult(r3.getResponseBody());

                                        // Send request #4
                                        LOG.logStartProcessingStepNonBlocking(4);
                                        asyncHttpClient.execute(getUrl(4),
                                                (Response r4) -> {
                                                    LOG.logEndProcessingStepNonBlocking(4, r4.getStatusCode());

                                                    // Process response #4
                                                    r.processResult(r4.getResponseBody());

                                                    // Send request #5
                                                    LOG.logStartProcessingStepNonBlocking(5);
                                                    asyncHttpClient.execute(getUrl(5),
                                                        (Response r5) -> {
                                                            LOG.logEndProcessingStepNonBlocking(5, r5.getStatusCode());

                                                            // Process response #5
                                                            r.processResult(r5.getResponseBody());

                                                            // Get the total result and set it on the deferred result
                                                            boolean deferredStatus = deferredResult.setResult(r.getTotalResult());
                                                            LOG.logEndNonBlocking(r5.getStatusCode(), deferredStatus);

                                                            return r5;
                                                        });
                                                    return r4;
                                                });
                                        return r3;
                                    });
                            return r2;
                        });
                return r1;
            });

    LOG.logLeaveThreadNonBlocking();

    // Return to let go of the precious thread we are holding on to...
    return deferredResult;
}
 
Example #23
Source File: TestServerFixture.java    From fixd with Apache License 2.0 4 votes vote down vote up
@Test
public void testUponAndMarshallingAndUnmarshallingWithHandler() throws Exception {
    
    server.marshal("application/json")
          .with(new JSONMarshaller());
    
    server.unmarshal("application/json")
          .with(new JSONUnmarshaller());
    
    server.handle(Method.GET, "/subscribe")
          .with(new HttpRequestHandler() {
              public void handle(HttpRequest request, HttpResponse response) {
                  response.setStatusCode(200);
                  response.setContentType("application/json");
                  SimplePojo entity = request.getBody(SimplePojo.class);
                  response.setBody(new SimplePojo(entity.getVal()));
              }
          })
          .upon(Method.PUT, "/broadcast", "application/json");
    
    final List<String> broadcasts = new ArrayList<String>();
    ListenableFuture<Integer> f = client.prepareGet("http://localhost:8080/subscribe")
          .execute(new AddToListOnBodyPartReceivedHandler(broadcasts));
    
    /* need some time for the above request to complete
     * before the broadcast requests can start */
    Thread.sleep(100);
    
    for (int i = 0; i < 2; i++) {

        AsyncHttpClient otherClient = new AsyncHttpClient();
        try {
            otherClient.preparePut("http://localhost:8080/broadcast")
                    .setHeader("Content-Type", "application/json")
                    .setBody("{\"val\":\"hello" + i + "\"}")
                    .execute().get();
        
            /* sometimes the last broadcast request is not
             * finished before f.done() is called */
            Thread.sleep(200);
        } finally {
            otherClient.close();
        }
    }
    
    f.done(null);
    assertEquals("[{\"val\":\"hello0\"}, {\"val\":\"hello1\"}]", 
            broadcasts.toString());
}
 
Example #24
Source File: TestServerFixture.java    From fixd with Apache License 2.0 4 votes vote down vote up
@Test
public void testUponWithMultipleScubscribers() throws Exception {
    
    server.handle(Method.GET, "/subscribe")
          .with(200, "text/plain", "message: :message")
          .upon(Method.GET, "/broadcast/:message");

    AsyncHttpClient client1 = new AsyncHttpClient();
    AsyncHttpClient client2 = new AsyncHttpClient();

    try {
        final List<String> client1Broadcasts = new ArrayList<String>();
        ListenableFuture<Integer> f1 = client1.prepareGet("http://localhost:8080/subscribe")
                .execute(new AddToListOnBodyPartReceivedHandler(client1Broadcasts));

        final List<String> client2Broadcasts = new ArrayList<String>();
        ListenableFuture<Integer> f2 = client2.prepareGet("http://localhost:8080/subscribe")
                .execute(new AddToListOnBodyPartReceivedHandler(client2Broadcasts));
    
        /* need some time for the above requests to complete
         * before the broadcast requests can start */
        Thread.sleep(200);

        for (int i = 0; i < 2; i++) {

            AsyncHttpClient otherClient = new AsyncHttpClient();
            try {
                otherClient.prepareGet("http://localhost:8080/broadcast/hello" + i).execute().get();
        
            /* sometimes the last broadcast request is not
             * finished before f.done() is called */
                Thread.sleep(200);
            } finally {
                otherClient.close();
            }
        }

        f1.done(null);
        f2.done(null);
        assertEquals("[message: hello0, message: hello1]", client1Broadcasts.toString());
        assertEquals("[message: hello0, message: hello1]", client2Broadcasts.toString());
    } finally {
        client1.close();
        client2.close();
    }
}
 
Example #25
Source File: TestServerFixture.java    From fixd with Apache License 2.0 4 votes vote down vote up
@Test
public void testUponHandlesDifferentSubscriptions() throws Exception {
    
    server.handle(Method.GET, "/subscr1")
          .with(200, "text/plain", "message1")
          .upon(Method.GET, "/broadc1");
    
    server.handle(Method.GET, "/subscr2")
          .with(200, "text/plain", "message2")
          .upon(Method.GET, "/broadc2");

    AsyncHttpClient client1 = new AsyncHttpClient();
    AsyncHttpClient client2 = new AsyncHttpClient();

    try {
        final List<String> broadcasts1 = new ArrayList<String>();
        ListenableFuture<Integer> f1 = client1.prepareGet("http://localhost:8080/subscr1")
                .execute(new AddToListOnBodyPartReceivedHandler(broadcasts1));

        final List<String> broadcasts2 = new ArrayList<String>();
        ListenableFuture<Integer> f2 = client2.prepareGet("http://localhost:8080/subscr2")
                .execute(new AddToListOnBodyPartReceivedHandler(broadcasts2));
    
        /* need some time for the above request to complete
         * before the broadcast requests can start */
        Thread.sleep(200);

        AsyncHttpClient otherClient = new AsyncHttpClient();
        try {
            new AsyncHttpClient()
                    .prepareGet("http://localhost:8080/broadc2")
                    .execute().get();
    
            /* sometimes the last broadcast request is not
             * finished before f.done() is called */
            Thread.sleep(200);
        } finally {
            otherClient.close();
        }

        f1.done(null);
        f2.done(null);
        assertEquals("[]", broadcasts1.toString());
        assertEquals("[message2]", broadcasts2.toString());
    } finally {
        client1.close();
        client2.close();
    }
}
 
Example #26
Source File: ComposableFutureAdapter.java    From ob1k with Apache License 2.0 votes vote down vote up
ListenableFuture<T> provide();