@Test(groups = "standalone")
  public void asyncStreamThrowableRefusedTest() throws Exception {

    final CountDownLatch l = new CountDownLatch(1);
    try (AsyncHttpClient c = asyncHttpClient()) {
      c.prepareGet(getTargetUrl())
          .execute(
              new AsyncHandlerAdapter() {

                @Override
                public State onHeadersReceived(HttpResponseHeaders content) throws Exception {
                  throw new RuntimeException("FOO");
                }

                @Override
                public void onThrowable(Throwable t) {
                  try {
                    if (t.getMessage() != null) {
                      assertEquals(t.getMessage(), "FOO");
                    }
                  } finally {
                    l.countDown();
                  }
                }
              });

      if (!l.await(10, TimeUnit.SECONDS)) {
        fail("Timed out");
      }
    }
  }
  @Test(groups = {"standalone", "default_provider"})
  public void testListenableFuture() throws Exception {
    final AtomicInteger statusCode = new AtomicInteger(500);
    try (AsyncHttpClient ahc = asyncHttpClient()) {
      final CountDownLatch latch = new CountDownLatch(1);
      final ListenableFuture<Response> future = ahc.prepareGet(getTargetUrl()).execute();
      future.addListener(
          new Runnable() {

            public void run() {
              try {
                statusCode.set(future.get().getStatusCode());
                latch.countDown();
              } catch (InterruptedException e) {
                e.printStackTrace();
              } catch (ExecutionException e) {
                e.printStackTrace();
              }
            }
          },
          Executors.newFixedThreadPool(1));

      latch.await(10, TimeUnit.SECONDS);
      assertEquals(statusCode.get(), 200);
    }
  }
 @Test(groups = "online")
 public void testGoogleComWithTimeout() throws Exception {
   try (AsyncHttpClient c = asyncHttpClient(config().setRequestTimeout(10000))) {
     Response response = c.prepareGet("http://google.com/").execute().get(10, TimeUnit.SECONDS);
     assertNotNull(response);
     assertTrue(response.getStatusCode() == 301 || response.getStatusCode() == 302);
   }
 }
 @Test(groups = "online")
 public void testMailGoogleCom() throws Exception {
   try (AsyncHttpClient c = asyncHttpClient(config().setRequestTimeout(10000))) {
     Response response =
         c.prepareGet("http://mail.google.com/").execute().get(10, TimeUnit.SECONDS);
     assertNotNull(response);
     assertEquals(response.getStatusCode(), 200);
   }
 }
 // FIXME Get a 302 in France...
 @Test(groups = "online", enabled = false)
 public void testUrlRequestParametersEncoding() throws Exception {
   try (AsyncHttpClient client = asyncHttpClient()) {
     String requestUrl2 = URL + URLEncoder.encode(REQUEST_PARAM, UTF_8.name());
     logger.info(String.format("Executing request [%s] ...", requestUrl2));
     Response response = client.prepareGet(requestUrl2).execute().get();
     assertEquals(response.getStatusCode(), 302);
   }
 }
 @Test(groups = "online", enabled = false)
 // FIXME
 public void testMicrosoftCom() throws Exception {
   try (AsyncHttpClient c = asyncHttpClient(config().setRequestTimeout(10000))) {
     Response response = c.prepareGet("http://microsoft.com/").execute().get(10, TimeUnit.SECONDS);
     assertNotNull(response);
     assertEquals(response.getStatusCode(), 301);
   }
 }
  @Test(groups = "online")
  public void stripQueryStringTest() throws Exception {

    try (AsyncHttpClient c = asyncHttpClient(config().setFollowRedirect(true))) {
      Response response = c.prepareGet("http://www.freakonomics.com/?p=55846").execute().get();

      assertNotNull(response);
      assertEquals(response.getStatusCode(), 200);
    }
  }
  @Test(groups = "online")
  public void asyncFullBodyProperlyRead() throws Exception {
    try (AsyncHttpClient client = asyncHttpClient()) {
      Response r = client.prepareGet("http://www.cyberpresse.ca/").execute().get();

      InputStream stream = r.getResponseBodyAsStream();
      int contentLength = Integer.valueOf(r.getHeader("Content-Length"));

      assertEquals(contentLength, IOUtils.toByteArray(stream).length);
    }
  }
 // @Test(groups = "online")
 public void notRedirected302Test() throws Exception {
   isSet.getAndSet(false);
   try (AsyncHttpClient c = asyncHttpClient(config().setFollowRedirect(true))) {
     Response response =
         c.prepareGet(getTargetUrl())
             .setFollowRedirect(false)
             .setHeader("X-redirect", "http://www.microsoft.com/")
             .execute()
             .get();
     assertNotNull(response);
     assertEquals(response.getStatusCode(), 302);
   }
 }
 @Test(groups = "standalone")
 public void testQueryParameters() throws Exception {
   try (AsyncHttpClient client = asyncHttpClient()) {
     Future<Response> f =
         client
             .prepareGet("http://127.0.0.1:" + port1 + "/foo")
             .addHeader("Accepts", "*/*")
             .execute();
     Response resp = f.get(3, TimeUnit.SECONDS);
     assertNotNull(resp);
     assertEquals(resp.getStatusCode(), 400);
     assertEquals(resp.getResponseBody(), BAD_REQUEST_STR);
   }
 }
  @Test(groups = "online")
  public void asyncStream302RedirectWithBody() throws Exception {
    final AtomicReference<Integer> statusCode = new AtomicReference<>(0);
    final AtomicReference<HttpHeaders> responseHeaders = new AtomicReference<>();
    try (AsyncHttpClient c = asyncHttpClient(config().setFollowRedirect(true))) {
      Future<String> f =
          c.prepareGet("http://google.com/")
              .execute(
                  new AsyncHandlerAdapter() {

                    public State onStatusReceived(HttpResponseStatus status) throws Exception {
                      statusCode.set(status.getStatusCode());
                      return State.CONTINUE;
                    }

                    @Override
                    public State onHeadersReceived(HttpResponseHeaders content) throws Exception {
                      responseHeaders.set(content.getHeaders());
                      return State.CONTINUE;
                    }

                    @Override
                    public String onCompleted() throws Exception {
                      return null;
                    }
                  });

      f.get(20, TimeUnit.SECONDS);
      assertTrue(statusCode.get() != 302);
      HttpHeaders h = responseHeaders.get();
      assertNotNull(h);
      assertEquals(h.get("server"), "gws");
      // This assertion below is not an invariant, since implicitly contains locale-dependant
      // settings
      // and fails when run in country having own localized Google site and it's locale relies on
      // something
      // other than ISO-8859-1.
      // In Hungary for example, http://google.com/ redirects to http://www.google.hu/, a localized
      // Google site, that uses ISO-8892-2 encoding (default for HU). Similar is true for other
      // non-ISO-8859-1 using countries that have "localized" google, like google.hr, google.rs,
      // google.cz, google.sk etc.
      //
      // assertEquals(h.get(HttpHeaders.Names.CONTENT_TYPE), "text/html; charset=ISO-8859-1");
    }
  }
  @Test(groups = "standalone")
  public void closeConnectionTest() throws Exception {
    try (AsyncHttpClient c = asyncHttpClient()) {
      Response r =
          c.prepareGet(getTargetUrl())
              .execute(
                  new AsyncHandler<Response>() {

                    private Response.ResponseBuilder builder = new Response.ResponseBuilder();

                    public State onHeadersReceived(HttpResponseHeaders content) throws Exception {
                      builder.accumulate(content);
                      return State.CONTINUE;
                    }

                    public void onThrowable(Throwable t) {}

                    public State onBodyPartReceived(HttpResponseBodyPart content) throws Exception {
                      builder.accumulate(content);

                      if (content.isLast()) {
                        content.markUnderlyingConnectionAsToBeClosed();
                      }
                      return State.CONTINUE;
                    }

                    public State onStatusReceived(HttpResponseStatus responseStatus)
                        throws Exception {
                      builder.accumulate(responseStatus);

                      return State.CONTINUE;
                    }

                    public Response onCompleted() throws Exception {
                      return builder.build();
                    }
                  })
              .get();

      assertNotNull(r);
      assertEquals(r.getStatusCode(), 200);
    }
  }
  @Test(groups = "standalone")
  public void asyncStreamGETTest() throws Exception {
    final CountDownLatch l = new CountDownLatch(1);
    final AtomicReference<HttpHeaders> responseHeaders = new AtomicReference<>();
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    try (AsyncHttpClient c = asyncHttpClient()) {
      c.prepareGet(getTargetUrl())
          .execute(
              new AsyncHandlerAdapter() {

                @Override
                public State onHeadersReceived(HttpResponseHeaders content) throws Exception {
                  try {
                    responseHeaders.set(content.getHeaders());
                    return State.ABORT;
                  } finally {
                    l.countDown();
                  }
                }

                @Override
                public void onThrowable(Throwable t) {
                  try {
                    throwable.set(t);
                  } finally {
                    l.countDown();
                  }
                }
              });

      if (!l.await(5, TimeUnit.SECONDS)) {
        fail("Timeout out");
      }

      HttpHeaders h = responseHeaders.get();
      assertNotNull(h, "No response headers");
      assertEquals(
          h.get(HttpHeaders.Names.CONTENT_TYPE),
          TEXT_HTML_CONTENT_TYPE_WITH_UTF_8_CHARSET,
          "Unexpected content-type");
      assertNull(throwable.get(), "Unexpected exception");
    }
  }
  @Test(groups = "online", enabled = false)
  public void testAHC62Com() throws Exception {
    try (AsyncHttpClient c = asyncHttpClient(config().setFollowRedirect(true))) {
      Response response =
          c.prepareGet("http://api.crunchbase.com/v/1/financial-organization/kinsey-hills-group.js")
              .execute(
                  new AsyncHandler<Response>() {

                    private Response.ResponseBuilder builder = new Response.ResponseBuilder();

                    public void onThrowable(Throwable t) {
                      t.printStackTrace();
                    }

                    public State onBodyPartReceived(HttpResponseBodyPart bodyPart)
                        throws Exception {
                      System.out.println(bodyPart.getBodyPartBytes().length);
                      builder.accumulate(bodyPart);

                      return State.CONTINUE;
                    }

                    public State onStatusReceived(HttpResponseStatus responseStatus)
                        throws Exception {
                      builder.accumulate(responseStatus);
                      return State.CONTINUE;
                    }

                    public State onHeadersReceived(HttpResponseHeaders headers) throws Exception {
                      builder.accumulate(headers);
                      return State.CONTINUE;
                    }

                    public Response onCompleted() throws Exception {
                      return builder.build();
                    }
                  })
              .get(10, TimeUnit.SECONDS);
      assertNotNull(response);
      assertTrue(response.getResponseBody().length() >= 3870);
    }
  }
  @Test(groups = "online", enabled = false)
  public void invalidStreamTest2() throws Exception {
    AsyncHttpClientConfig config =
        config() //
            .setRequestTimeout(10000) //
            .setFollowRedirect(true) //
            .setKeepAlive(false) //
            .setMaxRedirects(6) //
            .build();

    try (AsyncHttpClient c = asyncHttpClient(config)) {
      Response response = c.prepareGet("http://bit.ly/aUjTtG").execute().get();
      if (response != null) {
        System.out.println(response);
      }
    } catch (Throwable t) {
      t.printStackTrace();
      assertNotNull(t.getCause());
      assertEquals(t.getCause().getMessage(), "invalid version format: ICY");
    }
  }
  // @Test(groups = "online")
  public void redirected302Test() throws Exception {
    isSet.getAndSet(false);
    try (AsyncHttpClient c = asyncHttpClient()) {
      Response response =
          c.prepareGet(getTargetUrl())
              .setFollowRedirect(true)
              .setHeader("X-redirect", "http://www.microsoft.com/")
              .execute()
              .get();

      assertNotNull(response);
      assertEquals(response.getStatusCode(), 200);

      String anyMicrosoftPage = "http://www.microsoft.com[^:]*:80";
      String baseUrl = getBaseUrl(response.getUri());

      assertTrue(
          baseUrl.matches(anyMicrosoftPage),
          "response does not show redirection to " + anyMicrosoftPage);
    }
  }
  @Test(
      groups = "standalone",
      timeOut = 3000,
      description = "Test behavior of 'read only status line' scenario.")
  public void asyncStreamJustStatusLine() throws Exception {
    final int STATUS = 0;
    final int COMPLETED = 1;
    final int OTHER = 2;
    final boolean[] whatCalled = new boolean[] {false, false, false};
    final CountDownLatch latch = new CountDownLatch(1);
    try (AsyncHttpClient client = asyncHttpClient()) {
      Future<Integer> statusCode =
          client
              .prepareGet(getTargetUrl())
              .execute(
                  new AsyncHandler<Integer>() {
                    private int status = -1;

                    @Override
                    public void onThrowable(Throwable t) {
                      whatCalled[OTHER] = true;
                      latch.countDown();
                    }

                    @Override
                    public State onBodyPartReceived(HttpResponseBodyPart bodyPart)
                        throws Exception {
                      whatCalled[OTHER] = true;
                      latch.countDown();
                      return State.ABORT;
                    }

                    @Override
                    public State onStatusReceived(HttpResponseStatus responseStatus)
                        throws Exception {
                      whatCalled[STATUS] = true;
                      status = responseStatus.getStatusCode();
                      latch.countDown();
                      return State.ABORT;
                    }

                    @Override
                    public State onHeadersReceived(HttpResponseHeaders headers) throws Exception {
                      whatCalled[OTHER] = true;
                      latch.countDown();
                      return State.ABORT;
                    }

                    @Override
                    public Integer onCompleted() throws Exception {
                      whatCalled[COMPLETED] = true;
                      latch.countDown();
                      return status;
                    }
                  });

      if (!latch.await(2, TimeUnit.SECONDS)) {
        fail("Timeout");
        return;
      }
      Integer status = statusCode.get(TIMEOUT, TimeUnit.SECONDS);
      assertEquals((int) status, 200, "Expected status code failed.");

      if (!whatCalled[STATUS]) {
        fail("onStatusReceived not called.");
      }
      if (!whatCalled[COMPLETED]) {
        fail("onCompleted not called.");
      }
      if (whatCalled[OTHER]) {
        fail("Other method of AsyncHandler got called.");
      }
    }
  }