@Test
  public void testTimerThreadLeak() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    if (ctx instanceof StandardContext) {
      ((StandardContext) ctx).setClearReferencesStopTimerThreads(true);
    }

    Tomcat.addServlet(ctx, "taskServlet", new TaskServlet());
    ctx.addServletMapping("/", "taskServlet");

    tomcat.start();

    // This will trigger the timer & thread creation
    getUrl("http://localhost:" + getPort() + "/");

    // Stop the context
    ctx.stop();

    Thread[] threads = getThreads();
    for (Thread thread : threads) {
      if (thread != null
          && thread.isAlive()
          && TaskServlet.TIMER_THREAD_NAME.equals(thread.getName())) {
        thread.join(5000);
        if (thread.isAlive()) {
          fail("Timer thread still running");
        }
      }
    }
  }
  private void setUpLogin() throws Exception {

    // Must have a real docBase for webapps - just use temp
    basicContext = tomcat.addContext(CONTEXT_PATH_LOGIN, System.getProperty("java.io.tmpdir"));
    basicContext.setSessionTimeout(SHORT_SESSION_TIMEOUT_MINS);

    // Add protected servlet to the context
    Tomcat.addServlet(basicContext, "TesterServlet3", new TesterServletEncodeUrl());
    basicContext.addServletMapping(URI_PROTECTED, "TesterServlet3");
    SecurityCollection collection = new SecurityCollection();
    collection.addPattern(URI_PROTECTED);
    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    basicContext.addConstraint(sc);

    // Add unprotected servlet to the context
    Tomcat.addServlet(basicContext, "TesterServlet4", new TesterServletEncodeUrl());
    basicContext.addServletMapping(URI_PUBLIC, "TesterServlet4");
    SecurityCollection collection2 = new SecurityCollection();
    collection2.addPattern(URI_PUBLIC);
    SecurityConstraint sc2 = new SecurityConstraint();
    // do not add a role - which signals access permitted without one
    sc2.addCollection(collection2);
    basicContext.addConstraint(sc2);

    // Configure the authenticator and inherit the Realm from Engine
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("BASIC");
    basicContext.setLoginConfig(lc);
    AuthenticatorBase basicAuthenticator = new BasicAuthenticator();
    basicContext.getPipeline().addValve(basicAuthenticator);
  }
  public void testListeners() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    File docBase = new File(System.getProperty("java.io.tmpdir"));

    Context ctx = tomcat.addContext("", docBase.getAbsolutePath());

    TrackingServlet tracking = new TrackingServlet();
    Wrapper wrapper = Tomcat.addServlet(ctx, "tracking", tracking);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/stage1", "tracking");

    TimeoutServlet timeout = new TimeoutServlet(true, null);
    Wrapper wrapper2 = Tomcat.addServlet(ctx, "timeout", timeout);
    wrapper2.setAsyncSupported(true);
    ctx.addServletMapping("/stage2", "timeout");

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/stage1");

    ByteChunk res = getUrl(url.toString());

    assertEquals(
        "DispatchingServletGet-DispatchingServletGet-onStartAsync-"
            + "TimeoutServletGet-onStartAsync-onTimeout-onComplete-",
        res.toString());
  }
