示例#1
0
  /**
   * Create the new Jetty client connector.
   *
   * @param jaxrsClient JAX-RS client instance, for which the connector is created.
   * @param config client configuration.
   */
  JettyConnector(final Client jaxrsClient, final Configuration config) {

    final SSLContext sslContext = getSslContext(jaxrsClient, config);
    final SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setSslContext(sslContext);
    this.client = new HttpClient(sslContextFactory);

    final Object connectTimeout = config.getProperties().get(ClientProperties.CONNECT_TIMEOUT);
    if (connectTimeout != null
        && connectTimeout instanceof Integer
        && (Integer) connectTimeout > 0) {
      client.setConnectTimeout((Integer) connectTimeout);
    }
    final Object threadPoolSize =
        config.getProperties().get(ClientProperties.ASYNC_THREADPOOL_SIZE);
    if (threadPoolSize != null
        && threadPoolSize instanceof Integer
        && (Integer) threadPoolSize > 0) {
      final String name = HttpClient.class.getSimpleName() + "@" + hashCode();
      final QueuedThreadPool threadPool = new QueuedThreadPool((Integer) threadPoolSize);
      threadPool.setName(name);
      client.setExecutor(threadPool);
    }
    Boolean disableCookies =
        (Boolean) config.getProperties().get(JettyClientProperties.DISABLE_COOKIES);
    disableCookies = (disableCookies != null) ? disableCookies : false;

    final AuthenticationStore auth = client.getAuthenticationStore();
    final Object basicAuthProvider =
        config.getProperty(JettyClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION);
    if (basicAuthProvider != null && (basicAuthProvider instanceof BasicAuthentication)) {
      auth.addAuthentication((BasicAuthentication) basicAuthProvider);
    }

    final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
    if (proxyUri != null) {
      final URI u = getProxyUri(proxyUri);
      final ProxyConfiguration proxyConfig = client.getProxyConfiguration();
      proxyConfig.getProxies().add(new HttpProxy(u.getHost(), u.getPort()));
    }

    if (disableCookies) {
      client.setCookieStore(new HttpCookieStore.Empty());
    }

    try {
      client.start();
    } catch (final Exception e) {
      throw new ProcessingException("Failed to start the client.", e);
    }
    this.cookieStore = client.getCookieStore();
  }
  @Test
  public void testProxyWithResponseContent() throws Exception {
    prepareProxy();

    HttpClient result = new HttpClient();
    result
        .getProxyConfiguration()
        .getProxies()
        .add(new HttpProxy("localhost", proxyConnector.getLocalPort()));
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setName("foo");
    threadPool.setMaxThreads(20);
    result.setExecutor(threadPool);
    result.start();

    ContentResponse[] responses = new ContentResponse[10];

    final byte[] content = new byte[1024];
    new Random().nextBytes(content);
    prepareServer(
        new HttpServlet() {
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws ServletException, IOException {
            if (req.getHeader("Via") != null) resp.addHeader(PROXIED_HEADER, "true");
            resp.getOutputStream().write(content);
          }
        });

    for (int i = 0; i < 10; ++i) {
      // Request is for the target server
      responses[i] =
          result
              .newRequest("localhost", serverConnector.getLocalPort())
              .timeout(5, TimeUnit.SECONDS)
              .send();
    }

    for (int i = 0; i < 10; ++i) {
      Assert.assertEquals(200, responses[i].getStatus());
      Assert.assertTrue(responses[i].getHeaders().containsKey(PROXIED_HEADER));
      Assert.assertArrayEquals(content, responses[i].getContent());
    }
  }
  @Test
  public void testInvalidation() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    AbstractTestServer server1 = createServer(0);
    server1.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
    server1.start();
    int port1 = server1.getPort();
    System.err.println("Port1=" + port1);
    try {
      AbstractTestServer server2 = createServer(0);
      server2.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
      server2.start();
      int port2 = server2.getPort();
      System.err.println("port2=" + port2);
      try {
        HttpClient client = new HttpClient();
        QueuedThreadPool executor = new QueuedThreadPool();
        client.setExecutor(executor);
        client.start();
        try {
          String[] urls = new String[2];
          urls[0] = "http://localhost:" + port1 + contextPath + servletMapping;
          urls[1] = "http://localhost:" + port2 + contextPath + servletMapping;

          // Create the session on node1
          ContentResponse response1 = client.GET(urls[0] + "?action=init");

          assertEquals(HttpServletResponse.SC_OK, response1.getStatus());
          String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
          assertTrue(sessionCookie != null);
          // Mangle the cookie, replacing Path with $Path, etc.
          sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");

          // Be sure the session is also present in node2

          Request request2 = client.newRequest(urls[1] + "?action=increment");
          request2.header("Cookie", sessionCookie);
          ContentResponse response2 = request2.send();
          assertEquals(HttpServletResponse.SC_OK, response2.getStatus());

          // Invalidate on node1
          Request request1 = client.newRequest(urls[0] + "?action=invalidate");
          request1.header("Cookie", sessionCookie);
          response1 = request1.send();
          assertEquals(HttpServletResponse.SC_OK, response1.getStatus());

          pause();

          // Be sure on node2 we don't see the session anymore
          request2 = client.newRequest(urls[1] + "?action=test");
          request2.header("Cookie", sessionCookie);
          response2 = request2.send();
          assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
        } finally {
          client.stop();
        }
      } finally {
        server2.stop();
      }
    } finally {
      server1.stop();
    }
  }
  public static void main(String[] args) throws Exception {

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
      host = args[0];
    }

    int port = 37232;
    if (args.length > 1) {
      port = Integer.valueOf(args[1]);
    }

    String homeUrl = "http://{host}:{port}/home";
    logger.debug("Sending warm-up HTTP request to " + homeUrl);
    HttpStatus status =
        new RestTemplate().getForEntity(homeUrl, Void.class, host, port).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<>();

    StandardWebSocketClient webSocketClient = new StandardWebSocketClient();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
      ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
      taskScheduler.afterPropertiesSet();

      String stompUrl = "ws://{host}:{port}/stomp";
      WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
      stompClient.setMessageConverter(new StringMessageConverter());
      stompClient.setTaskScheduler(taskScheduler);
      stompClient.setDefaultHeartbeat(new long[] {0, 0});

      logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
      StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
      stopWatch.start();

      List<ConsumerStompSessionHandler> consumers = new ArrayList<>();
      for (int i = 0; i < NUMBER_OF_USERS; i++) {
        consumers.add(
            new ConsumerStompSessionHandler(
                BROADCAST_MESSAGE_COUNT,
                connectLatch,
                subscribeLatch,
                messageLatch,
                disconnectLatch,
                failure));
        stompClient.connect(stompUrl, consumers.get(i), host, port);
      }

      if (failure.get() != null) {
        throw new AssertionError("Test failed", failure.get());
      }
      if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
        fail("Not all users connected, remaining: " + connectLatch.getCount());
      }
      if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
        fail("Not all users subscribed, remaining: " + subscribeLatch.getCount());
      }

      stopWatch.stop();
      logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

      logger.debug(
          "Broadcasting "
              + BROADCAST_MESSAGE_COUNT
              + " messages to "
              + NUMBER_OF_USERS
              + " users ");
      stopWatch.start();

      ProducerStompSessionHandler producer =
          new ProducerStompSessionHandler(BROADCAST_MESSAGE_COUNT, failure);
      stompClient.connect(stompUrl, producer, host, port);
      stompClient.setTaskScheduler(taskScheduler);

      if (failure.get() != null) {
        throw new AssertionError("Test failed", failure.get());
      }
      if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
        for (ConsumerStompSessionHandler consumer : consumers) {
          if (consumer.messageCount.get() < consumer.expectedMessageCount) {
            logger.debug(consumer);
          }
        }
      }
      if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
        fail("Not all handlers received every message, remaining: " + messageLatch.getCount());
      }

      producer.session.disconnect();
      if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
        fail("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
      }

      stopWatch.stop();
      logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

      System.out.println("\nPress any key to exit...");
      System.in.read();
    } catch (Throwable t) {
      t.printStackTrace();
    } finally {
      jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
  }
