@Test(groups = "standalone", enabled = false)
  public void testProxyActivationProperty()
      throws IOException, ExecutionException, TimeoutException, InterruptedException {
    // FIXME not threadsafe!
    Properties originalProps = new Properties();
    originalProps.putAll(System.getProperties());
    System.setProperty(ProxyUtils.PROXY_HOST, "127.0.0.1");
    System.setProperty(ProxyUtils.PROXY_PORT, String.valueOf(port1));
    System.setProperty(ProxyUtils.PROXY_NONPROXYHOSTS, "localhost");
    System.setProperty(
        AsyncHttpClientConfigDefaults.ASYNC_CLIENT_CONFIG_ROOT + "useProxyProperties", "true");
    AsyncHttpClientConfigHelper.reloadProperties();

    try (AsyncHttpClient client = asyncHttpClient()) {
      String proxifiedTarget = "http://127.0.0.1:1234/";
      Future<Response> f = client.prepareGet(proxifiedTarget).execute();
      Response resp = f.get(3, TimeUnit.SECONDS);
      assertNotNull(resp);
      assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
      assertEquals(resp.getHeader("target"), "/");

      String nonProxifiedTarget = "http://localhost:1234/";
      f = client.prepareGet(nonProxifiedTarget).execute();
      try {
        resp = f.get(3, TimeUnit.SECONDS);
        fail("should not be able to connect");
      } catch (ExecutionException e) {
        // ok, no proxy used
      }
    } finally {
      System.setProperties(originalProps);
    }
  }
  @Test(groups = {"standalone", "default_provider"})
  public void multipleRequestsTest() throws Exception {
    try (AsyncHttpClient c = new DefaultAsyncHttpClient()) {
      String body = "hello there";

      // once
      Response response =
          c.preparePost(getTargetUrl())
              .setBody(body)
              .setHeader("Content-Type", "text/html")
              .execute()
              .get(TIMEOUT, TimeUnit.SECONDS);

      assertEquals(response.getResponseBody(), body);

      // twice
      response =
          c.preparePost(getTargetUrl())
              .setBody(body)
              .setHeader("Content-Type", "text/html")
              .execute()
              .get(TIMEOUT, TimeUnit.SECONDS);

      assertEquals(response.getResponseBody(), body);
    }
  }
  @Test(groups = "standalone")
  public void testObserveMultiple() {
    final TestSubscriber<Response> tester = new TestSubscriber<>();

    try (AsyncHttpClient client = asyncHttpClient()) {
      Observable<Response> o1 =
          AsyncHttpObservable.observe(() -> client.prepareGet("http://gatling.io"));
      Observable<Response> o2 =
          AsyncHttpObservable.observe(
              () -> client.prepareGet("http://www.wisc.edu").setFollowRedirect(true));
      Observable<Response> o3 =
          AsyncHttpObservable.observe(
              () -> client.prepareGet("http://www.umn.edu").setFollowRedirect(true));
      Observable<Response> all = Observable.merge(o1, o2, o3);
      all.subscribe(tester);
      tester.awaitTerminalEvent();
      tester.assertTerminalEvent();
      tester.assertCompleted();
      tester.assertNoErrors();
      List<Response> responses = tester.getOnNextEvents();
      assertNotNull(responses);
      assertEquals(responses.size(), 3);
      for (Response response : responses) {
        assertEquals(response.getStatusCode(), 200);
      }
    } catch (Exception e) {
      Thread.currentThread().interrupt();
    }
  }
  private F.Promise<WSResponse> execute(Request request) {

    final scala.concurrent.Promise<WSResponse> scalaPromise =
        scala.concurrent.Promise$.MODULE$.<WSResponse>apply();
    try {
      AsyncHttpClient asyncHttpClient = (AsyncHttpClient) client.getUnderlying();
      asyncHttpClient.executeRequest(
          request,
          new AsyncCompletionHandler<Response>() {
            @Override
            public Response onCompleted(Response response) {
              final Response ahcResponse = response;
              scalaPromise.success(new AhcWSResponse(ahcResponse));
              return response;
            }

            @Override
            public void onThrowable(Throwable t) {
              scalaPromise.failure(t);
            }
          });
    } catch (RuntimeException exception) {
      scalaPromise.failure(exception);
    }
    return F.Promise.wrap(scalaPromise.future());
  }
  @Test(groups = {"standalone", "default_provider"})
  public void basicByteBufferTest() throws Exception {
    AsyncHttpClient c = getAsyncHttpClient(null);
    try {
      File largeFile = createTempFile(1024 * 100 * 10);
      final AtomicInteger byteReceived = new AtomicInteger();

      try {
        Response response =
            c.preparePut(getTargetUrl())
                .setBody(largeFile)
                .execute(
                    new AsyncCompletionHandlerAdapter() {
                      @Override
                      public STATE onBodyPartReceived(final HttpResponseBodyPart content)
                          throws Exception {
                        byteReceived.addAndGet(content.getBodyByteBuffer().capacity());
                        return super.onBodyPartReceived(content);
                      }
                    })
                .get();

        assertNotNull(response);
        assertEquals(response.getStatusCode(), 200);
        assertEquals(byteReceived.get(), largeFile.length());
        assertEquals(response.getResponseBody().length(), largeFile.length());

      } catch (IOException ex) {
        fail("Should have timed out");
      }
    } finally {
      c.close();
    }
  }
 @Test(groups = "standalone")
 public void testGlobalProxy()
     throws IOException, ExecutionException, TimeoutException, InterruptedException {
   try (AsyncHttpClient client =
       asyncHttpClient(config().setProxyServer(proxyServer("localhost", port1)))) {
     String target = "http://localhost:1234/";
     Future<Response> f = client.prepareGet(target).execute();
     Response resp = f.get(3, TimeUnit.SECONDS);
     assertNotNull(resp);
     assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
     assertEquals(resp.getHeader("target"), "/");
   }
 }
 @Test(groups = {"standalone", "default_provider"})
 public void urlWithoutSlashTest() throws Exception {
   try (AsyncHttpClient c = new DefaultAsyncHttpClient()) {
     String body = "hello there";
     Response response =
         c.preparePost(String.format("http://127.0.0.1:%d/foo/test", port1))
             .setBody(body)
             .setHeader("Content-Type", "text/html")
             .execute()
             .get(TIMEOUT, TimeUnit.SECONDS);
     assertEquals(response.getResponseBody(), body);
   }
 }
 @Test(groups = {"standalone", "default_provider"})
 public void testQueryParameters() throws Exception {
   try (AsyncHttpClient client = getAsyncHttpClient(null)) {
     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 = {"standalone", "default_provider"})
 public void Expect100Continue() throws Exception {
   try (AsyncHttpClient client = getAsyncHttpClient(null)) {
     Future<Response> f =
         client
             .preparePut("http://127.0.0.1:" + port1 + "/")
             .setHeader("Expect", "100-continue")
             .setBody(SIMPLE_TEXT_FILE)
             .execute();
     Response resp = f.get();
     assertNotNull(resp);
     assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
     assertEquals(resp.getResponseBody(), SIMPLE_TEXT_FILE_STRING);
   }
 }
  @Test(groups = "standalone")
  public void testNonProxyHostsRequestOverridesConfig()
      throws IOException, ExecutionException, TimeoutException, InterruptedException {

    ProxyServer configProxy = proxyServer("localhost", port1 - 1).build();
    ProxyServer requestProxy = proxyServer("localhost", port1).setNonProxyHost("localhost").build();

    try (AsyncHttpClient client = asyncHttpClient(config().setProxyServer(configProxy))) {
      String target = "http://localhost:1234/";
      client.prepareGet(target).setProxyServer(requestProxy).execute().get();
      assertFalse(true);
    } catch (Throwable e) {
      assertNotNull(e.getCause());
      assertEquals(e.getCause().getClass(), ConnectException.class);
    }
  }
  // @Test(groups = { "online", "default_provider" })
  public void notRedirected302Test() throws Exception {
    isSet.getAndSet(false);
    AsyncHttpClientConfig cg = new AsyncHttpClientConfig.Builder().setFollowRedirect(true).build();
    AsyncHttpClient c = getAsyncHttpClient(cg);
    try {
      Response response =
          c.prepareGet(getTargetUrl())
              .setFollowRedirect(false)
              .setHeader("X-redirect", "http://www.microsoft.com/")
              .execute()
              .get();

      assertNotNull(response);
      assertEquals(response.getStatusCode(), 302);
    } finally {
      c.close();
    }
  }
  // @Test(groups = { "standalone", "default_provider" })
  public void relativeLocationUrl() throws Exception {
    isSet.getAndSet(false);

    AsyncHttpClient c = getAsyncHttpClient(null);
    try {
      Response response =
          c.preparePost(getTargetUrl())
              .setFollowRedirect(true)
              .setHeader("X-redirect", "/foo/test")
              .execute()
              .get();
      assertNotNull(response);
      assertEquals(response.getStatusCode(), 302);
      assertEquals(response.getUri().toString(), getTargetUrl());
    } finally {
      c.close();
    }
  }
  @Test(groups = "standalone")
  public void testObserveError() {
    final TestSubscriber<Response> tester = new TestSubscriber<>();

    try (AsyncHttpClient client = asyncHttpClient()) {
      Observable<Response> o1 =
          AsyncHttpObservable.observe(() -> client.prepareGet("http://gatling.io/ttfn"));
      o1.subscribe(tester);
      tester.awaitTerminalEvent();
      tester.assertTerminalEvent();
      tester.assertCompleted();
      tester.assertNoErrors();
      List<Response> responses = tester.getOnNextEvents();
      assertNotNull(responses);
      assertEquals(responses.size(), 1);
      assertEquals(responses.get(0).getStatusCode(), 404);
    } catch (Exception e) {
      Thread.currentThread().interrupt();
    }
  }
  // @Test(groups = { "standalone", "default_provider" })
  public void redirected302InvalidTest() throws Exception {
    isSet.getAndSet(false);
    AsyncHttpClient c = getAsyncHttpClient(null);
    try {
      // If the test hit a proxy, no ConnectException will be thrown and instead of 404 will be
      // returned.
      Response response =
          c.preparePost(getTargetUrl())
              .setFollowRedirect(true)
              .setHeader("X-redirect", String.format("http://127.0.0.1:%d/", port2))
              .execute()
              .get();

      assertNotNull(response);
      assertEquals(response.getStatusCode(), 404);
    } catch (ExecutionException ex) {
      assertEquals(ex.getCause().getClass(), ConnectException.class);
    } finally {
      c.close();
    }
  }
  // @Test(groups = "standalone")
  public void testUseProxySelector()
      throws IOException, ExecutionException, TimeoutException, InterruptedException {
    ProxySelector originalProxySelector = ProxySelector.getDefault();
    ProxySelector.setDefault(
        new ProxySelector() {
          public List<Proxy> select(URI uri) {
            if (uri.getHost().equals("127.0.0.1")) {
              return Arrays.asList(
                  new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", port1)));
            } else {
              return Arrays.asList(Proxy.NO_PROXY);
            }
          }

          public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {}
        });

    try (AsyncHttpClient client = asyncHttpClient(config().setUseProxySelector(true))) {
      String proxifiedTarget = "http://127.0.0.1:1234/";
      Future<Response> f = client.prepareGet(proxifiedTarget).execute();
      Response resp = f.get(3, TimeUnit.SECONDS);
      assertNotNull(resp);
      assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
      assertEquals(resp.getHeader("target"), "/");

      String nonProxifiedTarget = "http://localhost:1234/";
      f = client.prepareGet(nonProxifiedTarget).execute();
      try {
        f.get(3, TimeUnit.SECONDS);
        fail("should not be able to connect");
      } catch (ExecutionException e) {
        // ok, no proxy used
      }
    } finally {
      // FIXME not threadsafe
      ProxySelector.setDefault(originalProxySelector);
    }
  }
  // @Test(groups = "standalone")
  public void testWildcardNonProxyHosts()
      throws IOException, ExecutionException, TimeoutException, InterruptedException {
    // FIXME not threadsafe!
    Properties originalProps = new Properties();
    originalProps.putAll(System.getProperties());
    System.setProperty(ProxyUtils.PROXY_HOST, "127.0.0.1");
    System.setProperty(ProxyUtils.PROXY_PORT, String.valueOf(port1));
    System.setProperty(ProxyUtils.PROXY_NONPROXYHOSTS, "127.*");
    AsyncHttpClientConfigHelper.reloadProperties();

    try (AsyncHttpClient client = asyncHttpClient(config().setUseProxyProperties(true))) {
      String nonProxifiedTarget = "http://127.0.0.1:1234/";
      Future<Response> f = client.prepareGet(nonProxifiedTarget).execute();
      try {
        f.get(3, TimeUnit.SECONDS);
        fail("should not be able to connect");
      } catch (ExecutionException e) {
        // ok, no proxy used
      }
    } finally {
      System.setProperties(originalProps);
    }
  }
  // @Test(groups = { "online", "default_provider" })
  public void redirected302Test() throws Exception {
    isSet.getAndSet(false);
    AsyncHttpClient c = getAsyncHttpClient(null);
    try {
      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);
    } finally {
      c.close();
    }
  }
  @Test(groups = {"online", "default_provider"})
  public void testMaxConnectionsWithinThreads() {

    String[] urls = new String[] {servletEndpointUri.toString(), servletEndpointUri.toString()};

    final AsyncHttpClient client =
        getAsyncHttpClient(
            new AsyncHttpClientConfig.Builder()
                .setConnectionTimeoutInMs(1000)
                .setRequestTimeoutInMs(5000)
                .setAllowPoolingConnection(true)
                .setMaxConnectionsTotal(1)
                .setMaxConnectionsPerHost(1)
                .build());

    try {
      final Boolean[] caughtError = new Boolean[] {Boolean.FALSE};
      List<Thread> ts = new ArrayList<Thread>();
      for (int i = 0; i < urls.length; i++) {
        final String url = urls[i];
        Thread t =
            new Thread() {
              public void run() {
                try {
                  client.prepareGet(url).execute();
                } catch (IOException e) {
                  // assert that 2nd request fails, because maxTotalConnections=1
                  // logger.debug(i);
                  caughtError[0] = true;
                  logger.error("Exception ", e);
                }
              }
            };
        t.start();
        ts.add(t);
      }

      for (Thread t : ts) {
        try {
          t.join();
        } catch (InterruptedException e) {
          logger.error("Exception ", e);
        }
      }

      // Let the threads finish
      try {
        Thread.sleep(4500);
      } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

      assertTrue(caughtError[0], "Max Connections should have been reached");

      boolean errorInNotThread = false;
      for (int i = 0; i < urls.length; i++) {
        final String url = urls[i];
        try {
          client.prepareGet(url).execute();
          // client.prepareGet(url).execute();
        } catch (IOException e) {
          // assert that 2nd request fails, because maxTotalConnections=1
          // logger.debug(i);
          errorInNotThread = true;
          System.err.println("============");
          e.printStackTrace();
          System.err.println("============");
        }
      }
      // Let the request finish
      try {
        Thread.sleep(2500);
      } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
      assertTrue(errorInNotThread, "Max Connections should have been reached");
    } finally {
      client.close();
    }
  }
Exemple #19
0
 @Override
 public void close() throws IOException {
   asyncHttpClient.close();
 }