예제 #4
0
  @Test
  public void testErrorPageHandling() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Add the error page
    Tomcat.addServlet(ctx, "error", new ErrorServlet());
    ctx.addServletMapping("/error", "error");

    // Add the error handling page
    Tomcat.addServlet(ctx, "report", new ReportServlet());
    ctx.addServletMapping("/report/*", "report");

    // And the handling for 500 responses
    ErrorPage errorPage500 = new ErrorPage();
    errorPage500.setErrorCode(Response.SC_INTERNAL_SERVER_ERROR);
    errorPage500.setLocation("/report/500");
    ctx.addErrorPage(errorPage500);

    // And the default error handling
    ErrorPage errorPageDefault = new ErrorPage();
    errorPageDefault.setLocation("/report/default");
    ctx.addErrorPage(errorPageDefault);

    tomcat.start();

    doTestErrorPageHandling(500, "/500");
    doTestErrorPageHandling(501, "/default");
  }
  private void setUpNonLogin(Tomcat tomcat) throws Exception {

    // Must have a real docBase for webapps - just use temp
    Context ctxt = tomcat.addContext(CONTEXT_PATH_NOLOGIN, System.getProperty("java.io.tmpdir"));
    ctxt.setSessionTimeout(LONG_TIMEOUT_SECS);

    // Add protected servlet
    Tomcat.addServlet(ctxt, "TesterServlet1", new TesterServlet());
    ctxt.addServletMapping(URI_PROTECTED, "TesterServlet1");

    SecurityCollection collection1 = new SecurityCollection();
    collection1.addPattern(URI_PROTECTED);
    SecurityConstraint sc1 = new SecurityConstraint();
    sc1.addAuthRole(ROLE);
    sc1.addCollection(collection1);
    ctxt.addConstraint(sc1);

    // Add unprotected servlet
    Tomcat.addServlet(ctxt, "TesterServlet2", new TesterServlet());
    ctxt.addServletMapping(URI_PUBLIC, "TesterServlet2");

    SecurityCollection collection2 = new SecurityCollection();
    collection2.addPattern(URI_PUBLIC);
    SecurityConstraint sc2 = new SecurityConstraint();
    // do not add a role - which signals access permitted without one
    sc2.addCollection(collection2);
    ctxt.addConstraint(sc2);

    // Configure the authenticator and inherit the Realm from Engine
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("NONE");
    ctxt.setLoginConfig(lc);
    ctxt.getPipeline().addValve(new NonLoginAuthenticator());
  }
예제 #6
0
  @Test
  public void testFlagFailCtxIfServletStartFails() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File docBase = new File(System.getProperty("java.io.tmpdir"));
    StandardContext context = (StandardContext) tomcat.addContext("", docBase.getAbsolutePath());

    // first we test the flag itself, which can be set on the Host and
    // Context
    assertFalse(context.getComputedFailCtxIfServletStartFails());

    StandardHost host = (StandardHost) tomcat.getHost();
    host.setFailCtxIfServletStartFails(true);
    assertTrue(context.getComputedFailCtxIfServletStartFails());
    context.setFailCtxIfServletStartFails(Boolean.FALSE);
    assertFalse(
        "flag on Context should override Host config",
        context.getComputedFailCtxIfServletStartFails());

    // second, we test the actual effect of the flag on the startup
    Wrapper servlet = Tomcat.addServlet(context, "myservlet", new FailingStartupServlet());
    servlet.setLoadOnStartup(1);

    tomcat.start();
    assertTrue("flag false should not fail deployment", context.getState().isAvailable());

    tomcat.stop();
    assertFalse(context.getState().isAvailable());

    host.removeChild(context);
    context = (StandardContext) tomcat.addContext("", docBase.getAbsolutePath());
    servlet = Tomcat.addServlet(context, "myservlet", new FailingStartupServlet());
    servlet.setLoadOnStartup(1);
    tomcat.start();
    assertFalse("flag true should fail deployment", context.getState().isAvailable());
  }
