org.apache.tomcat.websocket.server.WsContextListener Java Examples

The following examples show how to use org.apache.tomcat.websocket.server.WsContextListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestSsl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testKeyPass() throws Exception {
    TesterSupport.configureClientSsl();

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    org.apache.catalina.Context ctxt  = tomcat.addWebapp(
            null, "/examples", appDir.getAbsolutePath());
    ctxt.addApplicationListener(WsContextListener.class.getName());

    TesterSupport.initSsl(tomcat, TesterSupport.LOCALHOST_KEYPASS_JKS,
            TesterSupport.JKS_PASS, TesterSupport.JKS_KEY_PASS);

    tomcat.start();
    ByteChunk res = getUrl("https://localhost:" + getPort() +
        "/examples/servlets/servlet/HelloWorldExample");
    Assert.assertTrue(res.toString().indexOf("<a href=\"../helloworld.html\">") > 0);
    Assert.assertTrue("Checking no client issuer has been requested",
            TesterSupport.getLastClientAuthRequestedIssuerCount() == 0);
}
 
Example #2
Source File: TomcatWebSocketTestServer.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
public void deployConfig(Class<? extends WebApplicationInitializer>... initializers) {

        this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));

		// Add Tomcat's DefaultServlet
		Wrapper defaultServlet = this.context.createWrapper();
		defaultServlet.setName("default");
		defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
		this.context.addChild(defaultServlet);

		// Ensure WebSocket support
		this.context.addApplicationListener(WsContextListener.class.getName());

		this.context.addServletContainerInitializer(
				new SpringServletContainerInitializer(), new HashSet<Class<?>>(Arrays.asList(initializers)));
	}
 
Example #3
Source File: TomcatWebSocketTestServer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void deployConfig(WebApplicationContext wac, Filter... filters) {
	Assert.state(this.port != -1, "setup() was never called.");
	this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));
       this.context.addApplicationListener(WsContextListener.class.getName());
	Tomcat.addServlet(this.context, "dispatcherServlet", new DispatcherServlet(wac)).setAsyncSupported(true);
	this.context.addServletMapping("/", "dispatcherServlet");
	for (Filter filter : filters) {
		FilterDef filterDef = new FilterDef();
		filterDef.setFilterName(filter.getClass().getName());
		filterDef.setFilter(filter);
		filterDef.setAsyncSupported("true");
		this.context.addFilterDef(filterDef);
		FilterMap filterMap = new FilterMap();
		filterMap.setFilterName(filter.getClass().getName());
		filterMap.addURLPattern("/*");
		filterMap.setDispatcher("REQUEST,FORWARD,INCLUDE,ASYNC");
		this.context.addFilterMap(filterMap);
	}
}
 
Example #4
Source File: TomcatWebSocketTestServer.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void deployConfig(WebApplicationContext wac, Filter... filters) {
	Assert.state(this.port != -1, "setup() was never called.");
	this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));
	this.context.addApplicationListener(WsContextListener.class.getName());
	Tomcat.addServlet(this.context, "dispatcherServlet", new DispatcherServlet(wac)).setAsyncSupported(true);
	this.context.addServletMappingDecoded("/", "dispatcherServlet");
	for (Filter filter : filters) {
		FilterDef filterDef = new FilterDef();
		filterDef.setFilterName(filter.getClass().getName());
		filterDef.setFilter(filter);
		filterDef.setAsyncSupported("true");
		this.context.addFilterDef(filterDef);
		FilterMap filterMap = new FilterMap();
		filterMap.setFilterName(filter.getClass().getName());
		filterMap.addURLPattern("/*");
		filterMap.setDispatcher("REQUEST,FORWARD,INCLUDE,ASYNC");
		this.context.addFilterMap(filterMap);
	}
}
 
