@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");
        }
      }
    }
  }
  @Test
  public void testParallelIncapableOnJre6() {
    if (JreCompat.isJre7Available()) {
      // ignore on Jre7 or above
      return;
    }
    try {
      Tomcat tomcat = getTomcatInstance();
      // Must have a real docBase - just use temp
      Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));

      WebappLoader webappLoader = new WebappLoader();
      webappLoader.setLoaderClass(PARALLEL_CLASSLOADER);
      ctx.setLoader(webappLoader);

      tomcat.start();

      ClassLoader classloader = ctx.getLoader().getClassLoader();

      Assert.assertTrue(classloader instanceof ParallelWebappClassLoader);

      // parallel class loading capable
      Method getClassLoadingLock =
          getDeclaredMethod(classloader.getClass(), "getClassLoadingLock", String.class);
      // make sure we don't have getClassLoadingLock on JRE6.
      Assert.assertNull(getClassLoadingLock);
    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail("testParallelIncapableOnJre6 fails.");
    }
  }
  @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);
  }
  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());
  }
  private void doTestBug51376(boolean loadOnStartUp) throws Exception {
    // Test that for a servlet that was added programmatically its
    // loadOnStartup property is honored and its init() and destroy()
    // methods are called.

    // Set up a container
    Tomcat tomcat = getTomcatInstance();

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

    // Add ServletContainerInitializer
    Bug51376SCI sci = new Bug51376SCI(loadOnStartUp);
    ctx.addServletContainerInitializer(sci, null);

    // Start the context
    tomcat.start();

    // Stop the context
    ctx.stop();

    // Make sure that init() and destroy() were called correctly
    assertTrue(sci.getServlet().isOk());
    assertTrue(loadOnStartUp == sci.getServlet().isInitCalled());
  }
Beispiel #6
0
  @AfterClass
  public static void cleanup() {
    try {
      if (idpServer.getServer() != null
          && idpServer.getServer().getState() != LifecycleState.DESTROYED) {
        if (idpServer.getServer().getState() != LifecycleState.STOPPED) {
          idpServer.stop();
        }
        idpServer.destroy();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      if (rpServer.getServer() != null
          && rpServer.getServer().getState() != LifecycleState.DESTROYED) {
        if (rpServer.getServer().getState() != LifecycleState.STOPPED) {
          rpServer.stop();
        }
        rpServer.destroy();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  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()));
  }
  @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");
  }
Beispiel #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);
  }
    private FormAuthClient(
        boolean clientShouldUseCookies,
        boolean serverShouldUseCookies,
        boolean serverShouldChangeSessid)
        throws Exception {

      Tomcat tomcat = getTomcatInstance();
      File appDir = new File(getBuildDirectory(), "webapps/examples");
      Context ctx = tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
      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());
    }
  @Override
  public void testCookiesInstance() throws Exception {

    System.setProperty("org.apache.catalina.STRICT_SERVLET_COMPLIANCE", "true");
    System.setProperty("org.apache.tomcat.util.http.ServerCookie.FWD_SLASH_IS_SEPARATOR", "false");

    Tomcat tomcat = getTomcatInstance();

    addServlets(tomcat);

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + "/invalid");
    assertEquals("Cookie name fail", res.toString());
    res = getUrl("http://localhost:" + getPort() + "/null");
    assertEquals("Cookie name fail", res.toString());
    res = getUrl("http://localhost:" + getPort() + "/blank");
    assertEquals("Cookie name fail", res.toString());
    res = getUrl("http://localhost:" + getPort() + "/invalidFwd");
    assertEquals("Cookie name ok", res.toString());
    res = getUrl("http://localhost:" + getPort() + "/invalidStrict");
    assertEquals("Cookie name fail", res.toString());
    res = getUrl("http://localhost:" + getPort() + "/valid");
    assertEquals("Cookie name ok", res.toString());
  }
  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());
  }
  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());
  }
  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());
  }
  protected static void initSsl(
      Tomcat tomcat, String keystore, String keystorePass, String keyPass) {

    String protocol = tomcat.getConnector().getProtocolHandlerClassName();
    if (protocol.indexOf("Apr") == -1) {
      Connector connector = tomcat.getConnector();
      connector.setProperty("sslProtocol", "tls");
      File keystoreFile = new File("test/org/apache/tomcat/util/net/" + keystore);
      connector.setAttribute("keystoreFile", keystoreFile.getAbsolutePath());
      File truststoreFile = new File("test/org/apache/tomcat/util/net/ca.jks");
      connector.setAttribute("truststoreFile", truststoreFile.getAbsolutePath());
      if (keystorePass != null) {
        connector.setAttribute("keystorePass", keystorePass);
      }
      if (keyPass != null) {
        connector.setAttribute("keyPass", keyPass);
      }
    } else {
      File keystoreFile = new File("test/org/apache/tomcat/util/net/localhost-cert.pem");
      tomcat.getConnector().setAttribute("SSLCertificateFile", keystoreFile.getAbsolutePath());
      keystoreFile = new File("test/org/apache/tomcat/util/net/localhost-key.pem");
      tomcat.getConnector().setAttribute("SSLCertificateKeyFile", keystoreFile.getAbsolutePath());
    }
    tomcat.getConnector().setSecure(true);
    tomcat.getConnector().setProperty("SSLEnabled", "true");
  }
    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;
    }
  @Test
  public void testWebappListenerConfigureFail() throws Exception {
    // Test that if LifecycleListener on webapp fails during
    // configure_start event and if the cause of the failure is gone,
    // the context can be started without a need to redeploy it.

    // Set up a container
    Tomcat tomcat = getTomcatInstance();
    tomcat.start();
    // To not start Context automatically, as we have to configure it first
    ((ContainerBase) tomcat.getHost()).setStartChildren(false);

    FailingLifecycleListener listener = new FailingLifecycleListener();
    File root = new File("test/webapp-3.0");
    Context context = tomcat.addWebapp("", root.getAbsolutePath());
    context.addLifecycleListener(listener);

    try {
      context.start();
      fail();
    } catch (LifecycleException ex) {
      // As expected
    }
    assertEquals(LifecycleState.FAILED, context.getState());

    // The second attempt
    listener.setFail(false);
    context.start();
    assertEquals(LifecycleState.STARTED, context.getState());

    // Using a test from testBug49922() to check that the webapp is running
    ByteChunk result = getUrl("http://localhost:" + getPort() + "/bug49922/target");
    assertEquals("Target", result.toString());
  }
  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 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());
  }
Beispiel #21
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);
      }
    }
  }
  @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 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());
    }
Beispiel #24
0
 public static void main(String[] args) throws Exception {
   Tomcat tomcat = new Tomcat();
   tomcat.addWebapp("/", Paths.get("src/main/webapp").toAbsolutePath().toString());
   tomcat.start();
   System.out.println("http://localhost:8080/rest/hello");
   System.in.read();
   tomcat.stop();
 }
 /** Is this instance running? */
 public boolean isRunning() {
   return tomcat != null
       && tomcat.getServer().getState().isAvailable()
       && tomcat
           .getServer()
           .getState()
           .getLifecycleEvent()
           .equals(LifecycleState.STARTED.getLifecycleEvent());
 }
  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);
  }
  @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());
  }
  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());
  }
  @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");
    }
  }