예제 #7
0
    private FormAuthClientSelectedMethods(
        boolean clientShouldUseCookies,
        boolean serverShouldUseCookies,
        boolean serverShouldChangeSessid)
        throws Exception {

      Tomcat tomcat = getTomcatInstance();

      // No file system docBase required
      Context ctx = tomcat.addContext("", null);
      Tomcat.addServlet(ctx, "SelectedMethods", new SelectedMethodsServlet());
      ctx.addServletMapping("/test", "SelectedMethods");
      // Login servlet just needs to respond "OK". Client will handle
      // creating a valid response. No need for a form.
      Tomcat.addServlet(ctx, "Login", new TesterServlet());
      ctx.addServletMapping("/login", "Login");

      // Configure the security constraints
      SecurityConstraint constraint = new SecurityConstraint();
      SecurityCollection collection = new SecurityCollection();
      collection.setName("Protect PUT");
      collection.addMethod("PUT");
      collection.addPattern("/test");
      constraint.addCollection(collection);
      constraint.addAuthRole("tomcat");
      ctx.addConstraint(constraint);

      // Configure authentication
      LoginConfig lc = new LoginConfig();
      lc.setAuthMethod("FORM");
      lc.setLoginPage("/login");
      ctx.setLoginConfig(lc);
      ctx.getPipeline().addValve(new FormAuthenticator());

      setUseCookies(clientShouldUseCookies);
      ctx.setCookies(serverShouldUseCookies);

      MapRealm realm = new MapRealm();
      realm.addUser("tomcat", "tomcat");
      realm.addUserRole("tomcat", "tomcat");
      ctx.setRealm(realm);

      tomcat.start();

      // perhaps this does not work until tomcat has started?
      ctx.setSessionTimeout(TIMEOUT_MINS);

      // Valve pipeline is only established after tomcat starts
      Valve[] valves = ctx.getPipeline().getValves();
      for (Valve valve : valves) {
        if (valve instanceof AuthenticatorBase) {
          ((AuthenticatorBase) valve).setChangeSessionIdOnAuthentication(serverShouldChangeSessid);
          break;
        }
      }

      // Port only known after Tomcat starts
      setPort(getPort());
    }
예제 #8
0
  @Test
  public void testConnectionClose() throws Exception {
    Assume.assumeTrue(
        "This test is skipped, because this connector does not support Comet.", isCometSupported());

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Tomcat.addServlet(root, "comet", new ConnectionCloseServlet());
    root.addServletMapping("/comet", "comet");
    Tomcat.addServlet(root, "hello", new HelloWorldServlet());
    root.addServletMapping("/hello", "hello");
    tomcat.getConnector().setProperty("connectionTimeout", "5000");
    tomcat.start();

    // Create connection to Comet servlet
    final Socket socket = SocketFactory.getDefault().createSocket("localhost", getPort());
    socket.setSoTimeout(5000);

    final OutputStream os = socket.getOutputStream();
    String requestLine = "POST http://localhost:" + getPort() + "/comet HTTP/1.1\r\n";
    os.write(requestLine.getBytes());
    os.write("transfer-encoding: chunked\r\n".getBytes());
    os.write("\r\n".getBytes());
    // Don't send any data
    os.write("0\r\n\r\n".getBytes());

    InputStream is = socket.getInputStream();
    ResponseReaderThread readThread = new ResponseReaderThread(is);
    readThread.start();

    // Wait for the comet request/response to finish
    int count = 0;
    while (count < 10 && !readThread.getResponse().endsWith("OK")) {
      Thread.sleep(500);
      count++;
    }

    if (count == 10) {
      fail("Comet request did not complete");
    }

    // Read thread should have terminated cleanly when the server closed the
    // socket
    Assert.assertFalse(readThread.isAlive());
    Assert.assertNull(readThread.getException());

    os.close();
    is.close();
  }
예제 #9
0
  public static void addServlets(Tomcat tomcat) {
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Tomcat.addServlet(ctx, path, new TestBug49158Servlet());
    ctx.addServletMapping("/" + path, path);
  }