Example #5
Source File: AbstractWebSocketIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Parameters(name = "client[{0}] - server [{1}]")
public static Object[][] arguments() throws IOException {

	WebSocketClient[] clients = new WebSocketClient[] {
			new TomcatWebSocketClient(),
			new JettyWebSocketClient(),
			new ReactorNettyWebSocketClient(),
			new UndertowWebSocketClient(Xnio.getInstance().createWorker(OptionMap.EMPTY))
	};

	Map<HttpServer, Class<?>> servers = new LinkedHashMap<>();
	servers.put(new TomcatHttpServer(TMP_DIR.getAbsolutePath(), WsContextListener.class), TomcatConfig.class);
	servers.put(new JettyHttpServer(), JettyConfig.class);
	servers.put(new ReactorHttpServer(), ReactorNettyConfig.class);
	servers.put(new UndertowHttpServer(), UndertowConfig.class);

	Flux<WebSocketClient> f1 = Flux.fromArray(clients).concatMap(c -> Flux.just(c).repeat(servers.size()));
	Flux<HttpServer> f2 = Flux.fromIterable(servers.keySet()).repeat(clients.length);
	Flux<Class<?>> f3 = Flux.fromIterable(servers.values()).repeat(clients.length);

	return Flux.zip(f1, f2, f3).map(Tuple3::toArray).collectList().block()
			.toArray(new Object[clients.length * servers.size()][2]);
}
 
Example #6
Source File: TomcatWebSocketTestServer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void deployConfig(WebApplicationContext wac, Filter... filters) {
	Assert.state(this.port != -1, "setup() was never called.");
	this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));
	this.context.addApplicationListener(WsContextListener.class.getName());
	Tomcat.addServlet(this.context, "dispatcherServlet", new DispatcherServlet(wac)).setAsyncSupported(true);
	this.context.addServletMappingDecoded("/", "dispatcherServlet");
	for (Filter filter : filters) {
		FilterDef filterDef = new FilterDef();
		filterDef.setFilterName(filter.getClass().getName());
		filterDef.setFilter(filter);
		filterDef.setAsyncSupported("true");
		this.context.addFilterDef(filterDef);
		FilterMap filterMap = new FilterMap();
		filterMap.setFilterName(filter.getClass().getName());
		filterMap.addURLPattern("/*");
		filterMap.setDispatcher("REQUEST,FORWARD,INCLUDE,ASYNC");
		this.context.addFilterMap(filterMap);
	}
}
 
Example #7
Source File: AbstractWebSocketIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Parameters(name = "client[{0}] - server [{1}]")
public static Object[][] arguments() throws IOException {

	WebSocketClient[] clients = new WebSocketClient[] {
			new TomcatWebSocketClient(),
			new JettyWebSocketClient(),
			new ReactorNettyWebSocketClient(),
			new UndertowWebSocketClient(Xnio.getInstance().createWorker(OptionMap.EMPTY))
	};

	Map<HttpServer, Class<?>> servers = new LinkedHashMap<>();
	servers.put(new TomcatHttpServer(TMP_DIR.getAbsolutePath(), WsContextListener.class), TomcatConfig.class);
	servers.put(new JettyHttpServer(), JettyConfig.class);
	servers.put(new ReactorHttpServer(), ReactorNettyConfig.class);
	servers.put(new UndertowHttpServer(), UndertowConfig.class);

	Flux<WebSocketClient> f1 = Flux.fromArray(clients).concatMap(c -> Flux.just(c).repeat(servers.size()));
	Flux<HttpServer> f2 = Flux.fromIterable(servers.keySet()).repeat(clients.length);
	Flux<Class<?>> f3 = Flux.fromIterable(servers.values()).repeat(clients.length);

	return Flux.zip(f1, f2, f3).map(Tuple3::toArray).collectList().block()
			.toArray(new Object[clients.length * servers.size()][2]);
}
 
Example #8
Source File: TestSsl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testSimpleSsl() throws Exception {
    TesterSupport.configureClientSsl();

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    org.apache.catalina.Context ctxt  = tomcat.addWebapp(
            null, "/examples", appDir.getAbsolutePath());
    ctxt.addApplicationListener(WsContextListener.class.getName());

    TesterSupport.initSsl(tomcat);

    tomcat.start();
    ByteChunk res = getUrl("https://localhost:" + getPort() +
        "/examples/servlets/servlet/HelloWorldExample");
    Assert.assertTrue(res.toString().indexOf("<a href=\"../helloworld.html\">") > 0);
    Assert.assertTrue("Checking no client issuer has been requested",
            TesterSupport.getLastClientAuthRequestedIssuerCount() == 0);
}
 
Example #9
Source File: TestTomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testGetResource() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    String contextPath = "/examples";

    File appDir = new File(getBuildDirectory(), "webapps" + contextPath);
    // app dir is relative to server home
    Context ctx =
        tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
    ctx.addApplicationListener(WsContextListener.class.getName());

    Tomcat.addServlet(ctx, "testGetResource", new GetResource());
    ctx.addServletMappingDecoded("/testGetResource", "testGetResource");

    tomcat.start();

    ByteChunk res = new ByteChunk();

    int rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/testGetResource", res, null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertTrue(res.toString().contains("<?xml version=\"1.0\" "));
}
 
