@AfterClass
  public static void stopServer() throws Exception {
    httpClient.stop();

    server.stop();
    server.join();
  }
 @After
 public void dispose() throws Exception {
   server1.stop();
   server2.stop();
   balancer.stop();
   client.stop();
 }
  @Override
  public void tearDown() throws Exception {

    // if (log.isInfoEnabled())
    log.warn("tearing down test: " + getName());

    if (m_fixture != null) {

      m_fixture.stop();

      m_fixture = null;
    }

    if (m_indexManager != null && namespace != null) {

      dropTripleStore(m_indexManager, namespace);

      m_indexManager = null;
    }

    namespace = null;

    m_rootURL = null;
    m_serviceURL = null;

    m_repo.close();

    m_client.stop();

    log.info("tear down done");

    super.tearDown();
  }
 public void stop() {
   try {
     client.stop();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
 @Override
 public void close() {
   try {
     client.stop();
   } catch (final Exception e) {
     throw new ProcessingException("Failed to stop the client.", e);
   }
 }
  @Test
  public void testSessionMigration() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    AbstractTestServer server1 = createServer(0);
    server1.addContext(contextPath).addServlet(TestServlet.class, servletMapping);

    try {
      server1.start();
      int port1 = server1.getPort();

      AbstractTestServer server2 = createServer(0);
      server2.addContext(contextPath).addServlet(TestServlet.class, servletMapping);

      try {
        server2.start();
        int port2 = server2.getPort();

        HttpClient client = new HttpClient();
        client.start();
        try {
          // Perform one request to server1 to create a session
          int value = 1;
          Request request1 =
              client.POST(
                  "http://localhost:"
                      + port1
                      + contextPath
                      + servletMapping
                      + "?action=set&value="
                      + value);
          ContentResponse response1 = request1.send();
          assertEquals(HttpServletResponse.SC_OK, response1.getStatus());
          String sessionCookie = response1.getHeaders().get("Set-Cookie");
          assertTrue(sessionCookie != null);
          // Mangle the cookie, replacing Path with $Path, etc.
          sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");

          // Perform a request to server2 using the session cookie from the previous request
          // This should migrate the session from server1 to server2.
          Request request2 =
              client.newRequest(
                  "http://localhost:" + port2 + contextPath + servletMapping + "?action=get");
          request2.header("Cookie", sessionCookie);
          ContentResponse response2 = request2.send();
          assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
          String response = response2.getContentAsString();
          assertEquals(response.trim(), String.valueOf(value));
        } finally {
          client.stop();
        }
      } finally {
        server2.stop();
      }
    } finally {
      server1.stop();
    }
  }
  @Test
  public void testAttributeNamesWithDots() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    int maxInactivePeriod = 10000;
    int scavengePeriod = 20000;
    AbstractTestServer server1 = createServer(0, maxInactivePeriod, scavengePeriod);
    server1.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
    server1.start();
    int port1 = server1.getPort();

    AbstractTestServer server2 = createServer(0, maxInactivePeriod, scavengePeriod);
    server2.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
    server2.start();
    int port2 = server2.getPort();

    try {

      HttpClient client = new HttpClient();
      client.start();
      try {

        // Perform one request to server1 to create a session with attribute with dotted name
        ContentResponse response =
            client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");

        assertEquals(HttpServletResponse.SC_OK, response.getStatus());

        String resp = response.getContentAsString();

        String[] sessionTestResponse = resp.split("/");
        assertEquals("a.b.c", sessionTestResponse[0]);

        String sessionCookie = response.getHeaders().get(HttpHeader.SET_COOKIE);

        assertTrue(sessionCookie != null);
        // Mangle the cookie, replacing Path with $Path, etc.
        sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");

        // Make a request to the 2nd server which will do a refresh, use TestServlet to ensure that
        // the
        // session attribute with dotted name is not removed
        Request request2 =
            client.newRequest(
                "http://localhost:" + port2 + contextPath + servletMapping + "?action=get");
        request2.header("Cookie", sessionCookie);
        ContentResponse response2 = request2.send();
        assertEquals(HttpServletResponse.SC_OK, response2.getStatus());

      } finally {
        client.stop();
      }
    } finally {
      server1.stop();
      server2.stop();
    }
  }
  /**
   * If nodeA creates a session, and just afterwards crashes, it is the only node that knows about
   * the session. We want to test that the session data is gone after scavenging.
   */
  @Test
  public void testOrphanedSession() throws Exception {
    // Disable scavenging for the first server, so that we simulate its "crash".
    String contextPath = "";
    String servletMapping = "/server";
    int inactivePeriod = 5;
    AbstractTestServer server1 = createServer(0, inactivePeriod, -1);
    server1.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
    try {
      server1.start();
      int port1 = server1.getPort();
      int scavengePeriod = 2;
      AbstractTestServer server2 = createServer(0, inactivePeriod, scavengePeriod);
      server2.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
      try {
        server2.start();
        int port2 = server2.getPort();
        HttpClient client = new HttpClient();
        client.start();
        try {
          // Connect to server1 to create a session and get its session cookie
          ContentResponse response1 =
              client.GET(
                  "http://localhost:" + port1 + contextPath + servletMapping + "?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=");

          // Wait for the session to expire.
          // The first node does not do any scavenging, but the session
          // must be removed by scavenging done in the other node.
          Thread.sleep(TimeUnit.SECONDS.toMillis(inactivePeriod + 2L * scavengePeriod));

          // Perform one request to server2 to be sure that the session has been expired
          Request request =
              client.newRequest(
                  "http://localhost:" + port2 + contextPath + servletMapping + "?action=check");
          request.header("Cookie", sessionCookie);
          ContentResponse response2 = request.send();
          assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
        } finally {
          client.stop();
        }
      } finally {
        server2.stop();
      }
    } finally {
      server1.stop();
    }
  }
  /** @throws Exception */
  public void testSessionRenewal() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    int maxInactive = 1;
    int scavengePeriod = 3;
    _server = createServer(0, maxInactive, scavengePeriod, SessionCache.NEVER_EVICT);
    WebAppContext context = _server.addWebAppContext(".", contextPath);
    context.setParentLoaderPriority(true);
    context.addServlet(TestServlet.class, servletMapping);
    TestHttpSessionIdListener testListener = new TestHttpSessionIdListener();
    context.addEventListener(testListener);

    HttpClient client = new HttpClient();
    try {
      _server.start();
      int port = _server.getPort();

      client.start();

      // make a request to create a session
      ContentResponse response =
          client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
      assertEquals(HttpServletResponse.SC_OK, response.getStatus());

      String sessionCookie = response.getHeaders().get("Set-Cookie");
      assertTrue(sessionCookie != null);
      assertFalse(testListener.isCalled());

      // make a request to change the sessionid
      Request request =
          client.newRequest(
              "http://localhost:" + port + contextPath + servletMapping + "?action=renew");
      request.header("Cookie", sessionCookie);
      ContentResponse renewResponse = request.send();

      assertEquals(HttpServletResponse.SC_OK, renewResponse.getStatus());
      String renewSessionCookie = renewResponse.getHeaders().get("Set-Cookie");
      assertNotNull(renewSessionCookie);
      assertNotSame(sessionCookie, renewSessionCookie);
      assertTrue(testListener.isCalled());

      assertTrue(
          verifyChange(
              context,
              AbstractTestServer.extractSessionId(sessionCookie),
              AbstractTestServer.extractSessionId(renewSessionCookie)));
    } finally {
      client.stop();
      _server.stop();
    }
  }
  @Test
  @Ignore("failing because an http cookie with null value is coming over as \"null\"")
  public void testSessionCookie() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    int scavengePeriod = 3;
    AbstractTestServer server = createServer(0, 1, scavengePeriod);
    ServletContextHandler context = server.addContext(contextPath);
    context.addServlet(TestServlet.class, servletMapping);

    try {
      server.start();
      int port = server.getPort();

      HttpClient client = new HttpClient();
      client.start();
      try {

        ContentResponse response =
            client.GET(
                "http://localhost:" + port + contextPath + servletMapping + "?action=create");
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());

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

        // Let's wait for the scavenger to run, waiting 2.5 times the scavenger period
        // pause(scavengePeriod);
        Request request =
            client.newRequest(
                "http://localhost:" + port + contextPath + servletMapping + "?action=check-cookie");
        request.header("Cookie", sessionCookie);
        response = request.send();

        assertEquals(HttpServletResponse.SC_OK, response.getStatus());

        request =
            client.newRequest(
                "http://localhost:" + port + contextPath + servletMapping + "?action=null-cookie");
        request.header("Cookie", sessionCookie);
        response = request.send();
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
      } finally {
        client.stop();
      }
    } finally {
      server.stop();
    }
  }
  protected static void runTest(String requestUrl, long count) {
    HttpClient client = new HttpClient();
    client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
    try {
      client.start();
    } catch (Exception ex) {
      LOG.debug(ex);
    }

    if (client != null) {
      for (long cnt = 0; cnt < count; cnt++) {
        try {
          ContentExchange getExchange = new ContentExchange();
          getExchange.setURL(requestUrl);
          getExchange.setMethod(HttpMethods.GET);

          client.send(getExchange);
          int state = getExchange.waitForDone();

          String content = "";
          int responseStatus = getExchange.getResponseStatus();
          if (responseStatus == HttpStatus.OK_200) {
            content = getExchange.getResponseContent();
          }

          Thread.sleep(100);
        } catch (InterruptedException ex) {
          break;
        } catch (IOException ex) {
          LOG.debug(ex);
        }
      }

      try {
        client.stop();
      } catch (Exception ex) {
        LOG.debug(ex);
      }
    }
  }
  @Test
  public void testJspDump() throws Exception {

    // System.err.println("http://127.0.0.1:9876/jsp/dump.jsp  sleeping....");
    // Thread.currentThread().sleep(5000000);
    // now test the jsp/dump.jsp
    HttpClient client = new HttpClient();
    try {
      client.start();
      ContentResponse response =
          client.GET(
              "http://127.0.0.1:"
                  + TestJettyOSGiBootCore.DEFAULT_JETTY_HTTP_PORT
                  + "/jsp/dump.jsp");
      Assert.assertEquals(HttpStatus.OK_200, response.getStatus());

      String content = new String(response.getContent());
      System.err.println("content: " + content);
      Assert.assertTrue(content.contains("<tr><th>ServletPath:</th><td>/jsp/dump.jsp</td></tr>"));
    } finally {
      client.stop();
    }
  }
  @Test
  public void testLastAccessTime() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    int maxInactivePeriod = 8;
    int scavengePeriod = 2;
    AbstractTestServer server1 = createServer(0, maxInactivePeriod, scavengePeriod);
    server1.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
    server1.start();
    int port1 = server1.getPort();
    try {
      AbstractTestServer server2 = createServer(0, maxInactivePeriod, scavengePeriod);
      server2.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
      server2.start();
      int port2 = server2.getPort();
      try {
        HttpClient client = new HttpClient();
        client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
        client.start();
        try {
          // Perform one request to server1 to create a session
          ContentExchange exchange1 = new ContentExchange(true);
          exchange1.setMethod(HttpMethods.GET);
          exchange1.setURL(
              "http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
          client.send(exchange1);
          exchange1.waitForDone();
          assertEquals(HttpServletResponse.SC_OK, exchange1.getResponseStatus());
          assertEquals("test", exchange1.getResponseContent());
          String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
          assertTrue(sessionCookie != null);
          // Mangle the cookie, replacing Path with $Path, etc.
          sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");

          // Perform some request to server2 using the session cookie from the previous request
          // This should migrate the session from server1 to server2, and leave server1's
          // session in a very stale state, while server2 has a very fresh session.
          // We want to test that optimizations done to the saving of the shared lastAccessTime
          // do not break the correct working
          int requestInterval = 500;
          for (int i = 0; i < maxInactivePeriod * (1000 / requestInterval); ++i) {
            ContentExchange exchange2 = new ContentExchange(true);
            exchange2.setMethod(HttpMethods.GET);
            exchange2.setURL("http://localhost:" + port2 + contextPath + servletMapping);
            exchange2.getRequestFields().add("Cookie", sessionCookie);
            client.send(exchange2);
            exchange2.waitForDone();
            assertEquals(HttpServletResponse.SC_OK, exchange2.getResponseStatus());
            assertEquals("test", exchange2.getResponseContent());

            String setCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
            if (setCookie != null)
              sessionCookie = setCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");

            Thread.sleep(requestInterval);
          }

          // At this point, session1 should be eligible for expiration.
          // Let's wait for the scavenger to run, waiting 2.5 times the scavenger period
          Thread.sleep(scavengePeriod * 2500L);

          // Access again server1, and ensure that we can still access the session
          exchange1 = new ContentExchange(true);
          exchange1.setMethod(HttpMethods.GET);
          exchange1.setURL("http://localhost:" + port1 + contextPath + servletMapping);
          exchange1.getRequestFields().add("Cookie", sessionCookie);
          client.send(exchange1);
          exchange1.waitForDone();
          assertEquals(HttpServletResponse.SC_OK, exchange1.getResponseStatus());
          // test that the session was kept alive by server 2 and still contains what server1 put in
          // it
          assertEquals("test", exchange1.getResponseContent());

        } finally {
          client.stop();
        }
      } finally {
        server2.stop();
      }
    } finally {
      server1.stop();
    }
  }
 @Override
 public void close() throws Exception {
   server.stop();
   client.stop();
   LOG.info("Onem2mHttpProvider Closed");
 }
 @After
 public void tearDown() throws Exception {
   server.stop();
   client.stop();
 }
 protected void stopClient() throws Exception {
   if (_client != null) {
     _client.stop();
     _client = null;
   }
 }
 public void shutdown() throws Exception {
   if (clientCreated) {
     client.stop();
   }
 }
  @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();
    }
  }
  @Test
  public void testLastAccessTime() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    int maxInactivePeriod = 8; // session will timeout after 8 seconds
    int scavengePeriod = 2; // scavenging occurs every 2 seconds
    AbstractTestServer server1 = createServer(0, maxInactivePeriod, scavengePeriod);
    TestServlet servlet1 = new TestServlet();
    ServletHolder holder1 = new ServletHolder(servlet1);
    ServletContextHandler context = server1.addContext(contextPath);
    TestSessionListener listener1 = new TestSessionListener();
    context.addEventListener(listener1);
    context.addServlet(holder1, servletMapping);
    server1.start();
    int port1 = server1.getPort();
    try {
      AbstractTestServer server2 = createServer(0, maxInactivePeriod, scavengePeriod);
      server2.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
      server2.start();
      int port2 = server2.getPort();
      try {
        HttpClient client = new HttpClient();
        client.start();
        try {
          // Perform one request to server1 to create a session
          Future<ContentResponse> future =
              client.GET(
                  "http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
          ContentResponse response1 = future.get();
          assertEquals(HttpServletResponse.SC_OK, response1.getStatus());
          assertEquals("test", response1.getContentAsString());
          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=");

          // Perform some request to server2 using the session cookie from the previous request
          // This should migrate the session from server1 to server2, and leave server1's
          // session in a very stale state, while server2 has a very fresh session.
          // We want to test that optimizations done to the saving of the shared lastAccessTime
          // do not break the correct working
          int requestInterval = 500;
          for (int i = 0; i < maxInactivePeriod * (1000 / requestInterval); ++i) {
            Request request =
                client.newRequest("http://localhost:" + port2 + contextPath + servletMapping);
            request.header("Cookie", sessionCookie);
            future = request.send();
            ContentResponse response2 = future.get();
            assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
            assertEquals("test", response2.getContentAsString());

            String setCookie = response2.getHeaders().getStringField("Set-Cookie");
            if (setCookie != null)
              sessionCookie = setCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");

            Thread.sleep(requestInterval);
          }

          // At this point, session1 should be eligible for expiration.
          // Let's wait for the scavenger to run, waiting 2.5 times the scavenger period
          Thread.sleep(scavengePeriod * 2500L);

          // check that the session was not scavenged over on server1 by ensuring that the
          // SessionListener destroy method wasn't called
          assertTrue(listener1.destroyed == false);
        } finally {
          client.stop();
        }
      } finally {
        server2.stop();
      }
    } finally {
      server1.stop();
    }
  }
 @After
 public void disposeProxy() throws Exception {
   client.stop();
   proxy.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);
  }
  @Test
  public void testRemoveSession() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    int scavengePeriod = 3;
    AbstractTestServer server = createServer(0, 1, scavengePeriod);
    ServletContextHandler context = server.addContext(contextPath);
    context.addServlet(TestServlet.class, servletMapping);
    TestEventListener testListener = new TestEventListener();
    context.getSessionHandler().addEventListener(testListener);
    AbstractSessionManager m =
        (AbstractSessionManager) context.getSessionHandler().getSessionManager();
    try {
      server.start();
      int port = server.getPort();

      HttpClient client = new HttpClient();
      client.start();
      try {
        ContentResponse response =
            client.GET(
                "http://localhost:" + port + contextPath + servletMapping + "?action=create");
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
        String sessionCookie = response.getHeaders().get("Set-Cookie");
        assertTrue(sessionCookie != null);
        // Mangle the cookie, replacing Path with $Path, etc.
        sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
        // ensure sessionCreated listener is called
        assertTrue(testListener.isCreated());
        assertEquals(1, m.getSessions());
        assertEquals(1, m.getSessionsMax());
        assertEquals(1, m.getSessionsTotal());

        // now delete the session
        Request request =
            client.newRequest(
                "http://localhost:" + port + contextPath + servletMapping + "?action=delete");
        request.header("Cookie", sessionCookie);
        response = request.send();
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
        // ensure sessionDestroyed listener is called
        assertTrue(testListener.isDestroyed());
        assertEquals(0, m.getSessions());
        assertEquals(1, m.getSessionsMax());
        assertEquals(1, m.getSessionsTotal());

        // The session is not there anymore, even if we present an old cookie
        request =
            client.newRequest(
                "http://localhost:" + port + contextPath + servletMapping + "?action=check");
        request.header("Cookie", sessionCookie);
        response = request.send();
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
        assertEquals(0, m.getSessions());
        assertEquals(1, m.getSessionsMax());
        assertEquals(1, m.getSessionsTotal());
      } finally {
        client.stop();
      }
    } finally {
      server.stop();
    }
  }
 protected void stopClient() throws Exception {
   if (httpClient != null) {
     httpClient.stop();
     httpClient = null;
   }
 }