예제 #10
0
  @Test
  public void testBug56042() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Bug56042Servlet bug56042Servlet = new Bug56042Servlet();
    Wrapper wrapper = Tomcat.addServlet(ctx, "bug56042Servlet", bug56042Servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/bug56042Servlet", "bug56042Servlet");

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/bug56042Servlet");

    ByteChunk res = new ByteChunk();
    int rc = getUrl(url.toString(), res, null);

    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);
  }
  @Test
  public void testPathParamsRedirect() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    File docBase = new File(System.getProperty("java.io.tmpdir"));

    // Create the folder that will trigger the redirect
    File foo = new File(docBase, "foo");
    addDeleteOnTearDown(foo);
    if (!foo.mkdirs() && !foo.isDirectory()) {
      Assert.fail("Unable to create foo directory in docBase");
    }

    Context ctx = tomcat.addContext("", docBase.getAbsolutePath());

    Tomcat.addServlet(ctx, "servlet", new PathParamServlet());
    ctx.addServletMapping("/", "servlet");

    tomcat.start();

    testPath("/", "none");
    testPath("/;jsessionid=1234", "1234");
    testPath("/foo;jsessionid=1234", "1234");
    testPath("/foo;jsessionid=1234;dummy", "1234");
    testPath("/foo;jsessionid=1234;dummy=5678", "1234");
    testPath("/foo;jsessionid=1234;=5678", "1234");
    testPath("/foo;jsessionid=1234/bar", "1234");
  }
  public void testAsyncStartNoComplete() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Minimise pauses during test
    tomcat.getConnector().setAttribute("connectionTimeout", Integer.valueOf(3000));

    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));

    AsyncStartNoCompleteServlet servlet = new AsyncStartNoCompleteServlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/", "servlet");

    tomcat.start();

    // Call the servlet the first time
    ByteChunk bc1 = getUrl("http://localhost:" + getPort() + "/?echo=run1");
    assertEquals("OK-run1", bc1.toString());

    // Call the servlet the second time with a request parameter
    ByteChunk bc2 = getUrl("http://localhost:" + getPort() + "/?echo=run2");
    assertEquals("OK-run2", bc2.toString());
  }
  @Test
  public void testConnectToServerEndpoint() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(
        new ApplicationListener(TesterEchoServer.Config.class.getName(), false));
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    Session wsSession =
        wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText(MESSAGE_STRING_1);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    Assert.assertEquals(MESSAGE_STRING_1, messages.peek());
  }
  public void testBug49567() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));

    Bug49567Servlet servlet = new Bug49567Servlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/", "servlet");

    tomcat.start();

    // Call the servlet once
    ByteChunk bc = getUrl("http://localhost:" + getPort() + "/");
    assertEquals("OK", bc.toString());

    // Give the async thread a chance to finish (but not too long)
    int counter = 0;
    while (!servlet.isDone() && counter < 10) {
      Thread.sleep(1000);
      counter++;
    }

    assertEquals("1false2true3true4true5false", servlet.getResult());
  }
    private Exception doRequest() {

      Tomcat tomcat = getTomcatInstance();

      Context root = tomcat.addContext("", TEMP_DIR);
      Tomcat.addServlet(root, "Bug54947", new TesterServlet());
      root.addServletMapping("/test", "Bug54947");

      try {
        tomcat.start();
        setPort(tomcat.getConnector().getLocalPort());

        // Open connection
        connect();

        String[] request = new String[2];
        request[0] = "GET http://localhost:8080/test HTTP/1.1" + CR;
        request[1] = LF + "Connection: close" + CRLF + CRLF;

        setRequest(request);
        processRequest(); // blocks until response has been read

        // Close the connection
        disconnect();
      } catch (Exception e) {
        return e;
      }
      return null;
    }
    private void doRequest() throws Exception {
      Tomcat tomcat = getTomcatInstance();
      Context root = tomcat.addContext("", TEMP_DIR);
      Tomcat.addServlet(root, "Simple", new SimpleServlet());
      root.addServletMapping("/test", "Simple");

      tomcat.start();
      // Open connection
      setPort(tomcat.getConnector().getLocalPort());
      connect();

      String[] request = new String[1];
      request[0] =
          "GET /test HTTP/1.0"
              + CRLF
              + "Cookie: "
              + COOKIE_WITH_NAME_ONLY_1
              + CRLF
              + "Cookie: "
              + COOKIE_WITH_NAME_ONLY_2
              + CRLF
              + CRLF;
      setRequest(request);
      processRequest(true); // blocks until response has been read
      String response = getResponseBody();

      // Close the connection
      disconnect();
      reset();
      tomcat.stop();
      // Need the extra equals since cookie 1 is just the name
      assertEquals(COOKIE_WITH_NAME_ONLY_1 + "=" + COOKIE_WITH_NAME_ONLY_2, response);
    }
  private void doMaxMessageSize(String path, long size, boolean expectOpen) throws Exception {

    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(
        new ApplicationListener(TesterEchoServer.Config.class.getName(), false));
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    Session s = connectToEchoServer(wsContainer, EndpointA.class, path);

    StringBuilder msg = new StringBuilder();
    for (long i = 0; i < size; i++) {
      msg.append('x');
    }

    s.getBasicRemote().sendText(msg.toString());

    // Wait for up to 5 seconds for session to close
    boolean open = s.isOpen();
    int count = 0;
    while (open != expectOpen && count < 50) {
      Thread.sleep(100);
      count++;
      open = s.isOpen();
    }

    Assert.assertEquals(Boolean.valueOf(expectOpen), Boolean.valueOf(s.isOpen()));
  }