Example #10
Source File: TestTomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testJsps() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    Context ctxt = tomcat.addWebapp(
            null, "/examples", appDir.getAbsolutePath());
    ctxt.addApplicationListener(WsContextListener.class.getName());

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() +
            "/examples/jsp/jsp2/el/basic-arithmetic.jsp");
    String text = res.toString();
    Assert.assertTrue(text, text.indexOf("<td>${(1==2) ? 3 : 4}</td>") > 0);
}
 
Example #11
Source File: TestTomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testSingleWebapp() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    Context ctxt = tomcat.addWebapp(
            null, "/examples", appDir.getAbsolutePath());
    ctxt.addApplicationListener(WsContextListener.class.getName());
    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() +
            "/examples/servlets/servlet/HelloWorldExample");
    String text = res.toString();
    Assert.assertTrue(text, text.indexOf("<a href=\"../helloworld.html\">") > 0);
}
 
Example #12
Source File: WebSocketBaseTest.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
protected Tomcat startServer(
        final Class<? extends WsContextListener> configClass)
        throws LifecycleException {

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(configClass.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    tomcat.start();
    return tomcat;
}
 
Example #13
Source File: TestSSLHostConfigIntegration.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testSslHostConfigIsSerializable() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    org.apache.catalina.Context ctxt  = tomcat.addWebapp(
            null, "/examples", appDir.getAbsolutePath());
    ctxt.addApplicationListener(WsContextListener.class.getName());

    TesterSupport.initSsl(tomcat);

    tomcat.start();

    SSLHostConfig[] sslHostConfigs =
            tomcat.getConnector().getProtocolHandler().findSslHostConfigs();

    boolean written = false;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
        for (SSLHostConfig sslHostConfig : sslHostConfigs) {
            oos.writeObject(sslHostConfig);
            written = true;
        }
    }

    Assert.assertTrue(written);
}
 
Example #14
Source File: TestCustomSsl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testCustomSslImplementation() throws Exception {

    TesterSupport.configureClientSsl();

    Tomcat tomcat = getTomcatInstance();
    Connector connector = tomcat.getConnector();

    Assume.assumeFalse("This test is only for JSSE based SSL connectors",
            connector.getProtocolHandlerClassName().contains("Apr"));

    connector.setProperty("sslImplementationName",
            "org.apache.tomcat.util.net.jsse.TesterBug50640SslImpl");

    // This setting will break ssl configuration unless the custom
    // implementation is used.
    connector.setProperty(TesterBug50640SslImpl.PROPERTY_NAME,
            TesterBug50640SslImpl.PROPERTY_VALUE);

    connector.setProperty("sslProtocol", "tls");

    File keystoreFile =
        new File(TesterSupport.LOCALHOST_RSA_JKS);
    connector.setAttribute(
            "keystoreFile", keystoreFile.getAbsolutePath());

    connector.setSecure(true);
    connector.setProperty("SSLEnabled", "true");

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    Context ctxt  = tomcat.addWebapp(
            null, "/examples", appDir.getAbsolutePath());
    ctxt.addApplicationListener(WsContextListener.class.getName());

    tomcat.start();
    ByteChunk res = getUrl("https://localhost:" + getPort() +
        "/examples/servlets/servlet/HelloWorldExample");
    Assert.assertTrue(res.toString().indexOf("<a href=\"../helloworld.html\">") > 0);
}
 
Example #15
Source File: TestFormAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private FormAuthClient(boolean clientShouldUseCookies,
        boolean clientShouldUseHttp11,
        boolean serverShouldUseCookies,
        boolean serverShouldChangeSessid) throws Exception {

    this.clientShouldUseHttp11 = clientShouldUseHttp11;

    Tomcat tomcat = getTomcatInstance();
    File appDir = new File(System.getProperty("tomcat.test.basedir"), "webapps/examples");
    Context ctx = tomcat.addWebapp(null, "/examples",
            appDir.getAbsolutePath());
    setUseCookies(clientShouldUseCookies);
    ctx.setCookies(serverShouldUseCookies);
    ctx.addApplicationListener(WsContextListener.class.getName());

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

    tomcat.start();

    // 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());
}
 
