@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 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()); }
@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()); }
@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()); }
@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"); }
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()); }
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()); }
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); }
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); }
@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."); } }
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()); }
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())); }
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()); }
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()); }
@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"); }
@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); } } }
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 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 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()); }
@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 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"); } }
@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()); }
@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(); }
@Test public void testSessionExpirySession() 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); Session s1a = connectToEchoServer(wsContainer, EndpointA.class, TesterEchoServer.Config.PATH_BASIC); s1a.setMaxIdleTimeout(3000); Session s2a = connectToEchoServer(wsContainer, EndpointA.class, TesterEchoServer.Config.PATH_BASIC); s2a.setMaxIdleTimeout(6000); Session s3a = connectToEchoServer(wsContainer, EndpointA.class, TesterEchoServer.Config.PATH_BASIC); s3a.setMaxIdleTimeout(9000); // Check all three sessions are open Set<Session> setA = s3a.getOpenSessions(); int expected = 3; while (expected > 0) { Assert.assertEquals(expected, getOpenCount(setA)); int count = 0; while (getOpenCount(setA) == expected && count < 5) { count++; Thread.sleep(1000); } expected--; } Assert.assertEquals(0, getOpenCount(setA)); }
private void pathParamExtenionTest(String path, String expected) throws Exception { // Setup Tomcat instance Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("/testapp", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(ctx, "servlet", new PathParamServlet()); ctx.addServletMapping("*.txt", "servlet"); tomcat.start(); ByteChunk res = getUrl("http://localhost:" + getPort() + path); Assert.assertEquals(expected, res.toString()); }