예제 #18
0
  @Test
  public void testBug58232() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug54807Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Assert.assertEquals(LifecycleState.STARTED, ctx.getState());

    SimpleClient client = new SimpleClient();
    URI uri = new URI("ws://localhost:" + getPort() + "/echoBasic");

    try (Session session = wsContainer.connectToServer(client, uri); ) {
      CountDownLatch latch = new CountDownLatch(1);
      BasicText handler = new BasicText(latch);
      session.addMessageHandler(handler);
      session.getBasicRemote().sendText("echoBasic");

      boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
      Assert.assertTrue(latchResult);

      Queue<String> messages = handler.getMessages();
      Assert.assertEquals(1, messages.size());
      for (String message : messages) {
        Assert.assertEquals("echoBasic", message);
      }
    }
  }
  protected static void configureClientCertContext(Tomcat tomcat) {
    TesterSupport.initSsl(tomcat);

    // Need a web application with a protected and unprotected URL
    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));

    Tomcat.addServlet(ctx, "simple", new SimpleServlet());
    ctx.addServletMapping("/unprotected", "simple");
    ctx.addServletMapping("/protected", "simple");

    // Security constraints
    SecurityCollection collection = new SecurityCollection();
    collection.addPattern("/protected");
    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole("testrole");
    sc.addCollection(collection);
    ctx.addConstraint(sc);

    // Configure the Realm
    MapRealm realm = new MapRealm();
    realm.addUser("CN=user1, C=US", "not used");
    realm.addUserRole("CN=user1, C=US", "testrole");
    ctx.setRealm(realm);

    // Configure the authenticator
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("CLIENT-CERT");
    ctx.setLoginConfig(lc);
    ctx.getPipeline().addValve(new SSLAuthenticator());
  }
  @Test
  public void testBug51653b() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Traces order of events across multiple components
    StringBuilder trace = new StringBuilder();

    // Add the page that generates the error
    Tomcat.addServlet(ctx, "test", new Bug51653ErrorTrigger());
    ctx.addServletMapping("/test", "test");

    // Add the error page
    Tomcat.addServlet(ctx, "errorPage", new Bug51653ErrorPage(trace));
    ctx.addServletMapping("/error", "errorPage");
    // And the handling for 404 responses
    ErrorPage errorPage = new ErrorPage();
    errorPage.setErrorCode(Response.SC_NOT_FOUND);
    errorPage.setLocation("/error");
    ctx.addErrorPage(errorPage);

    // Add the request listener
    Bug51653RequestListener reqListener = new Bug51653RequestListener(trace);
    ((StandardContext) ctx).addApplicationEventListener(reqListener);

    tomcat.start();

    // Request a page that does not exist
    int rc = getUrl("http://localhost:" + getPort() + "/test", new ByteChunk(), null);

    // Need to allow time (but not too long in case the test fails) for
    // ServletRequestListener to complete
    int i = 20;
    while (i > 0) {
      if (trace.toString().endsWith("Destroy")) {
        break;
      }
      Thread.sleep(250);
      i--;
    }

    assertEquals(Response.SC_NOT_FOUND, rc);
    assertEquals("InitErrorDestroy", trace.toString());
  }