Example #16
Source File: TomcatWebSocketTestServer.java    From bearchoke with Apache License 2.0 5 votes vote down vote up
@Override
public void deployConfig(WebApplicationContext cxt) {
	this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));
	this.context.addApplicationListener(WsContextListener.class.getName());
	Tomcat.addServlet(context, "dispatcherServlet", new DispatcherServlet(cxt));
	this.context.addServletMapping("/", "dispatcherServlet");
}
 
Example #17
Source File: TestMapperWebapps.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testContextReload_Bug56658_Bug56882() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    org.apache.catalina.Context ctxt  = tomcat.addWebapp(
            null, "/examples", appDir.getAbsolutePath());
    ctxt.addApplicationListener(WsContextListener.class.getName());
    tomcat.start();

    // The tests are from TestTomcat#testSingleWebapp(), #testJsps()
    // We reload the context and verify that the pages are still accessible
    ByteChunk res;
    String text;

    res = getUrl("http://localhost:" + getPort()
            + "/examples/servlets/servlet/HelloWorldExample");
    text = res.toString();
    Assert.assertTrue(text, text.contains("<a href=\"../helloworld.html\">"));

    res = getUrl("http://localhost:" + getPort()
            + "/examples/jsp/jsp2/el/basic-arithmetic.jsp");
    text = res.toString();
    Assert.assertTrue(text, text.contains("<td>${(1==2) ? 3 : 4}</td>"));

    res = getUrl("http://localhost:" + getPort() + "/examples/index.html");
    text = res.toString();
    Assert.assertTrue(text, text.contains("<title>Apache Tomcat Examples</title>"));

    long timeA = System.currentTimeMillis();
    res = getUrl("http://localhost:" + getPort()
            + "/examples/jsp/include/include.jsp");
    String timestamp = findCommonPrefix(timeA, System.currentTimeMillis());
    text = res.toString();
    Assert.assertTrue(text, text.contains(
            "In place evaluation of another JSP which gives you the current time: " + timestamp));
    Assert.assertTrue(text, text.contains(
            "To get the current time in ms"));
    Assert.assertTrue(text, text.contains(
            "by including the output of another JSP: " + timestamp));
    Assert.assertTrue(text, text.contains(":-)"));

    res = getUrl("http://localhost:" + getPort()
            + "/examples/jsp/forward/forward.jsp");
    text = res.toString();
    Assert.assertTrue(text, text.contains("VM Memory usage"));

    ctxt.reload();

    res = getUrl("http://localhost:" + getPort()
            + "/examples/servlets/servlet/HelloWorldExample");
    text = res.toString();
    Assert.assertTrue(text, text.contains("<a href=\"../helloworld.html\">"));

    res = getUrl("http://localhost:" + getPort()
            + "/examples/jsp/jsp2/el/basic-arithmetic.jsp");
    text = res.toString();
    Assert.assertTrue(text, text.contains("<td>${(1==2) ? 3 : 4}</td>"));

    res = getUrl("http://localhost:" + getPort() + "/examples/index.html");
    text = res.toString();
    Assert.assertTrue(text, text.contains("<title>Apache Tomcat Examples</title>"));

    timeA = System.currentTimeMillis();
    res = getUrl("http://localhost:" + getPort()
            + "/examples/jsp/include/include.jsp");
    timestamp = findCommonPrefix(timeA, System.currentTimeMillis());
    text = res.toString();
    Assert.assertTrue(text, text.contains(
            "In place evaluation of another JSP which gives you the current time: " + timestamp));
    Assert.assertTrue(text, text.contains(
            "To get the current time in ms"));
    Assert.assertTrue(text, text.contains(
            "by including the output of another JSP: " + timestamp));
    Assert.assertTrue(text, text.contains(":-)"));

    res = getUrl("http://localhost:" + getPort()
            + "/examples/jsp/forward/forward.jsp");
    text = res.toString();
    Assert.assertTrue(text, text.contains("VM Memory usage"));
}
 
