@Test
  public void createsMetricsForTheHandler() throws Exception {
    final ContentResponse response =
        client.GET("http://localhost:" + connector.getLocalPort() + "/hello");

    assertThat(response.getStatus()).isEqualTo(404);

    assertThat(registry.getNames())
        .containsOnly(
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.1xx-responses",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.2xx-responses",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.3xx-responses",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.4xx-responses",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.5xx-responses",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.active-suspended",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.async-dispatches",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.async-timeouts",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.get-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.put-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.active-dispatches",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.trace-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.other-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.connect-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.dispatches",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.head-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.post-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.options-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.active-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.delete-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.move-requests");
  }
  @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();
    }
  }
  @Test
  public void testProxyXForwardedHostHeaderIsPresent() throws Exception {
    prepareProxy();
    prepareServer(
        new HttpServlet() {
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws ServletException, IOException {
            PrintWriter writer = resp.getWriter();
            writer.write(req.getHeader("X-Forwarded-Host"));
            writer.flush();
          }
        });

    ContentResponse response = client.GET("http://localhost:" + serverConnector.getLocalPort());
    Assert.assertThat(
        "Response expected to contain content of X-Forwarded-Host Header from the request",
        response.getContentAsString(),
        Matchers.equalTo("localhost:" + serverConnector.getLocalPort()));
  }
  @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 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 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();
    }
  }
  @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();
    }
  }