예제 #21
0
  @Override
  public void construct() {
    tomcat = new Tomcat();

    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setURIEncoding("UTF-8");
    connector.setPort(5000);
    tomcat.getService().addConnector(connector);
    tomcat.setConnector(connector);

    try {
      Context ctx;

      if (new File(Configuration.WEBROOT_PATH).exists()) {
        L.i("Static web client found.");

        ctx = tomcat.addContext("", Configuration.WEBROOT_PATH);
        ctx.addWelcomeFile("index.html");

        Wrapper wrapper = tomcat.addServlet(ctx, "DefaultServlet", new DefaultServlet());
        wrapper.setAsyncSupported(true);
        wrapper.addInitParameter("listings", "false");
        wrapper.addMapping("/");
        wrapper.setLoadOnStartup(1);
      } else {
        L.w("No static web client found, web interface will not be available.");
        ctx = tomcat.addContext("/", "/tmp");
      }

      configureMimeMappings(ctx);

      addSessionFilter(ctx);
      addCharacterEncodingFilter(ctx);

      Wrapper wrapper = tomcat.addServlet(ctx, "JerseyServlet", new ServletContainer());
      wrapper.setAsyncSupported(true);
      wrapper.addInitParameter("javax.ws.rs.Application", JerseyApplication.class.getName());
      wrapper.addMapping("/api/*");
      wrapper.setLoadOnStartup(1);

      tomcat.start();
    } catch (Exception e) {
      L.e("Failed to start RestApiModule.", e);
    }
  }
  private void doTestWriteTimeoutServer(boolean setTimeoutOnContainer) throws Exception {

    /*
     * Note: There are all sorts of horrible uses of statics in this test
     *       because the API uses classes and the tests really need access
     *       to the instances which simply isn't possible.
     */
    timoutOnContainer = setTimeoutOnContainer;

    Tomcat tomcat = getTomcatInstance();

    if (getProtocol().equals(Http11Protocol.class.getName())) {
      // This will never work for BIO
      return;
    }

    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(new ApplicationListener(ConstantTxConfig.class.getName(), false));
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Session wsSession =
        wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://localhost:" + getPort() + ConstantTxConfig.PATH));

    wsSession.addMessageHandler(new BlockingBinaryHandler());

    int loops = 0;
    while (loops < 15) {
      Thread.sleep(1000);
      if (!ConstantTxEndpoint.getRunning()) {
        break;
      }
      loops++;
    }

    // Check the right exception was thrown
    Assert.assertNotNull(ConstantTxEndpoint.getException());
    Assert.assertEquals(ExecutionException.class, ConstantTxEndpoint.getException().getClass());
    Assert.assertNotNull(ConstantTxEndpoint.getException().getCause());
    Assert.assertEquals(
        SocketTimeoutException.class, ConstantTxEndpoint.getException().getCause().getClass());

    // Check correct time passed
    Assert.assertTrue(ConstantTxEndpoint.getTimeout() >= TIMEOUT_MS);

    // Check the timeout wasn't too long
    Assert.assertTrue(ConstantTxEndpoint.getTimeout() < TIMEOUT_MS * 2);
  }
 // Fireup tomcat and register this servlet
 public static void main(String[] args) throws LifecycleException, SQLException {
   Tomcat tomcat = new Tomcat();
   tomcat.setPort(8080);
   File base = new File(System.getProperty("java.io.tmpdir"));
   Context rootCtx = tomcat.addContext("/", base.getAbsolutePath());
   Tomcat.addServlet(rootCtx, "log", new LogService());
   rootCtx.addServletMapping("/*", "log");
   tomcat.start();
   tomcat.getServer().await();
 }
  private void doTestDispatchError(int iter, boolean useThread, boolean completeOnError)
      throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    File docBase = new File(System.getProperty("java.io.tmpdir"));

    Context ctx = tomcat.addContext("", docBase.getAbsolutePath());

    DispatchingServlet dispatch = new DispatchingServlet(true, completeOnError);
    Wrapper wrapper = Tomcat.addServlet(ctx, "dispatch", dispatch);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/stage1", "dispatch");

    ErrorServlet error = new ErrorServlet();
    Tomcat.addServlet(ctx, "error", error);
    ctx.addServletMapping("/stage2", "error");

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/stage1?iter=");
    url.append(iter);
    if (useThread) {
      url.append("&useThread=y");
    }
    ByteChunk res = getUrl(url.toString());

    StringBuilder expected = new StringBuilder();
    int loop = iter;
    while (loop > 0) {
      expected.append("DispatchingServletGet-");
      if (loop != iter) {
        expected.append("onStartAsync-");
      }
      loop--;
    }
    expected.append("ErrorServletGet-onError-onComplete-");
    assertEquals(expected.toString(), res.toString());
  }
  private void doTestWriteTimeoutClient(boolean setTimeoutOnContainer) throws Exception {

    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(new ApplicationListener(BlockingConfig.class.getName(), false));
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    // Set the async timeout
    if (setTimeoutOnContainer) {
      wsContainer.setAsyncSendTimeout(TIMEOUT_MS);
    }

    tomcat.start();

    Session wsSession =
        wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://localhost:" + getPort() + BlockingConfig.PATH));

    if (!setTimeoutOnContainer) {
      wsSession.getAsyncRemote().setSendTimeout(TIMEOUT_MS);
    }

    long lastSend = 0;

    // Should send quickly until the network buffers fill up and then block
    // until the timeout kicks in
    Exception exception = null;
    try {
      while (true) {
        Future<Void> f = wsSession.getAsyncRemote().sendBinary(ByteBuffer.wrap(MESSAGE_BINARY_4K));
        lastSend = System.currentTimeMillis();
        f.get();
      }
    } catch (Exception e) {
      exception = e;
    }

    long timeout = System.currentTimeMillis() - lastSend;

    String msg = "Time out was [" + timeout + "] ms";

    // Check correct time passed
    Assert.assertTrue(msg, timeout >= TIMEOUT_MS - MARGIN);

    // Check the timeout wasn't too long
    Assert.assertTrue(msg, timeout < TIMEOUT_MS * 2);

    Assert.assertNotNull(exception);
  }
  /*
   * Test {@link RemoteIpFilter} in Tomcat standalone server
   */
  @Test
  public void testWithTomcatServer() throws Exception {

    // mostly default configuration : enable "x-forwarded-proto"
    Map<String, String> remoteIpFilterParameter = new HashMap<>();
    remoteIpFilterParameter.put("protocolHeader", "x-forwarded-proto");

    // SETUP
    Tomcat tomcat = getTomcatInstance();
    Context root = tomcat.addContext("", TEMP_DIR);

    FilterDef filterDef = new FilterDef();
    filterDef.getParameterMap().putAll(remoteIpFilterParameter);
    filterDef.setFilterClass(RemoteIpFilter.class.getName());
    filterDef.setFilterName(RemoteIpFilter.class.getName());

    root.addFilterDef(filterDef);

    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(RemoteIpFilter.class.getName());
    filterMap.addURLPattern("*");
    root.addFilterMap(filterMap);

    MockHttpServlet mockServlet = new MockHttpServlet();

    Tomcat.addServlet(root, mockServlet.getClass().getName(), mockServlet);
    root.addServletMapping("/test", mockServlet.getClass().getName());

    getTomcatInstance().start();

    // TEST
    HttpURLConnection httpURLConnection =
        (HttpURLConnection)
            new URL("http://localhost:" + tomcat.getConnector().getLocalPort() + "/test")
                .openConnection();
    String expectedRemoteAddr = "my-remote-addr";
    httpURLConnection.addRequestProperty("x-forwarded-for", expectedRemoteAddr);
    httpURLConnection.addRequestProperty("x-forwarded-proto", "https");

    // VALIDATE

    Assert.assertEquals(HttpURLConnection.HTTP_OK, httpURLConnection.getResponseCode());
    HttpServletRequest request = mockServlet.getRequest();
    Assert.assertNotNull(request);

    // VALIDATE X-FOWARDED-FOR
    Assert.assertEquals(expectedRemoteAddr, request.getRemoteAddr());
    Assert.assertEquals(expectedRemoteAddr, request.getRemoteHost());

    // VALIDATE X-FORWARDED-PROTO
    Assert.assertTrue(request.isSecure());
    Assert.assertEquals("https", request.getScheme());
    Assert.assertEquals(443, request.getServerPort());
  }