Example #18
Source File: TestWebdavServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testGetWithSubpathmount() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    String contextPath = "/examples";

    File appDir = new File(getBuildDirectory(), "webapps" + contextPath);
    // app dir is relative to server home
    org.apache.catalina.Context ctx =
        tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());

    Tomcat.addServlet(ctx, "webdav", new WebdavServlet());
    ctx.addServletMappingDecoded("/webdav/*", "webdav");
    ctx.addApplicationListener(WsContextListener.class.getName());

    tomcat.start();

    final ByteChunk res = new ByteChunk();

    // Make sure WebdavServlet isn't exposing special directories
    // by remounting the webapp under a sub-path

    int rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/webdav/WEB-INF/web.xml", res, null);

    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/webdav/WEB-INF/doesntexistanywhere", res, null);
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);

    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/webdav/WEB-INF/", res, null);
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);

    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/webdav/META-INF/MANIFEST.MF", res, null);
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);

    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/webdav/META-INF/doesntexistanywhere", res, null);
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);

    // Make sure WebdavServlet is serving resources
    // relative to the map/mount point
    final ByteChunk rootResource = new ByteChunk();
    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/index.html", rootResource, null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);

    final ByteChunk subpathResource = new ByteChunk();
    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/webdav/index.html", subpathResource, null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);

    Assert.assertEquals(rootResource.toString(), subpathResource.toString());

    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/webdav/static/index.html", res, null);
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);

}
 
Example #19
Source File: TestMapperListener.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testTomcatRestartListenerCount_Bug56717() throws IOException,
        LifecycleException {
    // The test runs Tomcat twice, tests that it has started successfully,
    // and compares the counts of listeners registered on containers
    // after the first and the second starts.
    // Sample request is from TestTomcat#testSingleWebapp()

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    Context ctxt = tomcat.addWebapp(null, "/examples",
            appDir.getAbsolutePath());
    ctxt.addApplicationListener(WsContextListener.class.getName());
    tomcat.start();

    ByteChunk res;
    String text;
    res = getUrl("http://localhost:" + getPort()
            + "/examples/servlets/servlet/HelloWorldExample");
    text = res.toString();
    Assert.assertTrue(text, text.contains("<a href=\"../helloworld.html\">"));

    List<ListenersInfo> listenersFirst = new ArrayList<>();
    populateListenersInfo(listenersFirst, tomcat.getEngine());

    tomcat.stop();
    tomcat.start();

    res = getUrl("http://localhost:" + getPort()
            + "/examples/servlets/servlet/HelloWorldExample");
    text = res.toString();
    Assert.assertTrue(text, text.contains("<a href=\"../helloworld.html\">"));

    List<ListenersInfo> listenersSecond = new ArrayList<>();
    populateListenersInfo(listenersSecond, tomcat.getEngine());

    Assert.assertEquals(listenersFirst.size(), listenersSecond.size());
    for (int i = 0, len = listenersFirst.size(); i < len; i++) {
        ListenersInfo a = listenersFirst.get(i);
        ListenersInfo b = listenersSecond.get(i);
        boolean equal = a.container.getClass() == b.container.getClass()
                && a.containerListeners.length == b.containerListeners.length
                && a.lifecycleListeners.length == b.lifecycleListeners.length;
        if (!equal) {
            Assert.fail("The lists of listeners differ:\n" + a + "\n" + b);
        }
    }
}
 
Example #20
Source File: TestDefaultServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testGetWithSubpathmount() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    String contextPath = "/examples";

    File appDir = new File(getBuildDirectory(), "webapps" + contextPath);
    // app dir is relative to server home
    org.apache.catalina.Context ctx =
        tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
    ctx.addApplicationListener(WsContextListener.class.getName());

    // Override the default servlet with our own mappings
    Tomcat.addServlet(ctx, "default2", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default2");
    ctx.addServletMappingDecoded("/servlets/*", "default2");
    ctx.addServletMappingDecoded("/static/*", "default2");

    tomcat.start();

    final ByteChunk res = new ByteChunk();

    // Make sure DefaultServlet isn't exposing special directories
    // by remounting the webapp under a sub-path

    int rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/static/WEB-INF/web.xml", res, null);

    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/static/WEB-INF/doesntexistanywhere", res, null);
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);

    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);
    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/static/WEB-INF/", res, null);
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);

    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/static/META-INF/MANIFEST.MF", res, null);
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);

    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/static/META-INF/doesntexistanywhere", res, null);
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);

    // Make sure DefaultServlet is serving resources relative to the
    // context root regardless of where the it is mapped

    final ByteChunk rootResource = new ByteChunk();
    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/index.html", rootResource, null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);

    final ByteChunk subpathResource = new ByteChunk();
    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/servlets/index.html", subpathResource, null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);

    Assert.assertFalse(rootResource.toString().equals(subpathResource.toString()));

    rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/static/index.html", res, null);
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc);

}