示例#5
0
  @Override
  public void init() throws Exception {
    super.init();

    if (client == null) {
      client = new HttpClient(new SslContextFactory());
      client.setExecutor(new ExecutorThreadPool(threadPool));
      // configure timeout if set
      if (connectTimeout != -1) {
        client.setConnectTimeout(connectTimeout);
      }
      if (idleTimeout != -1) {
        client.setIdleTimeout(idleTimeout);
      }
      client.setMaxConnectionsPerDestination(maxConnectionsPerDestination);
      client.setMaxRequestsQueuedPerDestination(maxRequestsQueuedPerDestination);

      // Configure SSL - if relevant
      if (transportSSLEnabled) {
        KeyStoreManagement keyStore =
            KeyStoreManagement.getKeyStoreManagement(
                httpsKeystoreType, httpsKeystore, httpsKeyPassword);
        if (jmxControl != null && keyStore != null) {
          jmxControl.registerMBean(
              "CoUGAR:name=AsyncHttpClientKeyStore,beanName=" + beanName, keyStore);
        }
        KeyStoreManagement trustStore =
            KeyStoreManagement.getKeyStoreManagement(
                httpsTruststoreType, httpsTruststore, httpsTrustPassword);
        if (jmxControl != null) {
          jmxControl.registerMBean(
              "CoUGAR:name=AsyncHttpClientTrustStore,beanName=" + beanName, trustStore);
        }
        if (trustStore == null) {
          throw new IllegalStateException(
              "This configuration ostensibly supports TLS, yet doesn't provide valid truststore configuration");
        }

        final SslContextFactory sslContextFactory = client.getSslContextFactory();

        com.betfair.cougar.netutil.SslContextFactory factory =
            new com.betfair.cougar.netutil.SslContextFactory();
        factory.setTrustManagerFactoryKeyStore(trustStore.getKeyStore());
        if (keyStore != null) {
          factory.setKeyManagerFactoryKeyStore(keyStore.getKeyStore());
          factory.setKeyManagerFactoryKeyStorePassword(httpsKeyPassword);
        }
        SSLContext context = factory.newInstance();

        if (hostnameVerificationDisabled) {
          context.getDefaultSSLParameters().setEndpointIdentificationAlgorithm(null);
          LOGGER.warn(
              "CRITICAL SECURITY CHECKS ARE DISABLED: server SSL certificate hostname "
                  + "verification is turned off.");
        } else {
          context.getDefaultSSLParameters().setEndpointIdentificationAlgorithm("https");
        }

        sslContextFactory.setSslContext(context);
      }
      client.start();
      clientCreated = true;
    }

    metrics = new JettyTransportMetrics();

    if (jmxControl != null) {
      jmxControl.registerMBean("CoUGAR:name=AsyncHttpClientExecutable,beanName=" + beanName, this);
    }
  }