예제 #27
0
    private synchronized void init() throws Exception {
      if (init) return;

      Tomcat tomcat = getTomcatInstance();
      context = tomcat.addContext("", TEMP_DIR);
      Tomcat.addServlet(context, "regular", new Bug49711Servlet());
      Wrapper w = Tomcat.addServlet(context, "multipart", new Bug49711Servlet_multipart());

      // Tomcat.addServlet does not respect annotations, so we have
      // to set our own MultipartConfigElement.
      w.setMultipartConfigElement(new MultipartConfigElement(""));

      context.addServletMapping("/regular", "regular");
      context.addServletMapping("/multipart", "multipart");
      tomcat.start();

      setPort(tomcat.getConnector().getLocalPort());

      init = true;
    }
  private void doTestTimeout(boolean completeOnTimeout, String dispatchUrl) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    File docBase = new File(System.getProperty("java.io.tmpdir"));

    // Create the folder that will trigger the redirect
    File foo = new File(docBase, "async");
    if (!foo.exists() && !foo.mkdirs()) {
      fail("Unable to create async directory in docBase");
    }

    Context ctx = tomcat.addContext("", docBase.getAbsolutePath());

    TimeoutServlet timeout = new TimeoutServlet(completeOnTimeout, dispatchUrl);

    Wrapper wrapper = Tomcat.addServlet(ctx, "time", timeout);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/async", "time");

    if (dispatchUrl != null) {
      NonAsyncServlet nonAsync = new NonAsyncServlet();
      Tomcat.addServlet(ctx, "nonasync", nonAsync);
      ctx.addServletMapping(dispatchUrl, "nonasync");
    }

    tomcat.start();
    ByteChunk res = getUrl("http://localhost:" + getPort() + "/async");
    StringBuilder expected = new StringBuilder();
    expected.append("TimeoutServletGet-onTimeout-");
    if (!completeOnTimeout) {
      expected.append("onError-");
    }
    if (dispatchUrl == null) {
      expected.append("onComplete-");
    } else {
      expected.append("NonAsyncServletGet-");
    }
    assertEquals(expected.toString(), res.toString());
  }
  @Test
  public void testSessionExpiryContainer() throws Exception {

    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(
        new ApplicationListener(TesterEchoServer.Config.class.getName(), false));
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    // Need access to implementation methods for configuring unit tests
    WsWebSocketContainer wsContainer =
        (WsWebSocketContainer) ContainerProvider.getWebSocketContainer();

    // 5 second timeout
    wsContainer.setDefaultMaxSessionIdleTimeout(5000);
    wsContainer.setProcessPeriod(1);

    connectToEchoServer(wsContainer, EndpointA.class, TesterEchoServer.Config.PATH_BASIC);
    connectToEchoServer(wsContainer, EndpointA.class, TesterEchoServer.Config.PATH_BASIC);
    Session s3a =
        connectToEchoServer(wsContainer, EndpointA.class, TesterEchoServer.Config.PATH_BASIC);

    // Check all three sessions are open
    Set<Session> setA = s3a.getOpenSessions();
    Assert.assertEquals(3, setA.size());

    int count = 0;
    boolean isOpen = true;
    while (isOpen && count < 8) {
      count++;
      Thread.sleep(1000);
      isOpen = false;
      for (Session session : setA) {
        if (session.isOpen()) {
          isOpen = true;
          break;
        }
      }
    }

    if (isOpen) {
      for (Session session : setA) {
        if (session.isOpen()) {
          System.err.println("Session with ID [" + session.getId() + "] is open");
        }
      }
      Assert.fail("There were open sessions");
    }
  }
예제 #30
0
  @Test
  public void testBug54807() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug54807Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    Assert.assertEquals(LifecycleState.STARTED, ctx.getState());
  }