Ejemplo n.º 1
1
  @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")
  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();
    }
  }
Ejemplo n.º 3
0
 @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"), "/");
   }
 }
Ejemplo n.º 4
0
  // @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", "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);
   }
 }
Ejemplo n.º 6
0
  @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")
  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();
    }
  }
Ejemplo n.º 9
0
  // @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();
    }
  }